code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import os
import shutil
import csv
import random
class bms_config:
arch = 'Vnet'
# data
data = '/mnt/dataset/shared/zongwei/BraTS'
csv = "data/bms"
deltr = 30
input_rows = 64
input_cols = 64
input_deps = 32
crop_rows = 100
crop_cols = 100
crop_deps = 50
# mode... | [
"csv.reader",
"os.makedirs",
"random.Random",
"os.path.exists",
"os.path.join"
] | [((2542, 2579), 'os.path.join', 'os.path.join', (['self.model_path', '"""logs"""'], {}), "(self.model_path, 'logs')\n", (2554, 2579), False, 'import os\n'), ((5452, 5489), 'os.path.join', 'os.path.join', (['self.model_path', '"""logs"""'], {}), "(self.model_path, 'logs')\n", (5464, 5489), False, 'import os\n'), ((8155,... |
"""Generates a gin config from the current task/mixture list.
Usage: `python3 -m config.generate`
"""
from itertools import chain, product
from pathlib import Path
import t5
import conversational_ai.tasks # noqa: F401
WHITELIST = ["chitchat", "dailydialog", "convai2"]
sizes = ["small", "base", "large", "3b", "11b... | [
"t5.data.TaskRegistry.names",
"pathlib.Path",
"t5.data.MixtureRegistry.names",
"itertools.product"
] | [((498, 522), 'itertools.product', 'product', (['sizes', 'mixtures'], {}), '(sizes, mixtures)\n', (505, 522), False, 'from itertools import chain, product\n'), ((535, 582), 'pathlib.Path', 'Path', (['f"""./config/mixtures/{mixture}/{size}.gin"""'], {}), "(f'./config/mixtures/{mixture}/{size}.gin')\n", (539, 582), False... |
from super_taxi.model.generics import Vehicle, Coordinate
from super_taxi.model.cars import Car,SUVCar
class Taxi(Vehicle):
def __init__(self, id=None):
Vehicle.__init__(self, id=id)
self.position = Coordinate(0, 0)
self.ride = None
self.booked = False
self.pickup_distance ... | [
"super_taxi.model.cars.SUVCar.__init__",
"super_taxi.model.generics.Vehicle.__init__",
"super_taxi.model.cars.Car.__init__",
"super_taxi.model.generics.Coordinate"
] | [((167, 196), 'super_taxi.model.generics.Vehicle.__init__', 'Vehicle.__init__', (['self'], {'id': 'id'}), '(self, id=id)\n', (183, 196), False, 'from super_taxi.model.generics import Vehicle, Coordinate\n'), ((221, 237), 'super_taxi.model.generics.Coordinate', 'Coordinate', (['(0)', '(0)'], {}), '(0, 0)\n', (231, 237),... |
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | [
"airflow.exceptions.AirflowException"
] | [((3382, 3473), 'airflow.exceptions.AirflowException', 'AirflowException', (['"""Cannot get URL: No valid MS Teams webhook URL nor conn_id supplied"""'], {}), "(\n 'Cannot get URL: No valid MS Teams webhook URL nor conn_id supplied')\n", (3398, 3473), False, 'from airflow.exceptions import AirflowException\n')] |
import numpy as np
#import matplotlib.pyplot as plt
import shapely.geometry
from scipy.ndimage.morphology import binary_dilation
from scipy.ndimage import label
from multiprocessing import Pool
def voxels_to_polygon(image_stack, pixel_size, center=(0.5, 0.5)):
"""Take a stack of images and produce a stack of shap... | [
"numpy.radians",
"numpy.sum",
"scipy.ndimage.morphology.binary_dilation",
"numpy.zeros",
"numpy.ones",
"numpy.min",
"numpy.where",
"numpy.max",
"numpy.array",
"multiprocessing.Pool",
"numpy.alltrue",
"numpy.linalg.norm",
"numpy.sqrt",
"numpy.repeat"
] | [((1932, 1950), 'numpy.alltrue', 'np.alltrue', (['(s <= 2)'], {}), '(s <= 2)\n', (1942, 1950), True, 'import numpy as np\n'), ((2742, 2774), 'numpy.repeat', 'np.repeat', (['image', 'factor'], {'axis': '(1)'}), '(image, factor, axis=1)\n', (2751, 2774), True, 'import numpy as np\n'), ((2796, 2837), 'numpy.repeat', 'np.r... |
#!/usr/bin/env python3
""" rcrr_instr.py
Implementation of RCRR format instructions.
"""
from pyvex.lifting.util import Type, Instruction
import bitstring
from .logger import log_this
class RCRR_Instructions(Instruction):
""" Insert Bit Field instruction.
op = 0x97
op2 = 0x00 3-bit
User S... | [
"pyvex.lifting.util.Instruction.parse"
] | [((568, 600), 'pyvex.lifting.util.Instruction.parse', 'Instruction.parse', (['self', 'bitstrm'], {}), '(self, bitstrm)\n', (585, 600), False, 'from pyvex.lifting.util import Type, Instruction\n')] |
import panel as pn
import holoviews as hv
from earthsim.grabcut import GrabCutPanel, SelectRegionPanel
from adhui import CreateMesh, ConceptualModelEditor
hv.extension('bokeh')
stages = [
('Select Region', SelectRegionPanel),
('Grabcut', GrabCutPanel),
('Path Editor', ConceptualModelEditor),
('Mesh',... | [
"panel.pipeline.Pipeline",
"holoviews.extension"
] | [((156, 177), 'holoviews.extension', 'hv.extension', (['"""bokeh"""'], {}), "('bokeh')\n", (168, 177), True, 'import holoviews as hv\n'), ((369, 409), 'panel.pipeline.Pipeline', 'pn.pipeline.Pipeline', (['stages'], {'debug': '(True)'}), '(stages, debug=True)\n', (389, 409), True, 'import panel as pn\n')] |
import unittest
from etk.extractors.language_identification_extractor import LanguageIdentificationExtractor
class TestLanguageIdentificationExtractor(unittest.TestCase):
def test_langid(self):
extractor = LanguageIdentificationExtractor()
text_en = "langid.py comes pre-trained on 97 languages (I... | [
"unittest.main",
"etk.extractors.language_identification_extractor.LanguageIdentificationExtractor"
] | [((1663, 1678), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1676, 1678), False, 'import unittest\n'), ((220, 253), 'etk.extractors.language_identification_extractor.LanguageIdentificationExtractor', 'LanguageIdentificationExtractor', ([], {}), '()\n', (251, 253), False, 'from etk.extractors.language_identifica... |
# We expect the arccos of 1 to be 0, and of -1 to be pi:
np.arccos([1, -1])
# array([ 0. , 3.14159265])
# Plot arccos:
import matplotlib.pyplot as plt
x = np.linspace(-1, 1, num=100)
plt.plot(x, np.arccos(x))
plt.axis('tight')
plt.show()
| [
"matplotlib.pyplot.show",
"matplotlib.pyplot.axis"
] | [((220, 237), 'matplotlib.pyplot.axis', 'plt.axis', (['"""tight"""'], {}), "('tight')\n", (228, 237), True, 'import matplotlib.pyplot as plt\n'), ((238, 248), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (246, 248), True, 'import matplotlib.pyplot as plt\n')] |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import copy
import os
import datetime
import time
from functools import reduce
# Function that provide some information about the cvs files
def infos(old_df_names, months):
"""
Print informations about databases
... | [
"matplotlib.pyplot.title",
"pandas.DataFrame",
"matplotlib.pyplot.show",
"numpy.sum",
"matplotlib.pyplot.plot",
"pandas.read_csv",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.legend",
"pandas.merge",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.barh",
"matplotlib.pyplot.figure",
"numpy.m... | [((2627, 2639), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2637, 2639), True, 'import matplotlib.pyplot as plt\n'), ((2687, 2717), 'matplotlib.pyplot.bar', 'plt.bar', (['X', 'average_session_df'], {}), '(X, average_session_df)\n', (2694, 2717), True, 'import matplotlib.pyplot as plt\n'), ((2798, 2841)... |
# Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import mock
from services import parameters
from services import resultdb
from waterfall.test import wf_testcase
from go.chromium.org.luci.resultdb.proto.v1... | [
"mock.patch.object",
"services.parameters.TestFailedStep",
"services.resultdb_util.get_failed_tests_in_step",
"go.chromium.org.luci.resultdb.proto.v1.common_pb2.StringPair"
] | [((533, 630), 'mock.patch.object', 'mock.patch.object', (['swarming_util', '"""GetInvocationNameForSwarmingTask"""'], {'return_value': '"""inv_name"""'}), "(swarming_util, 'GetInvocationNameForSwarmingTask',\n return_value='inv_name')\n", (550, 630), False, 'import mock\n'), ((649, 694), 'mock.patch.object', 'mock.p... |
#!/usr/bin/env python
#
# Copyright (c) 2017-2018 Via Technology Ltd. All Rights Reserved.
# Consult your license regarding permissions and restrictions.
"""
Software to read Eurocontrol APDS files.
"""
import sys
import os
import bz2
import csv
import errno
import pandas as pd
from enum import IntEnum, unique
from p... | [
"pandas.DataFrame",
"pru.trajectory_fields.has_bz2_extension",
"csv.reader",
"pru.logger.logger",
"os.path.basename",
"pandas.read_csv",
"pru.trajectory_fields.is_valid_iso8601_date",
"pru.trajectory_files.create_convert_apds_filenames",
"bz2.open",
"pru.trajectory_fields.iso8601_datetime_parser",... | [((619, 635), 'pru.logger.logger', 'logger', (['__name__'], {}), '(__name__)\n', (625, 635), False, 'from pru.logger import logger\n'), ((5734, 5748), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (5746, 5748), True, 'import pandas as pd\n'), ((7064, 7118), 'pru.trajectory_files.create_convert_apds_filenames', ... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
import io
import os
import re
import sys
import json
#import copy
import codecs
#reload(sys)
#sys.setdefaultencoding('UTF-8')
DEBUG_MODE = False
CIN_HEAD = "%gen_inp"
ENAME_HEAD = "%ename"
CNAME_HEAD = "%cname"
ENCODI... | [
"os.makedirs",
"codecs.open",
"os.path.dirname",
"os.path.exists",
"io.open",
"os.path.join",
"re.sub"
] | [((10624, 10668), 'os.path.join', 'os.path.join', (['self.curdir', 'os.pardir', '"""json"""'], {}), "(self.curdir, os.pardir, 'json')\n", (10636, 10668), False, 'import os\n'), ((10685, 10731), 'os.makedirs', 'os.makedirs', (['json_dir'], {'mode': '(448)', 'exist_ok': '(True)'}), '(json_dir, mode=448, exist_ok=True)\n'... |
from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from django.views.generic import DetailView, TemplateView
from d... | [
"playoffs.models.Playoff.objects.filter",
"django.contrib.auth.models.User.objects.create_user",
"django.shortcuts.get_object_or_404",
"django.contrib.auth.authenticate",
"django.contrib.auth.login"
] | [((687, 736), 'django.contrib.auth.models.User.objects.create_user', 'User.objects.create_user', (['name'], {'password': 'password'}), '(name, password=password)\n', (711, 736), False, 'from django.contrib.auth.models import User\n'), ((756, 802), 'django.contrib.auth.authenticate', 'authenticate', ([], {'username': 'n... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 7 16:12:33 2016
@author: rmcleod
"""
import numpy as np
import matplotlib.pyplot as plt
import os, os.path, glob
mcFRCFiles = glob.glob( "FRC/*mcFRC.npy" )
zorroFRCFiles = glob.glob( "FRC/*zorroFRC.npy" )
zorroFRCs = [None] * len( zorroFRCFiles)
for J in np.arange( ... | [
"matplotlib.pyplot.title",
"numpy.load",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"numpy.array",
"glob.glob",
"matplotlib.pyplot.savefig"
] | [((177, 204), 'glob.glob', 'glob.glob', (['"""FRC/*mcFRC.npy"""'], {}), "('FRC/*mcFRC.npy')\n", (186, 204), False, 'import os, os.path, glob\n'), ((223, 253), 'glob.glob', 'glob.glob', (['"""FRC/*zorroFRC.npy"""'], {}), "('FRC/*zorroFRC.npy')\n", (232, 253), False, 'import os, os.path, glob\n'), ((621, 633), 'matplotli... |
# -*- coding: utf-8 -*-
"""
ArduinoMediator.
@auteur: Darkness4
"""
import logging
from threading import Thread
from time import sleep, time
from typing import Optional
from csgo_gsi_arduino_lcd.entities.state import State
from csgo_gsi_arduino_lcd.entities.status import Status
from serial import Serial
class Ardui... | [
"logging.info",
"time.sleep",
"time.time"
] | [((1144, 1178), 'logging.info', 'logging.info', (['"""Messenger is dead."""'], {}), "('Messenger is dead.')\n", (1156, 1178), False, 'import logging\n'), ((1661, 1667), 'time.time', 'time', ([], {}), '()\n', (1665, 1667), False, 'from time import sleep, time\n'), ((2893, 2903), 'time.sleep', 'sleep', (['(0.1)'], {}), '... |
import numpy as np
from pyutai import trees
from potentials import cluster
def cpd_size(cpd):
return np.prod(cpd.cardinality)
def unique_values(cpd):
unique, _ = np.unique(cpd.values, return_counts=True)
return len(unique)
def stats(net):
if not net.endswith('.bif'):
raise ValueError('Net ... | [
"numpy.unique",
"pyutai.trees.Tree.from_array",
"numpy.prod",
"potentials.cluster.Cluster.from_array"
] | [((107, 131), 'numpy.prod', 'np.prod', (['cpd.cardinality'], {}), '(cpd.cardinality)\n', (114, 131), True, 'import numpy as np\n'), ((174, 215), 'numpy.unique', 'np.unique', (['cpd.values'], {'return_counts': '(True)'}), '(cpd.values, return_counts=True)\n', (183, 215), True, 'import numpy as np\n'), ((978, 1064), 'pyu... |
import os
import threading
from PyQt5 import QtCore
from PyQt5.QtCore import QObject
from src.Apps import Apps
from src.model.Music import Music
from src.model.MusicList import MusicList
from src.service.MP3Parser import MP3
class ScanPaths(QObject, threading.Thread):
""" 异步扫描指定目录(指配置文件)下的所有音乐文件, 并写入数据库 """
... | [
"PyQt5.QtCore.pyqtSignal",
"src.Apps.Apps.musicService.batch_insert",
"os.path.basename",
"os.path.isdir",
"os.path.getsize",
"os.path.exists",
"src.model.Music.Music",
"src.service.MP3Parser.MP3",
"os.path.join",
"os.listdir"
] | [((370, 392), 'PyQt5.QtCore.pyqtSignal', 'QtCore.pyqtSignal', (['int'], {}), '(int)\n', (387, 392), False, 'from PyQt5 import QtCore\n'), ((889, 927), 'src.Apps.Apps.musicService.batch_insert', 'Apps.musicService.batch_insert', (['musics'], {}), '(musics)\n', (919, 927), False, 'from src.Apps import Apps\n'), ((3317, 3... |
#!/usr/bin/env python3
import argparse
import cairo
import parse_test
import subprocess
import typing
def hue_to_rgb(hue: float, lo: float) -> typing.Tuple[float, float, float]:
hue = max(0, min(1, hue))
if hue <= 1/3:
return (1 - (1-lo)*(hue-0)*3, lo + (1-lo)*(hue-0)*3, lo)
if hue <= 2/3:
... | [
"subprocess.run",
"argparse.ArgumentParser",
"cairo.Context",
"parse_test.TestParser",
"cairo.PDFSurface",
"argparse.FileType"
] | [((980, 1002), 'cairo.Context', 'cairo.Context', (['surface'], {}), '(surface)\n', (993, 1002), False, 'import cairo\n'), ((6675, 6768), 'subprocess.run', 'subprocess.run', (["['git', 'rev-parse', 'HEAD']"], {'capture_output': '(True)', 'check': '(True)', 'text': '(True)'}), "(['git', 'rev-parse', 'HEAD'], capture_outp... |
import os
import logging
import json
import asyncio
from collections import defaultdict
import nacl
from quart import Quart, jsonify, request, websocket
from quart_cors import cors
from blockchat.utils import encryption
from blockchat.types.blockchain import Blockchain, BlockchatJSONEncoder, BlockchatJSONDecoder
from... | [
"argparse.ArgumentParser",
"quart.websocket.args.get",
"collections.defaultdict",
"quart.Quart",
"quart.websocket.accept",
"blockchat.utils.storage.FirebaseBlockchatStorage",
"blockchat.types.blockchain.parse_node_addr",
"blockchat.types.blockchain.Blockchain",
"quart.request.args.get",
"logging.w... | [((603, 643), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'numeric_level'}), '(level=numeric_level)\n', (622, 643), False, 'import logging\n'), ((674, 689), 'quart.Quart', 'Quart', (['__name__'], {}), '(__name__)\n', (679, 689), False, 'from quart import Quart, jsonify, request, websocket\n'), ((696, 7... |
from reinforcement.agents.td_agent import TDAgent
from reinforcement.models.q_regression_model import QRegressionModel
from reinforcement.policies.e_greedy_policies import NormalEpsilonGreedyPolicy
from reinforcement.reward_functions.q_neuronal import QNeuronal
from unityagents import UnityEnvironment
import tensorflow... | [
"reinforcement.policies.e_greedy_policies.NormalEpsilonGreedyPolicy",
"tensorflow.Session",
"reinforcement.models.q_regression_model.QRegressionModel",
"reinforcement.agents.td_agent.TDAgent",
"unity_session.UnitySession",
"reinforcement.reward_functions.q_neuronal.QNeuronal",
"unityagents.UnityEnvironm... | [((594, 634), 'unityagents.UnityEnvironment', 'UnityEnvironment', ([], {'file_name': 'UNITY_BINARY'}), '(file_name=UNITY_BINARY)\n', (610, 634), False, 'from unityagents import UnityEnvironment\n'), ((643, 655), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (653, 655), True, 'import tensorflow as tf\n'), ((716,... |
import torch
import torch.nn as nn
from .layer import *
##### U^2-Net ####
class U2NET(nn.Module):
'''
详细见U2Net论文(md中有链接)
'''
def __init__(self, in_channels=1, out_channels=3):
super(U2NET, self).__init__()
self.stage1 = RSU7(in_channels, 32, 64)
self.pool12 = nn.MaxPool2d(2,... | [
"torch.nn.MaxPool2d",
"torch.nn.Conv2d",
"torch.cat"
] | [((305, 346), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', (['(2)'], {'stride': '(2)', 'ceil_mode': '(True)'}), '(2, stride=2, ceil_mode=True)\n', (317, 346), True, 'import torch.nn as nn\n'), ((410, 451), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', (['(2)'], {'stride': '(2)', 'ceil_mode': '(True)'}), '(2, stride=2, ceil_mode=True)... |
import os,sys
import datetime as dt
import numpy as np
try:
#for python 3.0 or later
from urllib.request import urlopen
except ImportError:
#Fall back to python 2 urllib2
from urllib2 import urlopen
import requests
from multiprocessing import Pool
import drms
from shutil import move
import glob
###Rem... | [
"sys.stdout.write",
"numpy.size",
"requests.head",
"os.makedirs",
"os.path.exists",
"datetime.datetime.strptime",
"datetime.timedelta",
"drms.Client",
"urllib2.urlopen",
"sys.exit"
] | [((3268, 3306), 'datetime.datetime.strptime', 'dt.datetime.strptime', (['time', '"""%Y/%m/%d"""'], {}), "(time, '%Y/%m/%d')\n", (3288, 3306), True, 'import datetime as dt\n'), ((6072, 6086), 'urllib2.urlopen', 'urlopen', (['inurl'], {}), '(inurl)\n', (6079, 6086), False, 'from urllib2 import urlopen\n'), ((7346, 7390),... |
from .regex_patterns import *
from bs4 import BeautifulSoup
import datetime
import re
def parse(response, option):
"""
Function to extract data from html schedule
:return: Parsed html in dictionary
"""
soup = BeautifulSoup(response.content, 'html.parser')
title_blue_original = soup.find("fon... | [
"bs4.BeautifulSoup",
"datetime.date",
"re.match",
"datetime.timedelta"
] | [((232, 278), 'bs4.BeautifulSoup', 'BeautifulSoup', (['response.content', '"""html.parser"""'], {}), "(response.content, 'html.parser')\n", (245, 278), False, 'from bs4 import BeautifulSoup\n'), ((3508, 3566), 'datetime.date', 'datetime.date', ([], {'year': 'items[2]', 'month': 'items[1]', 'day': 'items[0]'}), '(year=i... |
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | [
"tensorflow.keras.models.Model",
"research.mobilenet.common_modules.mobilenet_base",
"logging.basicConfig",
"research.mobilenet.common_modules.mobilenet_head"
] | [((1708, 1756), 'research.mobilenet.common_modules.mobilenet_base', 'common_modules.mobilenet_base', (['img_input', 'config'], {}), '(img_input, config)\n', (1737, 1756), False, 'from research.mobilenet import common_modules\n'), ((1794, 1834), 'research.mobilenet.common_modules.mobilenet_head', 'common_modules.mobilen... |
from unittest.mock import MagicMock
import pytest
from seqal.stoppers import BudgetStopper, F1Stopper
class TestF1Stopper:
"""Test F1Stopper class"""
@pytest.mark.parametrize(
"micro,micro_score,macro,macro_score,expected",
[
(True, 16, False, 0, True),
(True, 14, Fa... | [
"seqal.stoppers.F1Stopper",
"pytest.mark.parametrize",
"seqal.stoppers.BudgetStopper",
"unittest.mock.MagicMock"
] | [((164, 360), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""micro,micro_score,macro,macro_score,expected"""', '[(True, 16, False, 0, True), (True, 14, False, 0, False), (False, 0, True, \n 16, True), (False, 0, True, 14, False)]'], {}), "('micro,micro_score,macro,macro_score,expected', [(\n True, 16... |
"""Candid Covariance-Free Incremental PCA (CCIPCA)."""
import numpy as np
from scipy import linalg
from sklearn.utils import check_array
from sklearn.utils.validation import FLOAT_DTYPES
from sklearn.base import BaseEstimator
from sklearn.preprocessing import normalize
import copy
class CCIPCA(BaseEstimat... | [
"sklearn.utils.check_array",
"numpy.zeros",
"numpy.expand_dims",
"sklearn.preprocessing.normalize",
"numpy.dot"
] | [((1416, 1466), 'sklearn.utils.check_array', 'check_array', (['X'], {'dtype': 'FLOAT_DTYPES', 'copy': 'self.copy'}), '(X, dtype=FLOAT_DTYPES, copy=self.copy)\n', (1427, 1466), False, 'from sklearn.utils import check_array\n'), ((3110, 3155), 'sklearn.utils.check_array', 'check_array', (['X'], {'copy': 'copy', 'dtype': ... |
import pymongo
"""
mongo数据库的增删改查
1.首先本地启动mongodb: docker-compose -f second_step/example/mongo.yml up
2.运行以下命令
python.exe .\second_step\s7.py
参考:https://www.runoob.com/python3/python-mongodb.html
"""
class Model:
def __init__(self):
client = pymongo.MongoClient("mongodb://localhost:27017")
self.db... | [
"pymongo.MongoClient"
] | [((256, 304), 'pymongo.MongoClient', 'pymongo.MongoClient', (['"""mongodb://localhost:27017"""'], {}), "('mongodb://localhost:27017')\n", (275, 304), False, 'import pymongo\n')] |
from yaga_ga.evolutionary_algorithm.genes import IntGene, CharGene
from yaga_ga.evolutionary_algorithm.individuals import (
MixedIndividualStructure,
)
def test_initialization_with_tuple():
gene_1 = CharGene()
gene_2 = IntGene(lower_bound=1, upper_bound=1)
individual = MixedIndividualStructure((gene_1... | [
"yaga_ga.evolutionary_algorithm.genes.CharGene",
"yaga_ga.evolutionary_algorithm.individuals.MixedIndividualStructure",
"yaga_ga.evolutionary_algorithm.genes.IntGene"
] | [((209, 219), 'yaga_ga.evolutionary_algorithm.genes.CharGene', 'CharGene', ([], {}), '()\n', (217, 219), False, 'from yaga_ga.evolutionary_algorithm.genes import IntGene, CharGene\n'), ((233, 270), 'yaga_ga.evolutionary_algorithm.genes.IntGene', 'IntGene', ([], {'lower_bound': '(1)', 'upper_bound': '(1)'}), '(lower_bou... |
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import cv2,time,os
from moviepy.editor import *
from tkinter import filedialog as fd
def im_to_ascii(im:Image,width:int=640,keepAlpha:bool=True,highContrastMode:bool=False,fontResolution:int=5):
ratio:float = width/im.size[0]
... | [
"PIL.Image.new",
"cv2.imwrite",
"os.path.dirname",
"time.time",
"PIL.ImageFont.truetype",
"cv2.VideoCapture",
"PIL.Image.open",
"PIL.ImageDraw.Draw"
] | [((957, 1011), 'PIL.ImageFont.truetype', 'ImageFont.truetype', (['"""monogram.ttf"""', '(7 * fontResolution)'], {}), "('monogram.ttf', 7 * fontResolution)\n", (975, 1011), False, 'from PIL import ImageFont\n'), ((1025, 1060), 'PIL.Image.new', 'Image.new', (['"""RGB"""', '(w, h)', '(0, 0, 0)'], {}), "('RGB', (w, h), (0,... |
# Find the slit. This function finds the location of the slit in the photograph of the spectrum
# The function takes a single line of the data and scans it to find the maximum value.
# If it finds a block of saturated pixels it finds the middle pixel to be the slit.
# The function returns the column number of the slit.... | [
"math.sin",
"math.ceil"
] | [((880, 930), 'math.ceil', 'math.ceil', (['(0.5 * (endslit - startslit) + startslit)'], {}), '(0.5 * (endslit - startslit) + startslit)\n', (889, 930), False, 'import math\n'), ((1317, 1334), 'math.sin', 'math.sin', (['(i * res)'], {}), '(i * res)\n', (1325, 1334), False, 'import math\n')] |
import warnings
warnings.filterwarnings('ignore', category=UserWarning, append=True)
RAMS_Units=dict()
# winds
RAMS_Units['UC']='m s-1'
RAMS_Units['VC']='m s-1'
RAMS_Units['WC']='m s-1'
# potential temperature
RAMS_Units['THETA']='K'
RAMS_Units['PI']='J kg-1 K-1'
RAMS_Units['DN0']='kg m-3'
# water vapour mixing ratio... | [
"iris.coords.AuxCoord",
"warnings.filterwarnings",
"iris.cube.CubeList",
"numpy.zeros",
"iris.load",
"iris.Constraint",
"datetime.datetime",
"datetime.datetime.strptime",
"iris.load_cube",
"iris.coords.DimCoord",
"numpy.arange",
"numpy.diff",
"datetime.timedelta",
"numpy.array"
] | [((16, 84), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'category': 'UserWarning', 'append': '(True)'}), "('ignore', category=UserWarning, append=True)\n", (39, 84), False, 'import warnings\n'), ((2997, 3015), 'iris.load', 'load', (['filenames[0]'], {}), '(filenames[0])\n', (3001, 3015), F... |
from bootstrap3.renderers import FieldRenderer
from bootstrap3.text import text_value
from django.forms import CheckboxInput
from django.forms.utils import flatatt
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.utils.translation import pgettext
from i18nfield.forms i... | [
"bootstrap3.text.text_value",
"django.forms.utils.flatatt",
"django.utils.translation.pgettext"
] | [((972, 991), 'bootstrap3.text.text_value', 'text_value', (['content'], {}), '(content)\n', (982, 991), False, 'from bootstrap3.text import text_value\n'), ((802, 816), 'django.forms.utils.flatatt', 'flatatt', (['attrs'], {}), '(attrs)\n', (809, 816), False, 'from django.forms.utils import flatatt\n'), ((904, 932), 'dj... |
from src.dao.dao_aluno import DaoAluno
from tests.massa_dados import aluno_nome_1
from src.enums.enums import Situacao
from src.model.aluno import Aluno
from tests.massa_dados import materia_nome_2, materia_nome_3
class TestDaoAluno:
def _setup_aluno(self, cria_banco, id=1, nome=aluno_nome_1, cr=0,
... | [
"src.dao.dao_aluno.DaoAluno",
"src.model.aluno.Aluno"
] | [((638, 649), 'src.model.aluno.Aluno', 'Aluno', (['nome'], {}), '(nome)\n', (643, 649), False, 'from src.model.aluno import Aluno\n'), ((760, 787), 'src.dao.dao_aluno.DaoAluno', 'DaoAluno', (['aluno', 'cria_banco'], {}), '(aluno, cria_banco)\n', (768, 787), False, 'from src.dao.dao_aluno import DaoAluno\n'), ((1508, 15... |
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.views.generic import TemplateView
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.mail import send_mail
from django... | [
"django.shortcuts.render",
"django.utils.html.mark_safe",
"django.contrib.auth.get_user_model"
] | [((403, 419), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (417, 419), False, 'from django.contrib.auth import get_user_model\n'), ((731, 776), 'django.shortcuts.render', 'render', (['request', '"""core/message.html"""', 'context'], {}), "(request, 'core/message.html', context)\n", (737, 77... |
# Defines the data models used within the application
#
# See the Django documentation at https://docs.djangoproject.com/en/1.6/topics/db/models/
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.mail import send_mail
from django.db import models
from django.db.models... | [
"django.db.models.TextField",
"django.db.models.NullBooleanField",
"django.core.exceptions.ValidationError",
"django.core.urlresolvers.reverse",
"django.db.models.ForeignKey",
"django.dispatch.receiver",
"django.contrib.auth.models.User.objects.filter",
"django.db.models.DateField",
"django.db.model... | [((91807, 91845), 'django.dispatch.receiver', 'receiver', (['post_delete'], {'sender': 'Proposal'}), '(post_delete, sender=Proposal)\n', (91815, 91845), False, 'from django.dispatch import receiver\n'), ((91847, 91883), 'django.dispatch.receiver', 'receiver', (['post_save'], {'sender': 'Proposal'}), '(post_save, sender... |
# Copyright 2021, 2022 Cambridge Quantum Computing Ltd.
#
# 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 la... | [
"discopy.rigid.Diagram.tensor",
"discopy.Word",
"lambeq.core.utils.tokenised_sentence_type_check"
] | [((1659, 1672), 'discopy.Word', 'Word', (['word', 'S'], {}), '(word, S)\n', (1663, 1672), False, 'from discopy import Word\n'), ((1713, 1735), 'discopy.rigid.Diagram.tensor', 'Diagram.tensor', (['*words'], {}), '(*words)\n', (1727, 1735), False, 'from discopy.rigid import Diagram, Spider\n'), ((1195, 1234), 'lambeq.cor... |
"""PPO Agent for CRMDPs."""
import torch
import random
import numpy as np
from typing import Generator, List
from safe_grid_agents.common.utils import track_metrics
from safe_grid_agents.common.agents.policy_cnn import PPOCNNAgent
from safe_grid_agents.types import Rollout
from ai_safety_gridworlds.environments.tomat... | [
"numpy.sum",
"safe_grid_agents.types.Rollout",
"numpy.ravel",
"numpy.argsort",
"numpy.array",
"numpy.reshape",
"safe_grid_agents.common.utils.track_metrics",
"torch.no_grad",
"numpy.fromstring"
] | [((743, 757), 'numpy.sum', 'np.sum', (['(X != Y)'], {}), '(X != Y)\n', (749, 757), True, 'import numpy as np\n'), ((6632, 6648), 'numpy.array', 'np.array', (['boards'], {}), '(boards)\n', (6640, 6648), True, 'import numpy as np\n'), ((6667, 6684), 'numpy.array', 'np.array', (['rewards'], {}), '(rewards)\n', (6675, 6684... |
# Generated by Django 3.0.7 on 2021-07-13 11:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('customer', '0002_customer_address'),
]
operations = [
migrations.AlterField(
model_name='customer',
name='id',
... | [
"django.db.models.CharField",
"django.db.models.AutoField"
] | [((333, 426), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (349, 426), False, 'from django.db import migrations, models\... |
# pylint: disable=C0103
from fake_logs.fake_logs_cli import run_from_cli
# Run this module with "python fake-logs.py <arguments>"
if __name__ == "__main__":
run_from_cli()
| [
"fake_logs.fake_logs_cli.run_from_cli"
] | [((160, 174), 'fake_logs.fake_logs_cli.run_from_cli', 'run_from_cli', ([], {}), '()\n', (172, 174), False, 'from fake_logs.fake_logs_cli import run_from_cli\n')] |
"""
@author: <NAME>
@description : command dispatcher for solver
"""
# import for CommandSolverDispatcher
import uuid
from core import Details
import lib.system as system
import lib.system.time_integrators as integrator
from lib.objects import Dynamic, Kinematic, Condition, Force
from lib.objects.jit.data import Node... | [
"uuid.uuid4",
"lib.system.SolverContext",
"lib.system.Scene",
"lib.system.time_integrators.BackwardEulerIntegrator",
"core.CommandDispatcher.__init__",
"core.Details"
] | [((650, 687), 'core.CommandDispatcher.__init__', 'core.CommandDispatcher.__init__', (['self'], {}), '(self)\n', (681, 687), False, 'import core\n'), ((958, 980), 'lib.system.SolverContext', 'system.SolverContext', ([], {}), '()\n', (978, 980), True, 'import lib.system as system\n'), ((4943, 5004), 'lib.system.SolverCon... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from quotes_web.adminx import BaseAdmin
import xadmin
from .models import Quotes, Categories, Works, Writers, Speakers, Topics
class QuotesAdmin(BaseAdmin):
exclude = ('owner', 'view_nums', 'dig_nums')
xadmin.site.register(Quotes, QuotesAdmin)
c... | [
"xadmin.site.register"
] | [((275, 316), 'xadmin.site.register', 'xadmin.site.register', (['Quotes', 'QuotesAdmin'], {}), '(Quotes, QuotesAdmin)\n', (295, 316), False, 'import xadmin\n'), ((388, 435), 'xadmin.site.register', 'xadmin.site.register', (['Categories', 'CategoryAdmin'], {}), '(Categories, CategoryAdmin)\n', (408, 435), False, 'import... |
from flask import Blueprint, render_template, request, session, redirect, url_for
from pymysql import MySQLError
from datetime import date, datetime, timedelta
from dateutil.relativedelta import relativedelta
from air_ticket import conn
from air_ticket.utils import requires_login_airline_staff
mod = Blueprint('airline... | [
"flask.session.pop",
"flask.Blueprint",
"flask.redirect",
"dateutil.relativedelta.relativedelta",
"datetime.datetime.strptime",
"air_ticket.conn.commit",
"flask.render_template",
"air_ticket.conn.cursor"
] | [((302, 367), 'flask.Blueprint', 'Blueprint', (['"""airline_staff"""', '__name__'], {'url_prefix': '"""/airline_staff"""'}), "('airline_staff', __name__, url_prefix='/airline_staff')\n", (311, 367), False, 'from flask import Blueprint, render_template, request, session, redirect, url_for\n'), ((468, 511), 'flask.render... |
import just
import json
import pandas as pd
from pathlib import Path
pd.set_option('max_colwidth',300)
from encoder_decoder import TextEncoderDecoder, text_tokenize
from model import LSTMBase
TRAINING_TEST_CASES = ["from keras.layers import"]
columns_long_list = ['repo', 'path', 'url', 'code',
... | [
"encoder_decoder.TextEncoderDecoder",
"model.LSTMBase",
"pandas.read_json",
"pathlib.Path",
"pandas.set_option"
] | [((71, 105), 'pandas.set_option', 'pd.set_option', (['"""max_colwidth"""', '(300)'], {}), "('max_colwidth', 300)\n", (84, 105), True, 'import pandas as pd\n'), ((1174, 1199), 'model.LSTMBase', 'LSTMBase', (['model_name', 'ted'], {}), '(model_name, ted)\n', (1182, 1199), False, 'from model import LSTMBase\n'), ((1452, 1... |
"""Miscellaneous functions and helpers for the uclasm package."""
import numpy as np
def one_hot(idx, length):
"""Return a 1darray of zeros with a single one in the idx'th entry."""
one_hot = np.zeros(length, dtype=np.bool)
one_hot[idx] = True
return one_hot
def index_map(args):
"""Return a dict... | [
"numpy.zeros"
] | [((202, 233), 'numpy.zeros', 'np.zeros', (['length'], {'dtype': 'np.bool'}), '(length, dtype=np.bool)\n', (210, 233), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
# @Author: Administrator
# @Date: 2019-04-30 11:25:35
# @Last Modified by: Administrator
# @Last Modified time: 2019-05-26 01:25:58
"""
无 GUI 的游戏模拟器,可以模拟播放比赛记录
"""
import sys
sys.path.append("../")
from core import const as game_const
import os
import time
import json
import subprocess
im... | [
"sys.path.append",
"_lib.simulator.utils.cut_by_turn",
"json.loads",
"_lib.utils.json_load",
"os.system",
"json.dumps",
"time.sleep",
"_lib.simulator.stream.SimulatorConsoleOutputStream",
"multiprocessing.Pipe",
"multiprocessing.Process",
"os.path.join"
] | [((204, 226), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (219, 226), False, 'import sys\n'), ((674, 701), '_lib.utils.json_load', 'json_load', (['CONFIG_JSON_FILE'], {}), '(CONFIG_JSON_FILE)\n', (683, 701), False, 'from _lib.utils import json_load\n'), ((2094, 2115), '_lib.utils.json_load',... |
import json
from unittest.mock import Mock
from unittest.mock import patch
import pytest
from illumideskdummyauthenticator.authenticator import IllumiDeskDummyAuthenticator
from illumideskdummyauthenticator.validators import IllumiDeskDummyValidator
from tornado.web import RequestHandler
@pytest.mark.asyncio
async d... | [
"unittest.mock.patch.object",
"illumideskdummyauthenticator.authenticator.IllumiDeskDummyAuthenticator",
"json.dumps"
] | [((480, 567), 'unittest.mock.patch.object', 'patch.object', (['IllumiDeskDummyValidator', '"""validate_login_request"""'], {'return_value': '(True)'}), "(IllumiDeskDummyValidator, 'validate_login_request',\n return_value=True)\n", (492, 567), False, 'from unittest.mock import patch\n'), ((603, 633), 'illumideskdummy... |
# Generated by Django 2.2.4 on 2019-09-27 09:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('codebase', '0004_ticket_status'),
]
operations = [
migrations.AddField(
model_name='ticket',
name='is_closed',
... | [
"django.db.models.BooleanField"
] | [((333, 366), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)'}), '(default=True)\n', (352, 366), False, 'from django.db import migrations, models\n')] |
"""
This is the main setup file for Puck.
"""
from pathlib import Path
import subprocess
import json
import psycopg2 as pg
PUCK = Path.home().joinpath('.puck/')
print('Creating Configuration file...')
if Path.exists(PUCK):
for file in Path.iterdir(PUCK):
Path.unlink(file)
Path.rmdir(PUCK)
Path.mkdir... | [
"pathlib.Path.exists",
"json.dump",
"pathlib.Path.home",
"pathlib.Path.rmdir",
"pathlib.Path.mkdir",
"pathlib.Path.iterdir",
"pathlib.Path.unlink",
"psycopg2.connect"
] | [((207, 224), 'pathlib.Path.exists', 'Path.exists', (['PUCK'], {}), '(PUCK)\n', (218, 224), False, 'from pathlib import Path\n'), ((310, 326), 'pathlib.Path.mkdir', 'Path.mkdir', (['PUCK'], {}), '(PUCK)\n', (320, 326), False, 'from pathlib import Path\n'), ((242, 260), 'pathlib.Path.iterdir', 'Path.iterdir', (['PUCK'],... |
# Задача 8. Вариант 15.
# Доработайте игру "Анаграммы" (см. М.Доусон Программируем на Python. Гл.4) так, чтобы к каждому слову полагалась подсказка.
# Игрок должен получать право на подсказку в том случае, если у него нет никаких предположений.
# Разработайте систему начисления очков, по которой бы игроки, отгадавшие... | [
"random.choice"
] | [((563, 583), 'random.choice', 'random.choice', (['slova'], {}), '(slova)\n', (576, 583), False, 'import random\n')] |
# -*- coding: utf-8 -*-
import os
from sqlalchemy import create_engine
from sqlalchemy.engine.url import make_url
from sqlalchemy.exc import ProgrammingError
import logging
import pytest
logger = logging.getLogger(__name__)
def pytest_addoption(parser):
group = parser.getgroup('sqlalchemy')
group.addoption(... | [
"pytest.yield_fixture",
"pytest.fixture",
"sqlalchemy.create_engine",
"sqlalchemy.engine.url.make_url",
"logging.getLogger"
] | [((198, 225), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (215, 225), False, 'import logging\n'), ((666, 697), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""session"""'}), "(scope='session')\n", (680, 697), False, 'import pytest\n'), ((742, 773), 'pytest.fixture', 'pytest.fixt... |
#--------------------------------------Convert Attachment (DOC & PDF) Comments to Text---------------------------------#
#---------------------------------------------The GW Regulatory Studies Center-----------------------------------------#
#--------------------------------------------------Author: <NAME>-------------... | [
"json.dump",
"pdf2image.convert_from_path",
"os.path.abspath",
"json.dumps",
"PIL.Image.open",
"os.path.isfile",
"fitz.open",
"os.listdir"
] | [((1245, 1265), 'os.listdir', 'os.listdir', (['filePath'], {}), '(filePath)\n', (1255, 1265), False, 'import os\n'), ((3650, 3670), 'os.listdir', 'os.listdir', (['filePath'], {}), '(filePath)\n', (3660, 3670), False, 'import os\n'), ((4995, 5022), 'json.dumps', 'json.dumps', (['dic_pdfComments'], {}), '(dic_pdfComments... |
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../src')))
from card import Card, suit_num_dict, rank_num_dict
from itertools import product
deck = []
suits = []
ranks = []
for suit, rank in product(suit_num_dict.keys(),rank_num_dict.keys()):
deck.append(Card(suit,... | [
"card.rank_num_dict.keys",
"os.path.dirname",
"card.suit_num_dict.keys",
"card.Card"
] | [((250, 270), 'card.suit_num_dict.keys', 'suit_num_dict.keys', ([], {}), '()\n', (268, 270), False, 'from card import Card, suit_num_dict, rank_num_dict\n'), ((271, 291), 'card.rank_num_dict.keys', 'rank_num_dict.keys', ([], {}), '()\n', (289, 291), False, 'from card import Card, suit_num_dict, rank_num_dict\n'), ((310... |
# Copyright 2020, The TensorFlow Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | [
"absl.testing.absltest.main",
"tensorflow_privacy.privacy.privacy_tests.membership_inference_attack.models.LogisticRegressionAttacker",
"tensorflow_privacy.privacy.privacy_tests.membership_inference_attack.models.TrainedAttacker",
"numpy.array",
"tensorflow_privacy.privacy.privacy_tests.membership_inference... | [((3202, 3217), 'absl.testing.absltest.main', 'absltest.main', ([], {}), '()\n', (3215, 3217), False, 'from absl.testing import absltest\n'), ((964, 988), 'tensorflow_privacy.privacy.privacy_tests.membership_inference_attack.models.TrainedAttacker', 'models.TrainedAttacker', ([], {}), '()\n', (986, 988), False, 'from t... |
# Copyright (c) 2021, erpcloud.systems and contributors
# For license information, please see license.txt
# import frappe
from __future__ import unicode_literals
import frappe
from frappe.utils import getdate, nowdate
from frappe import _
from frappe.model.document import Document
from frappe.utils import cstr, get_d... | [
"frappe.db.sql",
"frappe.bold",
"frappe._"
] | [((474, 669), 'frappe.db.sql', 'frappe.db.sql', (['"""\n\t\t\tselect name from `tabStrategic Plan`\n\t\t\twhere workflow_state NOT IN ("Approved","Rejected","Completed") \n\t\t\t\tand name != %s\n\t\t\t\tand docstatus != 2\n\t\t"""', 'self.name'], {}), '(\n """\n\t\t\tselect name from `tabStrategic Plan`\n\t\t\twher... |
# %%
import sys, os
import pandas as pd
import networkx as nx
# import matplotlib.pyplot as plt
import numpy as np
import pickle
base_file_path = os.path.abspath(os.path.join(os.curdir, '..','..', '..')) # should point to the level above the src directory
data_path = os.path.join(base_file_path, 'data', 'Intercity_Dal... | [
"numpy.zeros",
"os.path.join",
"numpy.sum",
"numpy.concatenate"
] | [((269, 325), 'os.path.join', 'os.path.join', (['base_file_path', '"""data"""', '"""Intercity_Dallas"""'], {}), "(base_file_path, 'data', 'Intercity_Dallas')\n", (281, 325), False, 'import sys, os\n'), ((2582, 2607), 'numpy.zeros', 'np.zeros', (['(num_counties,)'], {}), '((num_counties,))\n', (2590, 2607), True, 'impor... |
#!/usr/bin/env python3
''' 문자열 s와 s보다 짧은 길이를 갖는 문자열의 배열인 T가 주어졌을 때,
T에 있는 각 문자열을 s에서 찾는 메서드를 작성하라.'''
import unittest
class TreeRoot:
def __init__(self, s):
self.root = SuffixTreeNode()
root = self.root
for i in range(len(s)):
root.insertString(s[i:], i)
def search(sel... | [
"unittest.main"
] | [((2658, 2673), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2671, 2673), False, 'import unittest\n')] |
from time import time
from uuid import UUID
import asyncpg
from app.senders.models import (EmailConfInDb, EmailStatus, Message,
MessageStatus, TelegramConfInDb,
TelegramStatus)
async def insert_email_conf(conn: asyncpg.Connection, conf: EmailConfInDb):... | [
"app.senders.models.EmailStatus",
"app.senders.models.EmailConfInDb",
"time.time",
"app.senders.models.TelegramStatus",
"app.senders.models.TelegramConfInDb",
"app.senders.models.Message"
] | [((1043, 1063), 'app.senders.models.EmailConfInDb', 'EmailConfInDb', ([], {}), '(**raw)\n', (1056, 1063), False, 'from app.senders.models import EmailConfInDb, EmailStatus, Message, MessageStatus, TelegramConfInDb, TelegramStatus\n'), ((1350, 1373), 'app.senders.models.TelegramConfInDb', 'TelegramConfInDb', ([], {}), '... |
# coding: utf-8
import matplotlib.pyplot as plt
import csv
"""
This script is for gathering force/RMSE data from training result of
GaN 350 sample and plot them
"""
if __name__ == '__main__':
GaN350folder="/home/okugawa/NNP-F/GaN/SMZ-200901/training_2element/350smpl/"
outfile=GaN350folder+"result/RMSE.csv"
... | [
"matplotlib.pyplot.title",
"csv.writer",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.savefig"
] | [((2310, 2322), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2320, 2322), True, 'import matplotlib.pyplot as plt\n'), ((2358, 2395), 'matplotlib.pyplot.title', 'plt.title', (['"""GaN 350sample force/RMSE"""'], {}), "('GaN 350sample force/RMSE')\n", (2367, 2395), True, 'import matplotlib.pyplot as plt\n'... |
from cv2 import cv2
import numpy as np
import anki_vector
from anki_vector.util import distance_mm, speed_mmps, degrees
def empty(a):
pass
robot=anki_vector.Robot()
robot.connect()
robot.camera.init_camera_feed()
robot.behavior.set_lift_height(0.0)
robot.behavior.set_head_angle(degrees(0))
cv2.namedWindow("Tr... | [
"cv2.cv2.namedWindow",
"cv2.cv2.arcLength",
"anki_vector.Robot",
"cv2.cv2.boundingRect",
"cv2.cv2.resizeWindow",
"cv2.cv2.getTrackbarPos",
"cv2.cv2.findContours",
"cv2.cv2.inRange",
"cv2.cv2.approxPolyDP",
"anki_vector.util.degrees",
"cv2.cv2.createTrackbar",
"numpy.array",
"cv2.cv2.Gaussian... | [((154, 173), 'anki_vector.Robot', 'anki_vector.Robot', ([], {}), '()\n', (171, 173), False, 'import anki_vector\n'), ((301, 329), 'cv2.cv2.namedWindow', 'cv2.namedWindow', (['"""TrackBars"""'], {}), "('TrackBars')\n", (316, 329), False, 'from cv2 import cv2\n'), ((330, 369), 'cv2.cv2.resizeWindow', 'cv2.resizeWindow',... |
# 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 agreed to in writing, software
#... | [
"rally_openstack.task.contexts.network.existing_network.ExistingNetwork",
"unittest.mock.MagicMock",
"unittest.mock.Mock",
"unittest.mock.patch",
"tests.unit.test.get_test_context",
"unittest.mock.call"
] | [((1485, 1539), 'unittest.mock.patch', 'mock.patch', (['"""rally_openstack.common.osclients.Clients"""'], {}), "('rally_openstack.common.osclients.Clients')\n", (1495, 1539), False, 'from unittest import mock\n'), ((919, 942), 'tests.unit.test.get_test_context', 'test.get_test_context', ([], {}), '()\n', (940, 942), Fa... |
# coding: utf-8
from unidecode import unidecode
import re
from .utils import stop_words
class Parser:
"""Parse user's query"""
def __init__(self, user_query):
self.user_query = user_query
def clean_string(self):
"""remove accents, upper and punctuation
and split into list
... | [
"unidecode.unidecode",
"re.compile"
] | [((399, 425), 'unidecode.unidecode', 'unidecode', (['self.user_query'], {}), '(self.user_query)\n', (408, 425), False, 'from unidecode import unidecode\n'), ((452, 470), 're.compile', 're.compile', (['"""\\\\w+"""'], {}), "('\\\\w+')\n", (462, 470), False, 'import re\n')] |
from rest_framework.response import Response
class SortModelMixin(object):
sort_child_name = None
sort_parent = None
sort_serializer = None
def get_sort_serializer(self, *args, **kwargs):
serializer_class = self.sort_serializer
kwargs["context"] = self.get_serializer_context()
... | [
"rest_framework.response.Response"
] | [((807, 832), 'rest_framework.response.Response', 'Response', (['serializer.data'], {}), '(serializer.data)\n', (815, 832), False, 'from rest_framework.response import Response\n')] |
# -*- coding: utf-8 -*-
from metamapper.celery import app
from datetime import timedelta
from django.utils.timezone import now
from app.audit.models import Activity
@app.task(bind=True)
def audit(self,
actor_id,
workspace_id,
verb,
old_values,
new_values,
... | [
"django.utils.timezone.now",
"app.audit.models.Activity.objects.create",
"metamapper.celery.app.task",
"datetime.timedelta",
"app.audit.models.Activity.objects.filter"
] | [((170, 189), 'metamapper.celery.app.task', 'app.task', ([], {'bind': '(True)'}), '(bind=True)\n', (178, 189), False, 'from metamapper.celery import app\n'), ((982, 987), 'django.utils.timezone.now', 'now', ([], {}), '()\n', (985, 987), False, 'from django.utils.timezone import now\n'), ((1079, 1084), 'django.utils.tim... |
from src import swift_project
from helpers import path_helper
import unittest
class TestSourceKitten(unittest.TestCase):
# Test with a simple project directory
# (i.e. without xcodeproj)
def test_source_files_simple_project(self):
project_directory = path_helper.monkey_example_directory()
... | [
"helpers.path_helper.monkey_example_directory",
"src.swift_project.source_files"
] | [((272, 310), 'helpers.path_helper.monkey_example_directory', 'path_helper.monkey_example_directory', ([], {}), '()\n', (308, 310), False, 'from helpers import path_helper\n'), ((329, 374), 'src.swift_project.source_files', 'swift_project.source_files', (['project_directory'], {}), '(project_directory)\n', (355, 374), ... |
import pandas as pd
file = r'file.log'
cols=['host','1','userid','date','tz','endpoint','status','data','referer','user_agent']
df=pd.read_csv(file,delim_whitespace=True,names=cols).drop('1',1)
print (df.head())
unique_ip=df.host.unique()
print(unique_ip)
total = df['data'].sum()
print('the serv... | [
"pandas.DataFrame",
"pandas.read_csv"
] | [((365, 410), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['status', 'Frequency']"}), "(columns=['status', 'Frequency'])\n", (377, 410), True, 'import pandas as pd\n'), ((140, 192), 'pandas.read_csv', 'pd.read_csv', (['file'], {'delim_whitespace': '(True)', 'names': 'cols'}), '(file, delim_whitespace=True, na... |
import unittest
from calculator import *
class CalculatorTest(unittest.TestCase):
def test_suma_dos_numeros(self):
calc = Calculator(5, 10)
self.assertEqual(15, calc.suma())
def test_resta_dos_numeros(self):
calc = Calculator(19, 8)
self.assertEqual(11, calc.resta())
... | [
"unittest.main"
] | [((1188, 1203), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1201, 1203), False, 'import unittest\n')] |
import copy
import logging
from dataclasses import dataclass
from typing import Any, Optional, Type, TypeVar
from thenewboston_node.business_logic.exceptions import ValidationError
from thenewboston_node.business_logic.models.base import BaseDataclass
from thenewboston_node.core.logging import validates
from thenewbos... | [
"thenewboston_node.core.utils.cryptography.derive_public_key",
"copy.deepcopy",
"thenewboston_node.core.logging.validates",
"typing.TypeVar",
"thenewboston_node.business_logic.exceptions.ValidationError",
"logging.getLogger"
] | [((638, 679), 'typing.TypeVar', 'TypeVar', (['"""T"""'], {'bound': '"""SignedChangeRequest"""'}), "('T', bound='SignedChangeRequest')\n", (645, 679), False, 'from typing import Any, Optional, Type, TypeVar\n'), ((690, 717), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (707, 717), False,... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: harness/grpc.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _sym... | [
"google.protobuf.symbol_database.Default",
"google.protobuf.descriptor.FieldDescriptor",
"google.protobuf.reflection.GeneratedProtocolMessageType",
"google.protobuf.descriptor.FileDescriptor"
] | [((380, 406), 'google.protobuf.symbol_database.Default', '_symbol_database.Default', ([], {}), '()\n', (404, 406), True, 'from google.protobuf import symbol_database as _symbol_database\n'), ((530, 1071), 'google.protobuf.descriptor.FileDescriptor', '_descriptor.FileDescriptor', ([], {'name': '"""harness/grpc.proto"""'... |
import os
import shelve
APP_SETTING_FILE = os.path.join(os.getcwd(), 'instance', "data", "app")
CACHE_DIR = os.path.join(os.getcwd(), 'instance', 'cache')
try:
os.makedirs(CACHE_DIR)
os.makedirs(os.path.dirname(APP_SETTING_FILE))
except OSError:
pass
# for item, value in os.environ.items():
# print(... | [
"os.path.abspath",
"os.makedirs",
"os.getcwd",
"os.path.dirname",
"shelve.open",
"os.environ.get"
] | [((355, 383), 'os.environ.get', 'os.environ.get', (['"""MEDIA_HOME"""'], {}), "('MEDIA_HOME')\n", (369, 383), False, 'import os\n'), ((58, 69), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (67, 69), False, 'import os\n'), ((123, 134), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (132, 134), False, 'import os\n'), ((167, ... |
# -*- coding: UTF-8 -*
from __future__ import print_function
__version__ = "1.2.0"
def get_certificate(hostname, port, sername=None):
import idna
from socket import socket
from OpenSSL import SSL
sock = socket()
sock.setblocking(True)
sock.connect((hostname, port), )
ctx = SSL.Context(SS... | [
"argparse.ArgumentParser",
"OpenSSL.SSL.Connection",
"datetime.datetime.today",
"time.time",
"socket.setdefaulttimeout",
"datetime.datetime.strptime",
"sys.stdout.flush",
"OpenSSL.SSL.Context",
"socket",
"idna.encode",
"sys.stdout.isatty",
"io.open",
"collections.OrderedDict",
"urllib.pars... | [((223, 231), 'socket', 'socket', ([], {}), '()\n', (229, 231), False, 'import socket\n'), ((306, 336), 'OpenSSL.SSL.Context', 'SSL.Context', (['SSL.SSLv23_METHOD'], {}), '(SSL.SSLv23_METHOD)\n', (317, 336), False, 'from OpenSSL import SSL\n'), ((422, 447), 'OpenSSL.SSL.Connection', 'SSL.Connection', (['ctx', 'sock'], ... |
from __future__ import absolute_import
from unittest import TestCase, skip
from ..wcs import WCS
import numpy as np
import os
import re
import sys
from astropy.io import fits
from astropy.modeling import (models, fitting, Model)
import matplotlib.pyplot as plt
from ccdproc import CCDData
class TestWCSBase(TestCase)... | [
"ccdproc.CCDData.read",
"os.path.dirname",
"re.match",
"numpy.ones",
"os.path.isfile",
"astropy.modeling.models.Chebyshev1D",
"astropy.io.fits.Header",
"os.path.join",
"re.sub"
] | [((1309, 1371), 'os.path.join', 'os.path.join', (['self.data_path', '"""goodman_comp_400M1_HgArNe.fits"""'], {}), "(self.data_path, 'goodman_comp_400M1_HgArNe.fits')\n", (1321, 1371), False, 'import os\n'), ((1419, 1454), 'ccdproc.CCDData.read', 'CCDData.read', (['test_file'], {'unit': '"""adu"""'}), "(test_file, unit=... |
from guizero import App, TextBox, Text
def count():
character_count.value = len(entered_text.value)
app = App()
entered_text = TextBox(app, command=count)
character_count = Text(app)
app.display()
| [
"guizero.TextBox",
"guizero.App",
"guizero.Text"
] | [((112, 117), 'guizero.App', 'App', ([], {}), '()\n', (115, 117), False, 'from guizero import App, TextBox, Text\n'), ((133, 160), 'guizero.TextBox', 'TextBox', (['app'], {'command': 'count'}), '(app, command=count)\n', (140, 160), False, 'from guizero import App, TextBox, Text\n'), ((179, 188), 'guizero.Text', 'Text',... |
from django.views.generic import RedirectView
from mobile.constants import DEFAULT_REDIRECT_URL, DEFAULT_REDIRECTORS
from mobile.services.mobile_redirector_service import DesktopToMobileRedirectorService
from share.models import Session
class MobileDataToolView(RedirectView):
def get_redirect_url(self, *args, **... | [
"share.models.Session.objects.get",
"mobile.services.mobile_redirector_service.DesktopToMobileRedirectorService",
"share.models.Session.id_from_hash"
] | [((467, 501), 'share.models.Session.objects.get', 'Session.objects.get', ([], {'id': 'session_id'}), '(id=session_id)\n', (486, 501), False, 'from share.models import Session\n'), ((412, 441), 'share.models.Session.id_from_hash', 'Session.id_from_hash', (['hash_id'], {}), '(hash_id)\n', (432, 441), False, 'from share.m... |
from util import generate_doc_src, auto_dict
from rdflib import Graph
from urllib.error import URLError
# Pull the latest Brick.ttl to /static/schema
try:
g = Graph()
g.parse("https://github.com/brickschema/Brick/releases/latest/download/Brick.ttl", format="turtle")
g.serialize("static/schema/Brick.ttl", f... | [
"util.auto_dict",
"rdflib.Graph",
"util.generate_doc_src"
] | [((449, 460), 'util.auto_dict', 'auto_dict', ([], {}), '()\n', (458, 460), False, 'from util import generate_doc_src, auto_dict\n'), ((164, 171), 'rdflib.Graph', 'Graph', ([], {}), '()\n', (169, 171), False, 'from rdflib import Graph\n'), ((1606, 1632), 'util.generate_doc_src', 'generate_doc_src', (['doc_spec'], {}), '... |
from sciapp.action import Free
import scipy.ndimage as ndimg
import numpy as np, wx
# from imagepy import IPy
#matplotlib.use('WXAgg')
import matplotlib.pyplot as plt
def block(arr):
img = np.zeros((len(arr),30,30), dtype=np.uint8)
img.T[:] = arr
return np.hstack(img)
class Temperature(Free):
title = 'Temperature... | [
"matplotlib.pyplot.title",
"scipy.ndimage.gaussian_filter1d",
"numpy.ones",
"matplotlib.pyplot.figure",
"numpy.exp",
"matplotlib.pyplot.gca",
"numpy.linspace",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show",
"scipy.ndimage.convolve1d",
"matplotlib.pyplot.leg... | [((258, 272), 'numpy.hstack', 'np.hstack', (['img'], {}), '(img)\n', (267, 272), True, 'import numpy as np, wx\n'), ((384, 433), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]'], {}), '([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])\n', (392, 433), True, 'import numpy as np, wx\n'), ((430, 496), 'numpy... |
from api_keys import CENSUS_KEY
import json
import requests
def getCensusResponse(table_url,get_ls,geo):
'''
Concatenates url string and returns response from census api query
input:
table_url (str): census api table url
get_ls (ls): list of tables to get data from
geo (str): geogra... | [
"requests.get"
] | [((525, 542), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (537, 542), False, 'import requests\n')] |
from django.apps import AppConfig
from django.utils.translation import ugettext, ugettext_lazy as _
from pretix import __version__ as version
class BadgesApp(AppConfig):
name = 'pretix.plugins.badges'
verbose_name = _("Badges")
class PretixPluginMeta:
name = _("Badges")
author = _("the p... | [
"django.utils.translation.ugettext",
"django.utils.translation.ugettext_lazy"
] | [((227, 238), 'django.utils.translation.ugettext_lazy', '_', (['"""Badges"""'], {}), "('Badges')\n", (228, 238), True, 'from django.utils.translation import ugettext, ugettext_lazy as _\n'), ((283, 294), 'django.utils.translation.ugettext_lazy', '_', (['"""Badges"""'], {}), "('Badges')\n", (284, 294), True, 'from djang... |
# coding: utf-8
"""
Shutterstock API Reference
The Shutterstock API provides access to Shutterstock's library of media, as well as information about customers' accounts and the contributors that provide the media. # noqa: E501
OpenAPI spec version: 1.0.11
Generated by: https://github.com/swagge... | [
"six.iteritems"
] | [((4744, 4777), 'six.iteritems', 'six.iteritems', (['self.swagger_types'], {}), '(self.swagger_types)\n', (4757, 4777), False, 'import six\n')] |
import pandas as pd
import numpy as np
from texttable import Texttable
from cape_privacy.pandas import dtypes
from cape_privacy.pandas.transformations import NumericPerturbation
from cape_privacy.pandas.transformations import DatePerturbation
from cape_privacy.pandas.transformations import NumericRounding
from cape_p... | [
"pandas.DataFrame",
"cape_privacy.pandas.transformations.DatePerturbation",
"numpy.random.seed",
"faker.Faker",
"faker.Faker.seed",
"anonympy.pandas.utils_pandas.get_datetime_columns",
"anonympy.pandas.utils_pandas.get_categorical_columns",
"anonympy.pandas.utils_pandas.get_numeric_columns",
"pandas... | [((2237, 2273), 'anonympy.pandas.utils_pandas.get_numeric_columns', '_utils.get_numeric_columns', (['self._df'], {}), '(self._df)\n', (2263, 2273), True, 'from anonympy.pandas import utils_pandas as _utils\n'), ((2309, 2349), 'anonympy.pandas.utils_pandas.get_categorical_columns', '_utils.get_categorical_columns', (['s... |
import matplotlib.pyplot as plt
import torch
# 回归类型的例子
data_shape = torch.ones(400, 2)
x0 = torch.normal(2 * data_shape, 1)
y0 = torch.zeros(data_shape.size()[0])
x1 = torch.normal(-2 * data_shape, 1)
y1 = torch.ones(data_shape.size()[0])
x = torch.cat((x0, x1), 0).type(torch.FloatTensor)
y = torch.cat((y0, y1)).type... | [
"torch.ones",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ioff",
"torch.nn.CrossEntropyLoss",
"torch.cat",
"torch.normal",
"matplotlib.pyplot.text",
"matplotlib.pyplot.ion",
"matplotlib.pyplot.cla",
"torch.max",
"torch.nn.Linear",
"matplotlib.pyplot.pause"
] | [((69, 87), 'torch.ones', 'torch.ones', (['(400)', '(2)'], {}), '(400, 2)\n', (79, 87), False, 'import torch\n'), ((93, 124), 'torch.normal', 'torch.normal', (['(2 * data_shape)', '(1)'], {}), '(2 * data_shape, 1)\n', (105, 124), False, 'import torch\n'), ((169, 201), 'torch.normal', 'torch.normal', (['(-2 * data_shape... |
import unittest
from pyblynkrestapi.PyBlynkRestApi import PyBlynkRestApi
class TestBase(unittest.TestCase):
def __init__(self,*args, **kwargs):
super(TestBase, self).__init__(*args, **kwargs)
self.auth_token = ''
self.blynk = PyBlynkRestApi(auth_token=self.auth_token)
| [
"pyblynkrestapi.PyBlynkRestApi.PyBlynkRestApi"
] | [((257, 299), 'pyblynkrestapi.PyBlynkRestApi.PyBlynkRestApi', 'PyBlynkRestApi', ([], {'auth_token': 'self.auth_token'}), '(auth_token=self.auth_token)\n', (271, 299), False, 'from pyblynkrestapi.PyBlynkRestApi import PyBlynkRestApi\n')] |
# -*- coding: utf-8 -*-
import os
import pathlib
from setuptools import setup, find_packages, Extension
from setuptools.command.build_ext import build_ext as build_ext_orig
_VERSION = '0.2.2'
class CMakeExtension(Extension):
def __init__(self, name):
super().__init__(name, sources=[])
class build_ext(bu... | [
"pathlib.Path",
"setuptools.find_packages"
] | [((541, 570), 'pathlib.Path', 'pathlib.Path', (['self.build_temp'], {}), '(self.build_temp)\n', (553, 570), False, 'import pathlib\n'), ((1570, 1585), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (1583, 1585), False, 'from setuptools import setup, find_packages, Extension\n'), ((494, 508), 'pathlib.Pa... |
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
# Init app
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
# Database
app.config['SQLALCHEMY_DATABASE_URI'] = ('sqlite:///' +
os.path.join(basedir, 'db.s... | [
"os.path.dirname",
"flask.Flask",
"flask_marshmallow.Marshmallow",
"flask_sqlalchemy.SQLAlchemy",
"os.path.join"
] | [((152, 167), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (157, 167), False, 'from flask import Flask, request, jsonify\n'), ((397, 412), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', (['app'], {}), '(app)\n', (407, 412), False, 'from flask_sqlalchemy import SQLAlchemy\n'), ((428, 444), 'flask_marshmallo... |
#!/usr/bin/env python
"""Module for setting up statistical models"""
from __future__ import division
from math import pi
import numpy as np
import pymc as mc
import graphics
import data_fds
import external_fds
def fds_mlr():
"""PyMC configuration with FDS as the model."""
# Priors
# FDS inputs: abs_coe... | [
"external_fds.read_fds",
"external_fds.gen_input",
"pymc.Uniform",
"graphics.plot_fds_mlr",
"pymc.Normal",
"external_fds.run_fds"
] | [((369, 605), 'pymc.Uniform', 'mc.Uniform', (['"""theta"""'], {'lower': '[1, 7500000000000.0, 187000.0, 0.75, 500, 0.01, 500, 0.5]', 'value': '[2500, 8500000000000.0, 188000.0, 0.85, 750, 0.25, 1000, 3.0]', 'upper': '[5000, 9500000000000.0, 189000.0, 1.0, 2000, 0.5, 2000, 6.0]'}), "('theta', lower=[1, 7500000000000.0, ... |
import collections
class Solution:
def knightProbability(self, N: int, K: int, r: int, c: int) -> float:
def valid(curr, curc):
if curr < 0 or curr > N - 1 or curc < 0 or curc > N - 1:
return False
return True
if valid(r, c) == False:
... | [
"collections.deque"
] | [((388, 424), 'collections.deque', 'collections.deque', (['[(r, c, 0, True)]'], {}), '([(r, c, 0, True)])\n', (405, 424), False, 'import collections\n')] |
# Copyright 2019 <NAME> GmbH
#
# 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, ... | [
"os.path.isdir",
"os.path.expanduser"
] | [((987, 1011), 'os.path.expanduser', 'os.path.expanduser', (['path'], {}), '(path)\n', (1005, 1011), False, 'import os\n'), ((1023, 1042), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (1036, 1042), False, 'import os\n')] |
#!/usr/bin/env python3
import asyncio
import logging
from typing import TextIO
import click
import yaml
from rich.logging import RichHandler
from hasspad.config import HasspadConfig
from hasspad.hasspad import Hasspad
logging.basicConfig(
level="INFO",
format="%(message)s",
datefmt="[%X]",
handlers=... | [
"click.File",
"click.command",
"yaml.safe_load",
"rich.logging.RichHandler",
"logging.getLogger"
] | [((369, 396), 'logging.getLogger', 'logging.getLogger', (['__file__'], {}), '(__file__)\n', (386, 396), False, 'import logging\n'), ((400, 415), 'click.command', 'click.command', ([], {}), '()\n', (413, 415), False, 'import click\n'), ((447, 462), 'click.File', 'click.File', (['"""r"""'], {}), "('r')\n", (457, 462), Fa... |
from adaptivefiltering.utils import AdaptiveFilteringError, is_iterable
# Mapping from human-readable name to class codes
_name_to_class = {
"unclassified": (0, 1),
"ground": (2,),
"low_vegetation": (3,),
"medium_vegetation": (4,),
"high_vegetation": (5,),
"building": (6,),
"low_point": (7... | [
"adaptivefiltering.utils.is_iterable",
"adaptivefiltering.utils.AdaptiveFilteringError"
] | [((1548, 1565), 'adaptivefiltering.utils.is_iterable', 'is_iterable', (['vals'], {}), '(vals)\n', (1559, 1565), False, 'from adaptivefiltering.utils import AdaptiveFilteringError, is_iterable\n'), ((768, 866), 'adaptivefiltering.utils.AdaptiveFilteringError', 'AdaptiveFilteringError', (['f"""Classification identifier \... |
# SPDX-FileCopyrightText: 2022-present <NAME> <<EMAIL>>
#
# SPDX-License-Identifier: MIT
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
class VCSBuildHook(BuildHookInterface):
PLUGIN_NAME = 'vcs'
def __init__(self, *args, **kwargs):
super(VCSBuildHook, self).__init__(*args, ... | [
"setuptools_scm.dump_version"
] | [((1484, 1591), 'setuptools_scm.dump_version', 'dump_version', (['self.root', 'self.metadata.version', 'self.config_version_file'], {'template': 'self.config_template'}), '(self.root, self.metadata.version, self.config_version_file,\n template=self.config_template)\n', (1496, 1591), False, 'from setuptools_scm impor... |
#!/usr/bin/env python
# encoding=utf-8
"""
Copyright (c) 2021 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFT... | [
"threading.Lock",
"threading.Thread",
"io.StringIO",
"paramiko.SSHClient"
] | [((793, 806), 'io.StringIO', 'io.StringIO', ([], {}), '()\n', (804, 806), False, 'import io\n'), ((828, 834), 'threading.Lock', 'Lock', ([], {}), '()\n', (832, 834), False, 'from threading import Thread, Lock\n'), ((1644, 1671), 'threading.Thread', 'Thread', ([], {'target': '_read_handle'}), '(target=_read_handle)\n', ... |
from pydantic import BaseModel
from bson import ObjectId
from typing import Any, List
from models.comment import CommentBase
from db.mongodb import get_database
class PostUpdates(BaseModel):
id: str
text: str
title: str
user_id: str
published: bool
up_vote: List[str]
down_vote: List[str]
... | [
"db.mongodb.get_database",
"models.comment.CommentBase.find_by_post_id",
"models.comment.CommentBase.delete_all_comments_for_post",
"bson.ObjectId"
] | [((429, 443), 'db.mongodb.get_database', 'get_database', ([], {}), '()\n', (441, 443), False, 'from db.mongodb import get_database\n'), ((707, 721), 'db.mongodb.get_database', 'get_database', ([], {}), '()\n', (719, 721), False, 'from db.mongodb import get_database\n'), ((1289, 1303), 'db.mongodb.get_database', 'get_da... |
import csv
import random
import re
import sys
import tqdm
import numpy as np
import torch
from torch.utils.data import TensorDataset
from transformers.tokenization_bert import BertTokenizer
def load_glove_txt(file_path="glove.840B.300d.txt"):
results = {}
num_file = sum([1 for i in open(file_path, "r", encodi... | [
"tqdm.tqdm",
"transformers.tokenization_bert.BertTokenizer",
"numpy.random.shuffle",
"csv.reader",
"torch.LongTensor",
"torch.utils.data.TensorDataset",
"re.sub",
"torch.tensor"
] | [((663, 690), 're.sub', 're.sub', (['"""\'s"""', '""" \'s"""', 'string'], {}), '("\'s", " \'s", string)\n', (669, 690), False, 'import re\n'), ((706, 735), 're.sub', 're.sub', (['"""\'ve"""', '""" \'ve"""', 'string'], {}), '("\'ve", " \'ve", string)\n', (712, 735), False, 'import re\n'), ((751, 780), 're.sub', 're.sub'... |
# Copyright (c) 2015 SUSE Linux GmbH. 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 la... | [
"azurectl.defaults.Defaults.unify_id",
"azure.servicemanagement.PublicKey",
"azure.servicemanagement.OSVirtualHardDisk",
"azure.servicemanagement.LinuxConfigurationSet",
"azure.servicemanagement.ConfigurationSet",
"azure.servicemanagement.ConfigurationSetInputEndpoint"
] | [((1993, 2103), 'azure.servicemanagement.LinuxConfigurationSet', 'LinuxConfigurationSet', (['instance_name', 'username', 'password', 'disable_ssh_password_authentication', 'custom_data'], {}), '(instance_name, username, password,\n disable_ssh_password_authentication, custom_data)\n', (2014, 2103), False, 'from azur... |
from typing import List, Optional
import pytest
from httpx import AsyncClient
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from ops2deb.exceptions import Ops2debUpdaterError
from ops2deb.logger import enable_debug
from ops2d... | [
"starlette.applications.Starlette",
"ops2deb.updater.GithubUpdateStrategy",
"ops2deb.logger.enable_debug",
"starlette.responses.Response",
"starlette.responses.JSONResponse",
"httpx.AsyncClient",
"pytest.raises",
"pytest.mark.parametrize",
"ops2deb.updater.GenericUpdateStrategy"
] | [((383, 401), 'ops2deb.logger.enable_debug', 'enable_debug', (['(True)'], {}), '(True)\n', (395, 401), False, 'from ops2deb.logger import enable_debug\n'), ((1533, 1904), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""versions,expected_result"""', "[(['1.0.0', '1.1.0'], '1.1.0'), (['1.0.0', '1.1.3'], '1.1.... |
from rest_framework import serializers
# djangorestframework-recursive
from rest_framework_recursive.fields import RecursiveField
# local
from .question import QuestionSerializer
from ..models import Section
class SectionSerializer(serializers.ModelSerializer):
children = RecursiveField(required=False, allow_nu... | [
"rest_framework_recursive.fields.RecursiveField"
] | [((281, 339), 'rest_framework_recursive.fields.RecursiveField', 'RecursiveField', ([], {'required': '(False)', 'allow_null': '(True)', 'many': '(True)'}), '(required=False, allow_null=True, many=True)\n', (295, 339), False, 'from rest_framework_recursive.fields import RecursiveField\n')] |
from django import forms
from django.contrib.auth import authenticate
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser, Profile
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = CustomUser
fields = ("first_name", "last_name", ... | [
"django.forms.PasswordInput",
"django.forms.EmailInput",
"django.forms.ValidationError",
"django.contrib.auth.authenticate",
"django.forms.Textarea"
] | [((549, 592), 'django.forms.EmailInput', 'forms.EmailInput', ([], {'attrs': "{'autofocus': True}"}), "(attrs={'autofocus': True})\n", (565, 592), False, 'from django import forms\n'), ((662, 725), 'django.forms.PasswordInput', 'forms.PasswordInput', ([], {'attrs': "{'autocomplete': 'current-password'}"}), "(attrs={'aut... |
from django.contrib import admin
from django.urls import path, include
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from rest_framework import permissions
schema_view = get_schema_view(
openapi.Info(
title='Movie DB API',
default_version='v1',
description='API to ... | [
"drf_yasg.openapi.Info",
"django.urls.path",
"django.urls.include"
] | [((218, 319), 'drf_yasg.openapi.Info', 'openapi.Info', ([], {'title': '"""Movie DB API"""', 'default_version': '"""v1"""', 'description': '"""API to fetch movie data."""'}), "(title='Movie DB API', default_version='v1', description=\n 'API to fetch movie data.')\n", (230, 319), False, 'from drf_yasg import openapi\n... |
import sys
import os
import pickle
import math
import numpy as np
import matplotlib.pyplot as plt
from pprint import pprint
os.chdir('C:/Users/<NAME>/Documents/Data/WHI long term record/coatings/')
file = open('fraction of detectable notch positions by BC core size - aged.pickl', 'r')
fractions_detectable_aged = pick... | [
"matplotlib.pyplot.show",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"pickle.load",
"pprint.pprint",
"os.chdir",
"matplotlib.pyplot.savefig"
] | [((126, 199), 'os.chdir', 'os.chdir', (['"""C:/Users/<NAME>/Documents/Data/WHI long term record/coatings/"""'], {}), "('C:/Users/<NAME>/Documents/Data/WHI long term record/coatings/')\n", (134, 199), False, 'import os\n'), ((316, 333), 'pickle.load', 'pickle.load', (['file'], {}), '(file)\n', (327, 333), False, 'import... |
import numpy as np
import torch
import pytorch_lightning as pl
from torch.utils.data import DataLoader
from implem.utils import device
class SimpleDataset(torch.utils.data.Dataset):
def __init__(self, data, offset=1, start=None, end=None):
super(SimpleDataset, self).__init__()
assert len(data.shap... | [
"numpy.asarray",
"numpy.prod",
"numpy.arange",
"torch.arange",
"torch.Generator"
] | [((653, 722), 'torch.arange', 'torch.arange', (['self.start', 'self.end'], {'requires_grad': '(False)', 'device': '"""cpu"""'}), "(self.start, self.end, requires_grad=False, device='cpu')\n", (665, 722), False, 'import torch\n'), ((1611, 1680), 'torch.arange', 'torch.arange', (['self.start', 'self.end'], {'requires_gra... |