code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# this is wait Web Driver... | [
"selenium.webdriver.support.ui.WebDriverWait",
"selenium.webdriver.support.expected_conditions.presence_of_element_located"
] | [((427, 476), 'selenium.webdriver.support.expected_conditions.presence_of_element_located', 'EC.presence_of_element_located', (['(By.XPATH, xpath)'], {}), '((By.XPATH, xpath))\n', (457, 476), True, 'from selenium.webdriver.support import expected_conditions as EC\n'), ((590, 648), 'selenium.webdriver.support.expected_c... |
import numpy as np
import pytest
import sets
@pytest.fixture
def dataset():
data = [[1, 3], [0, -1.5], [0, 0]]
target = [0, 0.5, 1]
return sets.Dataset(data=data, target=target)
def test_concat(dataset):
dataset['other'] = [[1], [2], [3]]
result = sets.Concat(1, 'data')(dataset, colu... | [
"sets.Concat",
"sets.Dataset",
"sets.Normalize",
"numpy.ones",
"numpy.unique",
"sets.Split",
"sets.OneHot",
"numpy.zeros",
"numpy.concatenate"
] | [((162, 200), 'sets.Dataset', 'sets.Dataset', ([], {'data': 'data', 'target': 'target'}), '(data=data, target=target)\n', (174, 200), False, 'import sets\n'), ((985, 1021), 'numpy.concatenate', 'np.concatenate', (['(one.data, two.data)'], {}), '((one.data, two.data))\n', (999, 1021), True, 'import numpy as np\n'), ((10... |
import glob as glob
import albumentations
import cv2
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
import os
from model import Net
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = Net().to(device)
# load the model checkpoint
checkpoi... | [
"matplotlib.pyplot.imshow",
"pandas.read_csv",
"torch.load",
"matplotlib.pyplot.imread",
"torch.max",
"matplotlib.pyplot.close",
"torch.no_grad",
"torch.tensor",
"torch.cuda.is_available",
"numpy.array",
"albumentations.Resize",
"matplotlib.pyplot.axis",
"numpy.transpose",
"model.Net",
"... | [((325, 359), 'torch.load', 'torch.load', (['"""../outputs/model.pth"""'], {}), "('../outputs/model.pth')\n", (335, 359), False, 'import torch\n'), ((577, 713), 'pandas.read_csv', 'pd.read_csv', (['"""../../input/german_traffic_sign/GTSRB/Final_Test/GTSRB_Final_Test_GT/GT-final_test.csv"""'], {'delimiter': '""";"""', '... |
from time import time
from functools import wraps
import matplotlib.pyplot as plt
from mandelbrot.python_mandel import compute_mandel as compute_mandel_py
from mandelbrot.hybrid_mandel import compute_mandel as compute_mandel_hy
from mandelbrot.cython_mandel import compute_mandel as compute_mandel_cy
def timer(func, n... | [
"time.time",
"matplotlib.pyplot.subplots",
"functools.wraps",
"matplotlib.pyplot.show"
] | [((825, 839), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (837, 839), True, 'import matplotlib.pyplot as plt\n'), ((890, 900), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (898, 900), True, 'import matplotlib.pyplot as plt\n'), ((331, 342), 'functools.wraps', 'wraps', (['func'], {}), '(fu... |
"""
Copyright 2021 Merck & Co., Inc. Kenilworth, NJ, USA.
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 ... | [
"logging.getLogger",
"json.loads",
"functools.partial"
] | [((1104, 1133), 'logging.getLogger', 'getLogger', (['"""auto_sql_syncker"""'], {}), "('auto_sql_syncker')\n", (1113, 1133), False, 'from logging import getLogger, DEBUG as LOGGING_DEBUG\n'), ((4486, 4574), 'functools.partial', 'partial', (['_match_dataset_and_table'], {'dataset_name': 'dataset_name', 'table_name': 'tab... |
import os
import csv
import collections
from collections import Counter
# variables in list
candidate_votes = []
candidate_selection = []
# set File path
file_path = os.path.join("..", "Resources", "election_data.csv")
# set path for reader
with open(file_path) as csvfile:
csv_reader = csv.reader... | [
"collections.Counter",
"os.path.join",
"csv.reader"
] | [((180, 232), 'os.path.join', 'os.path.join', (['""".."""', '"""Resources"""', '"""election_data.csv"""'], {}), "('..', 'Resources', 'election_data.csv')\n", (192, 232), False, 'import os\n'), ((2064, 2094), 'os.path.join', 'os.path.join', (['"""out_pypoll.txt"""'], {}), "('out_pypoll.txt')\n", (2076, 2094), False, 'im... |
# 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 applica... | [
"tensorboard.plugins.npmi.metadata.create_summary_metadata",
"tensorboard.plugins.npmi.summary.npmi_annotations",
"tensorflow.compat.v1.train.summary_iterator",
"tensorflow.test.main",
"tensorboard.plugins.npmi.metadata.parse_plugin_metadata",
"tensorflow.compat.v1.enable_eager_execution",
"tensorflow.c... | [((1139, 1176), 'tensorflow.compat.v1.enable_eager_execution', 'tf.compat.v1.enable_eager_execution', ([], {}), '()\n', (1174, 1176), True, 'import tensorflow as tf\n'), ((2639, 2653), 'tensorflow.test.main', 'tf.test.main', ([], {}), '()\n', (2651, 2653), True, 'import tensorflow as tf\n'), ((1504, 1542), 'tensorboard... |
# Copyright 2020 The KNIX 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 agree... | [
"subprocess.Popen",
"time.sleep",
"time.time",
"mfn_test_utils.MFNTest",
"os.system",
"socket.gethostname",
"sys.path.append"
] | [((709, 731), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (724, 731), False, 'import sys\n'), ((804, 855), 'subprocess.Popen', 'subprocess.Popen', (["['scripts/run_local_rabbitmq.sh']"], {}), "(['scripts/run_local_rabbitmq.sh'])\n", (820, 855), False, 'import subprocess\n'), ((856, 870), 'ti... |
import re
from collections import namedtuple
from . import runtime
class InvalidWorkflowUri(Exception):
pass
WorkflowUri = namedtuple(
'WorkflowURI',
['template_id', 'holder', 'instance_id']
)
class URI:
REGEX = re.compile(
r"^nyuki://(?P<template_id>[\w-]+)"
r"@(?P<holder>[\w-]+... | [
"collections.namedtuple",
"re.match",
"re.compile"
] | [((132, 199), 'collections.namedtuple', 'namedtuple', (['"""WorkflowURI"""', "['template_id', 'holder', 'instance_id']"], {}), "('WorkflowURI', ['template_id', 'holder', 'instance_id'])\n", (142, 199), False, 'from collections import namedtuple\n'), ((236, 342), 're.compile', 're.compile', (['"""^nyuki://(?P<template_i... |
import cv2
import pytesseract
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
#img = cv2.imread('chif.png')
img = cv2.imread('im.JPG')
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
#print(pytesseract.image_to_string(img))
### Detection charaters
hImg,wImg,_ = img.shape
... | [
"pytesseract.image_to_boxes",
"cv2.rectangle",
"cv2.imshow",
"cv2.putText",
"cv2.cvtColor",
"cv2.waitKey",
"cv2.imread"
] | [((162, 182), 'cv2.imread', 'cv2.imread', (['"""im.JPG"""'], {}), "('im.JPG')\n", (172, 182), False, 'import cv2\n'), ((190, 226), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2RGB'], {}), '(img, cv2.COLOR_BGR2RGB)\n', (202, 226), False, 'import cv2\n'), ((374, 418), 'pytesseract.image_to_boxes', 'pytesseract... |
import anndata
import os
def _cache_name(tempdir, task, dataset, test=None, method=None):
if not isinstance(task, str):
task = task.__name__.split(".")[-1]
if not isinstance(dataset, str):
dataset = dataset.__name__
if method is not None:
if not isinstance(method, str):
... | [
"os.path.isfile",
"anndata.read_h5ad"
] | [((735, 760), 'os.path.isfile', 'os.path.isfile', (['data_path'], {}), '(data_path)\n', (749, 760), False, 'import os\n'), ((848, 876), 'anndata.read_h5ad', 'anndata.read_h5ad', (['data_path'], {}), '(data_path)\n', (865, 876), False, 'import anndata\n')] |
#!/usr/bin/env python3
from contextlib import suppress
from dataclasses import dataclass
from dataclasses import field
from itertools import chain
from itertools import permutations
from itertools import product
from logging import basicConfig
from logging import info
from sys import stdout
from typing import Any
from ... | [
"logging.basicConfig",
"itertools.chain",
"dataclasses.dataclass",
"typing.cast",
"contextlib.suppress",
"itertools.permutations",
"logging.info",
"dataclasses.field"
] | [((485, 556), 'logging.basicConfig', 'basicConfig', ([], {'format': '"""{message}"""', 'level': '"""INFO"""', 'stream': 'stdout', 'style': '"""{"""'}), "(format='{message}', level='INFO', stream=stdout, style='{')\n", (496, 556), False, 'from logging import basicConfig\n'), ((560, 582), 'dataclasses.dataclass', 'datacl... |
'''
Parse input args, parse task file
'''
import argparse,json,logging,sys
import db
'''Variables whose values will be set by the following init() or init_by_cmd_line_args() function.'''
action = None #what action to do
task = None #task infomation
group_int_list = [] #group integer list of task
''' Fun... | [
"logging.basicConfig",
"logging.warning",
"argparse.ArgumentParser"
] | [((1330, 1355), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1353, 1355), False, 'import argparse, json, logging, sys\n'), ((1951, 2052), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'level', 'format': '"""%(asctime)-15s: %(message)s [%(filename)s:%(lineno)s]"""'}), "(level=l... |
import json
import asyncio
from functools import wraps, partial
from logging import Logger
import websockets
class WebSocketServer:
def __init__(self, bind_addr, port, logger):
self.bind_addr = bind_addr
self.port = port
self.active_ws = []
self.event_handlers = {}
self.lo... | [
"json.loads",
"json.dumps",
"websockets.serve",
"functools.partial",
"asyncio.Future"
] | [((3064, 3088), 'json.dumps', 'json.dumps', (['message_dict'], {}), '(message_dict)\n', (3074, 3088), False, 'import json\n'), ((3250, 3345), 'websockets.serve', 'websockets.serve', (['self.handler', 'self.bind_addr', 'self.port'], {'ping_timeout': '(20)', 'ping_interval': '(5)'}), '(self.handler, self.bind_addr, self.... |
# Copyright (c) 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | [
"trove.common.utils.execute_with_timeout",
"trove.guestagent.common.operating_system.service_discovery",
"trove.guestagent.datastore.experimental.postgresql.service.status.PgSqlAppStatus.get",
"oslo_log.log.getLogger"
] | [((897, 924), 'oslo_log.log.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (914, 924), True, 'from oslo_log import log as logging\n'), ((1187, 1247), 'trove.guestagent.common.operating_system.service_discovery', 'operating_system.service_discovery', (['PGSQL_SERVICE_CANDIDATES'], {}), '(PGSQL_SERV... |
import pytmx
import Box2D
import importlib
from PIL import ImageColor
from .gameobject import GameObject
class TileMap:
def __init__(self, tmxFile, gameObjectHandler, gameScreen):
tiled_map = pytmx.TiledMap(tmxFile, image_loader=gameScreen.image_loader)
if tiled_map.background_color:
... | [
"pytmx.TiledMap",
"importlib.import_module",
"Box2D.b2PolygonShape",
"PIL.ImageColor.getcolor",
"Box2D.b2BodyDef"
] | [((207, 268), 'pytmx.TiledMap', 'pytmx.TiledMap', (['tmxFile'], {'image_loader': 'gameScreen.image_loader'}), '(tmxFile, image_loader=gameScreen.image_loader)\n', (221, 268), False, 'import pytmx\n'), ((328, 382), 'PIL.ImageColor.getcolor', 'ImageColor.getcolor', (['tiled_map.background_color', '"""RGB"""'], {}), "(til... |
#!/usr/bin/env python
# Copyright (c) 2020 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
""" This module provides a helper for the co-simulation between vissim and car... | [
"random.choice",
"carla.Vector3D",
"carla.Location",
"math.radians",
"logging.error",
"carla.Rotation"
] | [((3625, 3679), 'carla.Vector3D', 'carla.Vector3D', (['in_vector.x', '(-in_vector.y)', 'in_vector.z'], {}), '(in_vector.x, -in_vector.y, in_vector.z)\n', (3639, 3679), False, 'import carla\n'), ((2147, 2213), 'carla.Location', 'carla.Location', (['out_location[0]', '(-out_location[1])', 'out_location[2]'], {}), '(out_l... |
"""
Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
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/L... | [
"nndet.io.save_json",
"numpy.random.rand",
"loguru.logger.info",
"SimpleITK.GetImageFromArray",
"argparse.ArgumentParser",
"os.getenv",
"random.seed",
"numpy.random.randint",
"numpy.random.seed",
"multiprocessing.Pool",
"numpy.zeros_like",
"itertools.repeat"
] | [((1225, 1241), 'random.seed', 'random.seed', (['idx'], {}), '(idx)\n', (1236, 1241), False, 'import random\n'), ((1246, 1265), 'numpy.random.seed', 'np.random.seed', (['idx'], {}), '(idx)\n', (1260, 1265), True, 'import numpy as np\n'), ((1271, 1308), 'loguru.logger.info', 'logger.info', (['f"""Generating case_{idx}""... |
#histograms
import matplotlib.pyplot as plt
import pandas as pd
Read_csv_filename = 'realEstate_trans.csv'
Read_csv_data = pd.read_csv(Read_csv_filename)
Read_csv_data = Read_csv_data.query('beds < 5')
Read_csv_data.hist(
column='price',
by='beds',
xlabelsize=9,
ylabelsize=9,
... | [
"matplotlib.pyplot.savefig",
"pandas.read_csv",
"matplotlib.pyplot.show"
] | [((131, 161), 'pandas.read_csv', 'pd.read_csv', (['Read_csv_filename'], {}), '(Read_csv_filename)\n', (142, 161), True, 'import pandas as pd\n'), ((355, 390), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""output/histogram.pdf"""'], {}), "('output/histogram.pdf')\n", (366, 390), True, 'import matplotlib.pyplot as pl... |
# Generated by Django 2.1.1 on 2018-09-29 13:17
from django.db import migrations
def init_templates(apps, schema_editor):
from byro.mails import default
MailTemplate = apps.get_model('mails', 'MailTemplate')
Configuration = apps.get_model('common', 'Configuration')
config, _ = Configuration.objects.g... | [
"django.db.migrations.RunPython"
] | [((780, 843), 'django.db.migrations.RunPython', 'migrations.RunPython', (['init_templates', 'migrations.RunPython.noop'], {}), '(init_templates, migrations.RunPython.noop)\n', (800, 843), False, 'from django.db import migrations\n')] |
import numpy as np
import tensorflow as tf
def set_seed(x):
"""
Set seed for both NumPy and TensorFlow.
"""
np.random.seed(x)
tf.set_random_seed(x)
def check_is_tf_vector(x):
if isinstance(x, tf.Tensor):
dimensions = x.get_shape()
if(len(dimensions) == 0):
raise Typ... | [
"tensorflow.get_variable",
"tensorflow.reduce_sum",
"numpy.log",
"tensorflow.set_random_seed",
"tensorflow.log",
"tensorflow.random_normal_initializer",
"numpy.exp",
"numpy.random.seed",
"tensorflow.clip_by_value",
"tensorflow.square",
"tensorflow.convert_to_tensor",
"tensorflow.reduce_max",
... | [((125, 142), 'numpy.random.seed', 'np.random.seed', (['x'], {}), '(x)\n', (139, 142), True, 'import numpy as np\n'), ((147, 168), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['x'], {}), '(x)\n', (165, 168), True, 'import tensorflow as tf\n'), ((1395, 1411), 'tensorflow.reduce_max', 'tf.reduce_max', (['x'], {}... |
from big_boss import *
from PyQt5.QtGui import QTextCursor
from PyQt5.QtWidgets import QApplication, QMainWindow
from Ui_big_boss import *
import logging
class GuiLogger(logging.Handler):
def emit(self, record):
self.edit.append(self.format(record)) # implementation of append_line omitted
self.edi... | [
"logging.getLogger",
"logging.info",
"PyQt5.QtWidgets.QApplication"
] | [((689, 708), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (706, 708), False, 'import logging\n'), ((859, 884), 'logging.info', 'logging.info', (['"""Quitting!"""'], {}), "('Quitting!')\n", (871, 884), False, 'import logging\n'), ((1045, 1067), 'PyQt5.QtWidgets.QApplication', 'QApplication', (['sys.argv'... |
"""Module to manage PI Eligibility Requests."""
import logging
import re
import urllib.parse
from functools import wraps
from chameleon.models import PIEligibility
from django.contrib.admin import ModelAdmin, site
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist
fro... | [
"logging.getLogger",
"django.contrib.auth.get_user_model",
"chameleon.models.PIEligibility.objects.filter",
"django.contrib.admin.site.register",
"util.keycloak_client.KeycloakClient",
"functools.wraps",
"re.sub",
"re.findall",
"django.utils.html.mark_safe"
] | [((441, 468), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (458, 468), False, 'import logging\n'), ((4199, 4247), 'django.contrib.admin.site.register', 'site.register', (['PIEligibility', 'PIEligibilityAdmin'], {}), '(PIEligibility, PIEligibilityAdmin)\n', (4212, 4247), False, 'from dja... |
#!/usr/bin/python
from utils.log import log
import json
import multiprocessing as mp
#make python 2 and 3 behave the same for raw input
if hasattr(__builtins__, 'raw_input'):
input = raw_input
data_file = "data.json"
#any bot class names to leave off the scoreboard for various reasons.
bots_to_skip = ["HumanB... | [
"os.listdir",
"inspect.getmembers",
"importlib.import_module",
"multiprocessing.cpu_count",
"itertools.combinations",
"multiprocessing.Pool",
"json.load",
"operator.itemgetter",
"sys.stdout.flush",
"time.time",
"gameArena.GameArena",
"json.dump"
] | [((655, 673), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (671, 673), False, 'import itertools, time, sys\n'), ((682, 774), 'gameArena.GameArena', 'GameArena', ([], {'num_cards': 'num_cards', 'num_games': 'num_games', 'player_arr': '[bot1_class, bot2_class]'}), '(num_cards=num_cards, num_games=num_games, ... |
import subprocess
import os
import shutil
import time
from rackattack import clientfactory
from tests import testlib
import rackattack
class UserVirtualRackAttack:
MAXIMUM_VMS = 4
def __init__(self):
assert '/usr' not in rackattack.__file__
self._requestPort = 3443
self._subscribePort... | [
"subprocess.Popen",
"time.sleep",
"os.getcwd",
"tests.testlib.waitForTCPServer",
"rackattack.clientfactory.factory",
"shutil.rmtree"
] | [((400, 443), 'shutil.rmtree', 'shutil.rmtree', (['imageDir'], {'ignore_errors': '(True)'}), '(imageDir, ignore_errors=True)\n', (413, 443), False, 'import shutil\n'), ((466, 845), 'subprocess.Popen', 'subprocess.Popen', (["['sudo', 'PYTHONPATH=.', 'UPSETO_JOIN_PYTHON_NAMESPACES=Yes', 'python',\n 'rackattack/virtual... |
from receptor_satellite import playbook_verifier_adapter
import subprocess
class FakePopen:
def __init__(self, returncode=0, response=None):
self.returncode = returncode
self.response = response
def communicate(self, input):
if self.response is None:
response = "Playbook ... | [
"receptor_satellite.playbook_verifier_adapter.verify"
] | [((715, 783), 'receptor_satellite.playbook_verifier_adapter.verify', 'playbook_verifier_adapter.verify', (['"""---\n- hosts: all\n tasks: []"""'], {}), '("""---\n- hosts: all\n tasks: []""")\n', (747, 783), False, 'from receptor_satellite import playbook_verifier_adapter\n'), ((1025, 1066), 'receptor_satellite.playbo... |
import otsu
import cv2
import numpy as np
if __name__ == "__main__":
image = cv2.imread('7.jpg', cv2.IMREAD_GRAYSCALE)
arr = np.asarray(image)
arr2 = cv2.resize(arr, (28, 28))
np.savetxt('./7_2.txt', arr2, fmt='%f')
otsu.otsu(arr2)
| [
"otsu.otsu",
"numpy.asarray",
"numpy.savetxt",
"cv2.resize",
"cv2.imread"
] | [((82, 123), 'cv2.imread', 'cv2.imread', (['"""7.jpg"""', 'cv2.IMREAD_GRAYSCALE'], {}), "('7.jpg', cv2.IMREAD_GRAYSCALE)\n", (92, 123), False, 'import cv2\n'), ((134, 151), 'numpy.asarray', 'np.asarray', (['image'], {}), '(image)\n', (144, 151), True, 'import numpy as np\n'), ((163, 188), 'cv2.resize', 'cv2.resize', ([... |
import os
import glob
import argparse
import numpy as np
from scipy.stats import gaussian_kde
from matplotlib import pyplot as plt
from matplotlib import gridspec
from cryoio import star
def calc_rmse(a, b):
"""
[[11, 12, 13],
[21, 22, 23],
...,
[n1, n2, n3]]
"""
return np.sqrt(np.mea... | [
"numpy.mean",
"os.path.exists",
"scipy.stats.gaussian_kde",
"argparse.ArgumentParser",
"matplotlib.pyplot.ylabel",
"os.makedirs",
"matplotlib.pyplot.xlabel",
"os.path.join",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure",
"matplotlib.gridspec.GridSpec",
"os.path.abspath",
"matplotlib.... | [((397, 439), 'os.path.join', 'os.path.join', (['working_directory', '"""Figures"""'], {}), "(working_directory, 'Figures')\n", (409, 439), False, 'import os\n'), ((540, 561), 'numpy.arange', 'np.arange', (['(0)', '(360)', '(10)'], {}), '(0, 360, 10)\n', (549, 561), True, 'import numpy as np\n'), ((670, 683), 'matplotl... |
import logging
from functools import partial
import numpy as np
import torch
from torch import nn
from deepqmc import Molecule
from deepqmc.physics import pairwise_diffs, pairwise_distance
from deepqmc.torchext import sloglindet, triu_flat
from deepqmc.utils import NULL_DEBUG
from deepqmc.wf import WaveFunction
from... | [
"logging.getLogger",
"numpy.sqrt",
"torch.randperm",
"torch.exp",
"pyscf.mcscf.CASSCF",
"deepqmc.torchext.triu_flat",
"torch.arange",
"torch.tanh",
"torch.nn.Identity",
"deepqmc.physics.pairwise_distance",
"torch.abs",
"pyscf.lib.chkfile.dump",
"torch.sign",
"deepqmc.torchext.sloglindet",
... | [((553, 580), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (570, 580), False, 'import logging\n'), ((15215, 15227), 'pyscf.scf.RHF', 'scf.RHF', (['mol'], {}), '(mol)\n', (15222, 15227), False, 'from pyscf import gto, lib, mcscf, scf\n'), ((2044, 2064), 'torch.sign', 'torch.sign', (['squ... |
import glob
import click
from tabulate import tabulate
from datetime import datetime
from qiskitflow.utils.constants import EXPERIMENTS_DIRECTORY, PAGINATION_SIZE
from qiskitflow.lib.experiment import Experiment
def detail(run_id: str) -> None:
click.echo(click.style("Run [{}] detailed information.\n".format(run... | [
"tabulate.tabulate",
"datetime.datetime.fromtimestamp",
"qiskitflow.lib.experiment.Experiment.load",
"click.style",
"glob.glob"
] | [((431, 452), 'glob.glob', 'glob.glob', (['glob_query'], {}), '(glob_query)\n', (440, 452), False, 'import glob\n'), ((659, 680), 'qiskitflow.lib.experiment.Experiment.load', 'Experiment.load', (['path'], {}), '(path)\n', (674, 680), False, 'from qiskitflow.lib.experiment import Experiment\n'), ((499, 590), 'click.styl... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Time:
2021-07-30 4:58 下午
Author:
huayang
Subject:
"""
from huaytools.pytorch.backend.distance_fn import euclidean_distance_nosqrt
from huaytools.pytorch.modules.wrapper.encoder import EncoderWrapper
from huaytools.pytorch.loss import TripletLoss
class... | [
"huaytools.pytorch.loss.TripletLoss"
] | [((639, 690), 'huaytools.pytorch.loss.TripletLoss', 'TripletLoss', ([], {'distance_fn': 'distance_fn', 'margin': 'margin'}), '(distance_fn=distance_fn, margin=margin)\n', (650, 690), False, 'from huaytools.pytorch.loss import TripletLoss\n')] |
import numpy
from gensim.summarization.bm25 import BM25
class WrappedBM25(BM25):
def __init__(self, docs, tokenizer='spacy'):
self.docs = docs
if tokenizer == 'spacy':
try:
import spacy
except ImportError:
raise ImportError('Please install sp... | [
"numpy.argsort",
"spacy.load"
] | [((1126, 1147), 'numpy.argsort', 'numpy.argsort', (['scores'], {}), '(scores)\n', (1139, 1147), False, 'import numpy\n'), ((1481, 1502), 'numpy.argsort', 'numpy.argsort', (['scores'], {}), '(scores)\n', (1494, 1502), False, 'import numpy\n'), ((629, 645), 'spacy.load', 'spacy.load', (['"""en"""'], {}), "('en')\n", (639... |
# -*- coding:utf-8 -*-
"""
huobi Trade module.
https://huobiapi.github.io/docs/spot/v1/cn
Project: alphahunter
Author: HJQuant
Description: Asynchronous driven quantitative trading framework
"""
import json
import hmac
import copy
import gzip
import base64
import urllib
import hashlib
import datetime
from urllib imp... | [
"quant.utils.logger.error",
"base64.b64encode",
"quant.market.Trade",
"quant.tasks.SingleTask.run",
"gzip.decompress",
"quant.asset.Asset",
"quant.utils.tools.float_to_str",
"json.dumps",
"quant.trader.Trader.MAPPING_LAYER",
"quant.market.Orderbook",
"quant.state.State",
"quant.order.SymbolInf... | [((5387, 5411), 'urllib.parse.urljoin', 'urljoin', (['self._host', 'uri'], {}), '(self._host, uri)\n', (5394, 5411), False, 'from urllib.parse import urljoin\n'), ((7226, 7250), 'base64.b64encode', 'base64.b64encode', (['digest'], {}), '(digest)\n', (7242, 7250), False, 'import base64\n'), ((8936, 8953), 'collections.d... |
import collections
class Dictionary(dict):
'''
data structure for InvertedIndex
word -> postings(doc_id->word_count)
'''
def __missing__(self, key):
postings = collections.defaultdict(int)
self[key] = postings
return postings
class InvertedIndex:
def ... | [
"collections.defaultdict"
] | [((201, 229), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (224, 229), False, 'import collections\n')] |
"""
Create dasp app using Flask
"""
import dash
from flask import Flask
server = Flask(__name__)
app = dash.Dash(__name__, server=server)
app.config.suppress_callback_exceptions = True
| [
"dash.Dash",
"flask.Flask"
] | [((83, 98), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (88, 98), False, 'from flask import Flask\n'), ((105, 139), 'dash.Dash', 'dash.Dash', (['__name__'], {'server': 'server'}), '(__name__, server=server)\n', (114, 139), False, 'import dash\n')] |
from torch_rgcn.utils import *
from torch.nn.modules.module import Module
from torch.nn.parameter import Parameter
from torch import nn
import math
import torch
class DistMult(Module):
""" DistMult scoring function (from https://arxiv.org/pdf/1412.6575.pdf) """
def __init__(self,
indim,
... | [
"torch.nn.init.zeros_",
"torch.reshape",
"torch.mm",
"torch.nn.functional.dropout",
"torch.add",
"torch.cuda.is_available",
"torch.einsum",
"torch.spmm",
"torch.nn.init.calculate_gain",
"torch.no_grad",
"torch.empty",
"torch.FloatTensor",
"torch.cat",
"torch.ones"
] | [((10928, 10985), 'torch.ones', 'torch.ones', (['num_triples'], {'dtype': 'torch.float', 'device': 'device'}), '(num_triples, dtype=torch.float, device=device)\n', (10938, 10985), False, 'import torch\n'), ((21515, 21572), 'torch.ones', 'torch.ones', (['num_triples'], {'dtype': 'torch.float', 'device': 'device'}), '(nu... |
#* Importing Libraries
import json
import traceback
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import HttpResponse, response
from django.shortcuts import redirect
#* Relative Imports
from .utils import authentication as auth
#* Initializing Logs
from common... | [
"json.loads",
"django.shortcuts.redirect",
"rest_framework.response.Response"
] | [((6417, 6472), 'django.shortcuts.redirect', 'redirect', (['"""https://feasta-client-side.vercel.app/login"""'], {}), "('https://feasta-client-side.vercel.app/login')\n", (6425, 6472), False, 'from django.shortcuts import redirect\n'), ((6596, 6649), 'django.shortcuts.redirect', 'redirect', (['"""https://feasta-admin-a... |
################################################################################
import sys, types, os
from xml.etree.ElementTree import Comment, ProcessingInstruction, QName
from xml.etree.ElementTree import _encode, _escape_cdata, _escape_attrib
from xml.etree.ElementTree import ElementTree, Element, _ElementInterf... | [
"xml.etree.ElementTree._escape_cdata",
"xml.etree.ElementTree._escape_attrib",
"xml.etree.ElementTree.Element",
"sys.stderr.write",
"xml.etree.ElementTree.ElementTree.__init__",
"xml.etree.ElementTree._encode",
"xml.etree.ElementTree._ElementInterface.__init__"
] | [((2754, 2780), 'xml.etree.ElementTree.ElementTree.__init__', 'ElementTree.__init__', (['self'], {}), '(self)\n', (2774, 2780), False, 'from xml.etree.ElementTree import ElementTree, Element, _ElementInterface\n'), ((2831, 2848), 'xml.etree.ElementTree.Element', 'Element', (['root_tag'], {}), '(root_tag)\n', (2838, 284... |
"""The `Try` type is a simpler `Result` type that pins the error type
to Exception.
Everything else is the same as `Result`, just simpler to use.
"""
from typing import TypeVar
from .result import Error, Ok, Result
_TSource = TypeVar("_TSource")
Try = Result[_TSource, Exception]
class Success(Ok[_TSource, Excep... | [
"typing.TypeVar"
] | [((231, 250), 'typing.TypeVar', 'TypeVar', (['"""_TSource"""'], {}), "('_TSource')\n", (238, 250), False, 'from typing import TypeVar\n')] |
#!/usr/bin/env python
# coding: utf-8
# # GOOD READ REVIEWS
# In[1]:
from bs4 import BeautifulSoup
import requests
import pandas as pd
import re
# In[26]:
HEADERS = ({'User-Agent':
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36',
... | [
"bs4.BeautifulSoup",
"pandas.DataFrame",
"requests.get",
"pandas.read_csv"
] | [((495, 529), 'requests.get', 'requests.get', (['URL'], {'headers': 'HEADERS'}), '(URL, headers=HEADERS)\n', (507, 529), False, 'import requests\n'), ((583, 614), 'bs4.BeautifulSoup', 'BeautifulSoup', (['content1', '"""lxml"""'], {}), "(content1, 'lxml')\n", (596, 614), False, 'from bs4 import BeautifulSoup\n'), ((1097... |
'''
Extracts embeddings from ESM models.
'''
import argparse
from collections import defaultdict
import os
import pathlib
import numpy as np
import pandas as pd
import torch
from esm import Alphabet, FastaBatchedDataset, ProteinBertModel, pretrained, BatchConverter
from utils import read_fasta, save
criterion = tor... | [
"torch.nn.CrossEntropyLoss",
"argparse.ArgumentParser",
"esm.FastaBatchedDataset.from_file",
"torch.unsqueeze",
"os.path.join",
"esm.pretrained.load_model_and_alphabet",
"torch.tensor",
"torch.cuda.is_available",
"numpy.concatenate",
"torch.utils.data.DataLoader",
"torch.no_grad"
] | [((317, 360), 'torch.nn.CrossEntropyLoss', 'torch.nn.CrossEntropyLoss', ([], {'reduction': '"""none"""'}), "(reduction='none')\n", (342, 360), False, 'import torch\n'), ((397, 527), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Extract per-token representations and model outputs for seq... |
import asyncio
import pytest # type: ignore
from database_operator.databases import Database, PostgresConnection
from database_operator.handlers import filter_on_postgres_update
EXTENSIONS_BEFORE = ["postgis", "postrest"]
EXTENSIONS_AFTER = ["mathlib", "postgis"]
DATABASE_FIELD_MAP = {"database": "DATABASE-NAME"}
... | [
"database_operator.databases.Database.from_spec",
"database_operator.handlers.filter_on_postgres_update",
"database_operator.databases.PostgresConnection"
] | [((335, 391), 'database_operator.databases.PostgresConnection', 'PostgresConnection', (['"""test"""', '"""test"""', '"""test"""', '(5432)', '"""test"""'], {}), "('test', 'test', 'test', 5432, 'test')\n", (353, 391), False, 'from database_operator.databases import Database, PostgresConnection\n'), ((908, 970), 'database... |
# Generated by Django 2.0.6 on 2019-11-15 09:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('apimb', '0006_auto_20191115_0536'),
]
operations = [
migrations.AddField(
model_name='balance',
name='round_bal',
... | [
"django.db.models.IntegerField"
] | [((336, 366), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'null': '(True)'}), '(null=True)\n', (355, 366), False, 'from django.db import migrations, models\n')] |
import random
for num in range(1):
number = random.randint(1, 101)
entered_number = input("Guess a number:")
entered_number = int(entered_number)
if entered_number > number:
print("You were off by ", entered_number - number)
print("The random number generated was ", number)
elif entered_number... | [
"random.randint"
] | [((52, 74), 'random.randint', 'random.randint', (['(1)', '(101)'], {}), '(1, 101)\n', (66, 74), False, 'import random\n')] |
#!/usr/bin/env python
# Environment.py
# Copyright (C) 2006 CCLRC, <NAME>
#
# This code is distributed under the BSD license, a copy of which is
# included in the root directory of this package.
#
# 18th September 2006
#
# A handler for matters of the operating environment, which will impact
# on data harvesting,... | [
"os.statvfs",
"xia2.Handlers.Streams.Debug.write",
"ctypes.c_ulonglong",
"ctypes.pointer",
"ctypes.c_wchar_p",
"os.path.exists",
"os.path.split",
"platform.system",
"resource.setrlimit",
"inspect.stack",
"libtbx.introspection.number_of_processors",
"os.access",
"tempfile.mkdtemp",
"xia2.Ha... | [((588, 605), 'os.getenv', 'os.getenv', (['"""PATH"""'], {}), "('PATH')\n", (597, 605), False, 'import os\n'), ((1471, 1482), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1480, 1482), False, 'import os\n'), ((1927, 1943), 'os.statvfs', 'os.statvfs', (['path'], {}), '(path)\n', (1937, 1943), False, 'import os\n'), ((224... |
"""
百度分类API:
pip install baidu-aip
"""
import time
import os
import sys
import codecs
import json
import traceback
from tqdm import tqdm
from aip import AipNlp
sys.path.insert(0, './') # 定义搜索路径的优先顺序,序号从0开始,表示最大优先级
from data import baidu_config # noqa
""" 你的 APPID AK SK """
APP_ID = baidu_config.APP_ID # '你的 App ID... | [
"sys.path.insert",
"myClue.tools.file.read_file_texts",
"aip.AipNlp",
"myClue.tools.file.init_file_path",
"tqdm.tqdm",
"json.dumps",
"time.sleep",
"codecs.open",
"traceback.print_exc"
] | [((161, 185), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""./"""'], {}), "(0, './')\n", (176, 185), False, 'import sys\n'), ((435, 470), 'aip.AipNlp', 'AipNlp', (['APP_ID', 'API_KEY', 'SECRET_KEY'], {}), '(APP_ID, API_KEY, SECRET_KEY)\n', (441, 470), False, 'from aip import AipNlp\n'), ((1512, 1539), 'myClue.tool... |
from collections import Counter
class Solution:
def subdomainVisits(self, cpdomains):
table = Counter()
for data in cpdomains:
data = data.split(" ")
count = int(data[0])
domains = data[1].split(".")
for i in range(len(domains)):
doma... | [
"collections.Counter"
] | [((108, 117), 'collections.Counter', 'Counter', ([], {}), '()\n', (115, 117), False, 'from collections import Counter\n')] |
import socket
import select
import Macro
import sys
from Error import eprint
class Socket():
def __init__(self, optManager):
self.optManager = optManager
self.initSocket()
def __del__(self):
self.socket.close()
def initSocket(self):
try:
self.socket = socket.so... | [
"select.select",
"Error.eprint",
"socket.socket",
"sys.exit"
] | [((311, 360), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (324, 360), False, 'import socket\n'), ((1673, 1715), 'select.select', 'select.select', (['[self.socket]', '[]', '[]', '(0.05)'], {}), '([self.socket], [], [], 0.05)\n', (1686, 1715)... |
from pyramid.httpexceptions import (
HTTPBadRequest,
HTTPFound,
)
from pyramid.security import (
remember,
forget,
)
from deform import Form, ValidationFailure, Button
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm.exc import NoResultFound
from .models import SASession, BaseUser
from .for... | [
"pyramid.httpexceptions.HTTPBadRequest",
"pyramid.security.forget",
"deform.Button",
"pyramid.httpexceptions.HTTPFound",
"pyramid.security.remember"
] | [((9933, 9948), 'pyramid.security.forget', 'forget', (['request'], {}), '(request)\n', (9939, 9948), False, 'from pyramid.security import remember, forget\n'), ((571, 626), 'pyramid.httpexceptions.HTTPBadRequest', 'HTTPBadRequest', (['"""Your session seems to have timed out."""'], {}), "('Your session seems to have tim... |
#!/usr/bin/env python3
# Copyright 2020 The Chromium OS 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 os
import unittest
from cros.factory.gooftool import gbb
_TEST_DATA_PATH = os.path.join(os.path.dirname(__file__), 'testda... | [
"unittest.main",
"os.path.dirname",
"os.path.join"
] | [((342, 383), 'os.path.join', 'os.path.join', (['_TEST_DATA_PATH', '"""test_gbb"""'], {}), "(_TEST_DATA_PATH, 'test_gbb')\n", (354, 383), False, 'import os\n'), ((286, 311), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (301, 311), False, 'import os\n'), ((989, 1004), 'unittest.main', 'unitt... |
"""Communication Services List
This file calculates the top 5 stocks list by marketcap
"""
# Import modules
import csv
from pathlib import Path
import pandas as pd
def top_5_communicatoin_services_stocks_by_marketcap(sp500_w_marketcap, communication_services, communication_services_top_5):
sp500_w_marketcap = pd... | [
"pathlib.Path"
] | [((330, 379), 'pathlib.Path', 'Path', (['"""../Resources/stock_industry_marketcap.csv"""'], {}), "('../Resources/stock_industry_marketcap.csv')\n", (334, 379), False, 'from pathlib import Path\n')] |
# coding=utf-8
# Copyright 2021 The Google Flax Team Authors and The HuggingFace Inc. team.
#
# 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
... | [
"flax.linen.Dense",
"flax.core.frozen_dict.unfreeze",
"flax.linen.combine_masks",
"flax.linen.tanh",
"jax.random.split",
"jax.random.PRNGKey",
"jax.nn.initializers.normal",
"jax.numpy.full",
"jax.numpy.asarray",
"jax.numpy.ones_like",
"jax.lax.dynamic_update_slice",
"flax.traverse_util.unflatt... | [((9065, 9131), 'flax.linen.LayerNorm', 'nn.LayerNorm', ([], {'epsilon': 'self.config.layer_norm_eps', 'dtype': 'self.dtype'}), '(epsilon=self.config.layer_norm_eps, dtype=self.dtype)\n', (9077, 9131), True, 'import flax.linen as nn\n'), ((9155, 9203), 'flax.linen.Dropout', 'nn.Dropout', ([], {'rate': 'self.config.hidd... |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
from torch import Tensor
from mmflow.ops import build_operators
class LinkOutput:
"""The link output between two estimators in FlowNet2."""
def __init__(self) -> None:
self.upsample_flow = None
self.scaled_flo... | [
"torch.norm",
"mmflow.ops.build_operators",
"torch.nn.Upsample"
] | [((1404, 1429), 'mmflow.ops.build_operators', 'build_operators', (['warp_cfg'], {}), '(warp_cfg)\n', (1419, 1429), False, 'from mmflow.ops import build_operators\n'), ((1454, 1503), 'torch.nn.Upsample', 'nn.Upsample', ([], {'scale_factor': 'scale_factor', 'mode': 'mode'}), '(scale_factor=scale_factor, mode=mode)\n', (1... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name:decomposition
Description : 数据降维实例
旨在说明使用方法
Email : <EMAIL>
Date:2018/1/2
"""
from collections import namedtuple
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets im... | [
"sklearn.decomposition.MiniBatchDictionaryLearning",
"sklearn.decomposition.KernelPCA",
"sklearn.decomposition.FastICA",
"seaborn.set",
"seaborn.color_palette",
"sklearn.decomposition.PCA",
"sklearn.decomposition.SparsePCA",
"matplotlib.pyplot.scatter",
"sklearn.decomposition.IncrementalPCA",
"col... | [((636, 820), 'sklearn.datasets.make_classification', 'make_classification', ([], {'n_samples': '(1000)', 'n_features': '(5)', 'n_informative': '(2)', 'n_redundant': '(0)', 'n_repeated': '(0)', 'n_classes': '(3)', 'n_clusters_per_class': '(1)', 'class_sep': '(1.5)', 'flip_y': '(0.01)', 'random_state': '(0)'}), '(n_samp... |
from setuptools import setup, find_packages
setup(name='website-downloader',
description='A simple website downloader',
long_description='A simple website downloader',
packages=find_packages(exclude=["*tests*"]),
package_data={'': ['*.yaml']},
version='1.0.0',
install_requires=[
... | [
"setuptools.find_packages"
] | [((197, 231), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['*tests*']"}), "(exclude=['*tests*'])\n", (210, 231), False, 'from setuptools import setup, find_packages\n')] |
# Copyright (c) 2022, NVIDIA CORPORATION.
import pytest
from pandas import NA
from dask import dataframe as dd
from dask_cudf.tests.utils import _make_random_frame
@pytest.mark.parametrize(
"func",
[
lambda x: x + 1,
lambda x: x - 0.5,
lambda x: 2 if x is NA else 2 + (x + 1) / 4.1,
... | [
"dask.dataframe.assert_eq",
"pytest.mark.parametrize",
"dask.dataframe.from_pandas",
"dask_cudf.tests.utils._make_random_frame"
] | [((170, 304), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""func"""', '[lambda x: x + 1, lambda x: x - 0.5, lambda x: 2 if x is NA else 2 + (x + 1\n ) / 4.1, lambda x: 42]'], {}), "('func', [lambda x: x + 1, lambda x: x - 0.5, lambda\n x: 2 if x is NA else 2 + (x + 1) / 4.1, lambda x: 42])\n", (193,... |
# Copyright (C) 2019 Apple Inc. 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 list of conditions and the f... | [
"flask.redirect",
"flask.abort",
"resultsdbpy.flask_support.util.query_as_kwargs"
] | [((1757, 1774), 'resultsdbpy.flask_support.util.query_as_kwargs', 'query_as_kwargs', ([], {}), '()\n', (1772, 1774), False, 'from resultsdbpy.flask_support.util import AssertRequest, query_as_kwargs\n'), ((2261, 2278), 'resultsdbpy.flask_support.util.query_as_kwargs', 'query_as_kwargs', ([], {}), '()\n', (2276, 2278), ... |
import numpy as np
def Gini_index(Y_data):
gini = 0
#========= Edit here ==========
gini = 1 - np.sum([(count / len(Y_data)) ** 2 for _, count in zip(*np.unique(Y_data, return_counts=True))])
#====================================
return gini
def Entropy(Y_data):
entropy = 0
# ===== ... | [
"numpy.exp",
"numpy.log2",
"numpy.sqrt",
"numpy.unique"
] | [((836, 855), 'numpy.unique', 'np.unique', (['col_data'], {}), '(col_data)\n', (845, 855), True, 'import numpy as np\n'), ((1612, 1631), 'numpy.exp', 'np.exp', (['(z ** 2 / -2)'], {}), '(z ** 2 / -2)\n', (1618, 1631), True, 'import numpy as np\n'), ((1641, 1659), 'numpy.sqrt', 'np.sqrt', (['(2 * np.pi)'], {}), '(2 * np... |
from datetime import date
from flask import Flask, render_template, request, redirect, url_for, Response, session, flash
from flask_mongoengine import MongoEngine, Document
from flask_wtf import FlaskForm
from PIL import Image, ImageDraw
from wtforms import StringField, PasswordField
from wtforms import form
fro... | [
"flask_mail.Mail",
"flask_login.LoginManager",
"flask_mongoengine.MongoEngine",
"flask.Flask"
] | [((791, 827), 'flask.Flask', 'Flask', (['__name__'], {'template_folder': '"""."""'}), "(__name__, template_folder='.')\n", (796, 827), False, 'from flask import Flask, render_template, request, redirect, url_for, Response, session, flash\n'), ((836, 845), 'flask_mail.Mail', 'Mail', (['app'], {}), '(app)\n', (840, 845),... |
"""
Tests tokenize_big_file function
"""
import unittest
import timeit
from memory_profiler import memory_usage
from lab_2.main import tokenize_big_file, tokenize_by_lines
class TokenizeBigFileTest(unittest.TestCase):
"""
Checks for tokenize_big_file function
"""
def test_tokenize_big_file_ideal_cas... | [
"timeit.default_timer",
"lab_2.main.tokenize_big_file",
"memory_profiler.memory_usage"
] | [((495, 530), 'lab_2.main.tokenize_big_file', 'tokenize_big_file', (['"""lab_2/data.txt"""'], {}), "('lab_2/data.txt')\n", (512, 530), False, 'from lab_2.main import tokenize_big_file, tokenize_by_lines\n'), ((950, 972), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (970, 972), False, 'import timeit... |
from bson import ObjectId
from odmantic import Model
class Player(Model):
name: str
level: int = 1
document = {"name": "Leeroy", "_id": ObjectId("5f8352a87a733b8b18b0cb27")}
user = Player.parse_doc(document)
print(repr(user))
#> Player(
#> id=ObjectId("5f8352a87a733b8b18b0cb27"),
#> name="Leeroy",... | [
"bson.ObjectId"
] | [((149, 185), 'bson.ObjectId', 'ObjectId', (['"""5f8352a87a733b8b18b0cb27"""'], {}), "('5f8352a87a733b8b18b0cb27')\n", (157, 185), False, 'from bson import ObjectId\n')] |
#%matplotlib inline
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
from sklearn.metrics import confusion_matrix
import time
from datetime import timedelta
import math
import os
tf.logging.set_verbosity(tf.logging.INFO)
log_dir = 'tmp/loopy-nn/board/loop004' # Tensorboard log dir
save_dir =... | [
"tensorflow.equal",
"tensorflow.get_variable",
"matplotlib.pyplot.ylabel",
"tensorflow.logging.set_verbosity",
"math.sqrt",
"tensorflow.examples.tutorials.mnist.input_data.read_data_sets",
"tensorflow.nn.softmax",
"tensorflow.reduce_mean",
"tensorflow.cast",
"numpy.arange",
"matplotlib.pyplot.im... | [((206, 247), 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.INFO'], {}), '(tf.logging.INFO)\n', (230, 247), True, 'import tensorflow as tf\n'), ((616, 670), 'tensorflow.examples.tutorials.mnist.input_data.read_data_sets', 'input_data.read_data_sets', (['"""data/MNIST/"""'], {'one_hot': '... |
import pypeln as pl
from copy import copy, deepcopy
def generator():
yield from [1, 2, 3]
# stage = lambda: generator()
stage = [1, 2, 3]
stage = pl.process.map(lambda x: x + 1, stage)
# stage0 = deepcopy(stage)
print(list(stage))
print(list(stage))
print(pl.Element)
| [
"pypeln.process.map"
] | [((154, 192), 'pypeln.process.map', 'pl.process.map', (['(lambda x: x + 1)', 'stage'], {}), '(lambda x: x + 1, stage)\n', (168, 192), True, 'import pypeln as pl\n')] |
import numpy as np
import sys,os
import configparser
class InputFile():
"""Class for packaging all input/config file options together.
**Inputs**
----------
inputfilename : string
String specifying the desired inputfile name.
**Options**
----------
======================... | [
"configparser.ConfigParser"
] | [((1502, 1529), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (1527, 1529), False, 'import configparser\n')] |
from autogluon.core.utils.feature_selection import *
from autogluon.core.utils.utils import unevaluated_fi_df_template
import numpy as np
from numpy.core.fromnumeric import sort
import pandas as pd
import pytest
def evaluated_fi_df_template(features, importance=None, n=None):
rng = np.random.default_rng(0)
im... | [
"pandas.DataFrame",
"pandas.concat",
"numpy.random.default_rng",
"autogluon.core.utils.utils.unevaluated_fi_df_template"
] | [((289, 313), 'numpy.random.default_rng', 'np.random.default_rng', (['(0)'], {}), '(0)\n', (310, 313), True, 'import numpy as np\n'), ((334, 366), 'pandas.DataFrame', 'pd.DataFrame', (["{'name': features}"], {}), "({'name': features})\n", (346, 366), True, 'import pandas as pd\n'), ((1285, 1312), 'pandas.DataFrame', 'p... |
##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. law. Dissemination
# to non... | [
"dynamicserialize.dstypes.com.raytheon.uf.common.dataplugin.gfe.server.lock.LockTable",
"dynamicserialize.dstypes.com.raytheon.uf.common.dataplugin.gfe.server.lock.Lock"
] | [((2758, 2769), 'dynamicserialize.dstypes.com.raytheon.uf.common.dataplugin.gfe.server.lock.LockTable', 'LockTable', ([], {}), '()\n', (2767, 2769), False, 'from dynamicserialize.dstypes.com.raytheon.uf.common.dataplugin.gfe.server.lock import LockTable\n'), ((2667, 2705), 'dynamicserialize.dstypes.com.raytheon.uf.comm... |
# encoding: utf-8
"""
swatch.tests.test_writer
Solarized color palette using LAB data from
http://ethanschoonover.com/solarized
Copyright (c) 2019 <NAME> http://generic.cx/
All Rights Reserved
MIT Licensed, see LICENSE.TXT for details
"""
from __future__ import print_function
import unittest
class TestSwatchWriter(... | [
"unittest.main",
"json.load",
"os.path.join"
] | [((1959, 1974), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1972, 1974), False, 'import unittest\n'), ((566, 609), 'os.path.join', 'os.path.join', (['"""tests"""', '"""fixtures"""', 'basepath'], {}), "('tests', 'fixtures', basepath)\n", (578, 609), False, 'import swatch, os, json\n'), ((701, 723), 'json.load',... |
from unittest import mock
from unittest.mock import call
from django.test import override_settings
from lego.apps.external_sync.external import ldap
from lego.apps.users.constants import GROUP_COMMITTEE
from lego.apps.users.models import AbakusGroup, User
from lego.utils.test_utils import BaseTestCase
class LDAPTes... | [
"lego.apps.external_sync.external.ldap.LDAPSystem",
"lego.apps.users.models.User.objects.get",
"lego.apps.users.models.AbakusGroup.objects.get",
"unittest.mock.call",
"lego.apps.users.models.AbakusGroup.objects.all",
"django.test.override_settings",
"lego.apps.users.models.User.objects.all",
"lego.app... | [((410, 469), 'unittest.mock.patch', 'mock.patch', (['"""lego.apps.external_sync.external.ldap.LDAPLib"""'], {}), "('lego.apps.external_sync.external.ldap.LDAPLib')\n", (420, 469), False, 'from unittest import mock\n'), ((1044, 1092), 'django.test.override_settings', 'override_settings', ([], {'LDAP_GROUPS': "['UserAdm... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2010-2012 <NAME>
from os import urandom
import datetime
from django.db.models import *
from django.utils.translation import ugettext_lazy as _
from django.urls import reverse
from django.core.validators import validate_comma_separated_integer_list
ACCOMMNIGHTS_CHOICES = (
(... | [
"os.urandom",
"datetime.datetime.now",
"datetime.date.today",
"django.utils.translation.ugettext_lazy"
] | [((324, 336), 'django.utils.translation.ugettext_lazy', '_', (['"""1 night"""'], {}), "('1 night')\n", (325, 336), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((345, 358), 'django.utils.translation.ugettext_lazy', '_', (['"""2 nights"""'], {}), "('2 nights')\n", (346, 358), True, 'from django.ut... |
import cv2
import random
import numpy as np
IMG_WIDTH = 1200
IMG_HEIGHT = 800
WATERMARK_WIDTH = 256
WATERMARK_HEIGHT = 256
IMG_SIZE = IMG_HEIGHT * IMG_WIDTH
WATERMARK_SIZE = WATERMARK_HEIGHT * WATERMARK_WIDTH
KEY = 1001
THRESH = 75
def mean_neighbour(img, x, y):
val = 0
num = 0
i = x
j = y
if i ... | [
"numpy.zeros",
"random.seed"
] | [((1496, 1514), 'random.seed', 'random.seed', ([], {'a': 'KEY'}), '(a=KEY)\n', (1507, 1514), False, 'import random\n'), ((1701, 1759), 'numpy.zeros', 'np.zeros', (['(WATERMARK_WIDTH, WATERMARK_HEIGHT, 1)', 'np.uint8'], {}), '((WATERMARK_WIDTH, WATERMARK_HEIGHT, 1), np.uint8)\n', (1709, 1759), True, 'import numpy as np\... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
"""字典形式导入数据"""
x1 = {'Measure_1': [28.4,28.9,29.0,28.4,28.6],
'Measure_2': [28.4,29.0,29.1,28.5,28.6],
'Measure_3': [28.4,29.0,29.1,28.5,28.6]} # A测定员
x2 = {'Measure_1': [28.5,28.8,29.0,28.5,28.6],
'Measure_2': [28... | [
"numpy.ones",
"pandas.DataFrame",
"pandas.concat",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((597, 613), 'pandas.DataFrame', 'pd.DataFrame', (['x1'], {}), '(x1)\n', (609, 613), True, 'import pandas as pd\n'), ((779, 795), 'pandas.DataFrame', 'pd.DataFrame', (['x2'], {}), '(x2)\n', (791, 795), True, 'import pandas as pd\n'), ((961, 977), 'pandas.DataFrame', 'pd.DataFrame', (['x3'], {}), '(x3)\n', (973, 977), ... |
from boto3.dynamodb.conditions import Key
from botocore.exceptions import ClientError
from api.common import validation, errors
from api.data_access import dynamo_db as db
from api.model.model import FlashcardModel
from api.utils.id_utils import generate_id
table = db.dynamo_db.Table('qm_flashcard')
def delete(_id)... | [
"api.common.validation.validate_item_exists",
"api.model.model.FlashcardModel.from_dynamo",
"api.common.validation.validate_items_exist",
"api.common.errors.ApiError",
"api.utils.id_utils.generate_id",
"boto3.dynamodb.conditions.Key",
"api.data_access.dynamo_db.dynamo_db.Table"
] | [((268, 302), 'api.data_access.dynamo_db.dynamo_db.Table', 'db.dynamo_db.Table', (['"""qm_flashcard"""'], {}), "('qm_flashcard')\n", (286, 302), True, 'from api.data_access import dynamo_db as db\n'), ((938, 988), 'api.common.validation.validate_items_exist', 'validation.validate_items_exist', (['response', 'quietly'],... |
"""
File: RunnerFactory.py
License: Part of the PIRA project. Licensed under BSD 3 clause license. See LICENSE.txt file at https://github.com/jplehr/pira/LICENSE.txt
Description: Module to create different Runner objects, depending on the configuration.
"""
import lib.Logging as L
from lib.Configuration import PiraCon... | [
"lib.Runner.LocalScalingRunner",
"lib.Configuration.PiraConfigErrorException",
"lib.ProfileSink.PiraOneProfileSink",
"lib.Logging.get_logger"
] | [((2515, 2562), 'lib.Runner.LocalScalingRunner', 'LocalScalingRunner', (['self._config', 'attached_sink'], {}), '(self._config, attached_sink)\n', (2533, 2562), False, 'from lib.Runner import LocalRunner, LocalScalingRunner\n'), ((742, 762), 'lib.ProfileSink.PiraOneProfileSink', 'PiraOneProfileSink', ([], {}), '()\n', ... |
from torch import nn
import torch
class ShowAndTellWithPretrainedImageEmbeddings(nn.Module):
def __init__(
self, dict_size,
embedding_dim, hidden_size,
data_mode, pad_idx=None):
super(ShowAndTellWithPretrainedImageEmbeddings, self).__init__()
assert data_mode =... | [
"torch.nn.ReLU",
"torch.nn.Softmax",
"torch.nn.LSTM",
"torch.nn.LSTMCell",
"torch.mean",
"torch.stack",
"torch.nn.utils.rnn.pack_sequence",
"torch.nn.RNN",
"torch.transpose",
"torch.nn.utils.rnn.PackedSequence",
"torch.cat",
"torch.sum",
"torch.nn.Linear",
"torch.nn.Embedding"
] | [((495, 550), 'torch.nn.Linear', 'nn.Linear', ([], {'in_features': '(2048)', 'out_features': 'embedding_dim'}), '(in_features=2048, out_features=embedding_dim)\n', (504, 550), False, 'from torch import nn\n'), ((673, 765), 'torch.nn.Embedding', 'nn.Embedding', ([], {'num_embeddings': 'dict_size', 'embedding_dim': 'embe... |
import torch
import torch.nn as nn
import numpy as np
import math
from model import common
def make_model(args, parent=False):
return DenseSkip(args)
class DenseBlock(nn.Module):
def __init__(self, growth_rate, n_feat_in, n_layers, conv=common.default_conv):
super(DenseBlock, self).__init__()
... | [
"torch.nn.ReLU",
"model.common.DenseLayer",
"model.common.Upsampler",
"torch.nn.Sequential",
"torch.nn.Conv2d",
"model.common.MeanShift",
"torch.cat"
] | [((789, 809), 'torch.nn.Sequential', 'nn.Sequential', (['*body'], {}), '(*body)\n', (802, 809), True, 'import torch.nn as nn\n'), ((1022, 1035), 'torch.nn.ReLU', 'nn.ReLU', (['(True)'], {}), '(True)\n', (1029, 1035), True, 'import torch.nn as nn\n'), ((1351, 1402), 'model.common.MeanShift', 'common.MeanShift', (['args.... |
# -*- coding: utf-8 -*-
# Author : <NAME>
# e-mail : <EMAIL>
# Powered by Seculayer © 2021 Service Model Team, R&D Center.
import os
import json
import joblib
from typing import Callable
from tensorflow.keras.preprocessing.text import tokenizer_from_json
from mlps.common.utils.FileUtils import FileUtils
from mlps.comm... | [
"json.load",
"json.dump",
"tensorflow.keras.preprocessing.text.tokenizer_from_json",
"mlps.common.utils.FileUtils.FileUtils.mkdir"
] | [((1308, 1334), 'mlps.common.utils.FileUtils.FileUtils.mkdir', 'FileUtils.mkdir', (['dir_model'], {}), '(dir_model)\n', (1323, 1334), False, 'from mlps.common.utils.FileUtils import FileUtils\n'), ((1963, 1989), 'mlps.common.utils.FileUtils.FileUtils.mkdir', 'FileUtils.mkdir', (['dir_model'], {}), '(dir_model)\n', (197... |
import os
import json
import time
import torch
import itertools
import detectron2.utils.comm as comm
from fvcore.common.file_io import PathManager
from detectron2.config import global_cfg
from detectron2.engine.train_loop import HookBase
from detectron2.evaluation.testing import flatten_results_dict
__all__ = ["EvalHo... | [
"detectron2.utils.comm.is_main_process",
"detectron2.utils.comm.synchronize",
"os.path.join",
"detectron2.evaluation.testing.flatten_results_dict",
"json.dump"
] | [((2729, 2747), 'detectron2.utils.comm.synchronize', 'comm.synchronize', ([], {}), '()\n', (2745, 2747), True, 'import detectron2.utils.comm as comm\n'), ((1531, 1560), 'detectron2.evaluation.testing.flatten_results_dict', 'flatten_results_dict', (['results'], {}), '(results)\n', (1551, 1560), False, 'from detectron2.e... |
# Copyright Amazon.com, Inc. or its affiliates. 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
#
# Unl... | [
"os.path.getsize",
"aws_codeseeder.services.s3.upload_file",
"datetime.datetime.utcnow",
"aws_codeseeder.LOGGER.debug",
"os.path.isfile",
"aws_codeseeder.LOGGER.info",
"time.time",
"typing.cast",
"aws_codeseeder.services._utils.boto3_client"
] | [((4773, 4803), 'aws_codeseeder.services._utils.boto3_client', 'boto3_client', (['"""cloudformation"""'], {}), "('cloudformation')\n", (4785, 4803), False, 'from aws_codeseeder.services._utils import boto3_client\n'), ((5056, 5099), 'typing.cast', 'cast', (['str', "resp['Stacks'][0]['StackStatus']"], {}), "(str, resp['... |
#zerosOnesAndLike.py
import numpy as np
list_of_lists = [[1,2,3], [4,5,6], [7,8,9]]
array_of_arrays = np.array(list_of_lists)
zeros_like_array = np.zeros_like(list_of_lists)
ones_like_array = np.ones_like(list_of_lists)
empty_like_array = np.empty_like(list_of_lists)
print("list_of_lists:", list_of_lists, sep="\n")
pr... | [
"numpy.empty_like",
"numpy.array",
"numpy.zeros_like",
"numpy.ones_like"
] | [((102, 125), 'numpy.array', 'np.array', (['list_of_lists'], {}), '(list_of_lists)\n', (110, 125), True, 'import numpy as np\n'), ((145, 173), 'numpy.zeros_like', 'np.zeros_like', (['list_of_lists'], {}), '(list_of_lists)\n', (158, 173), True, 'import numpy as np\n'), ((192, 219), 'numpy.ones_like', 'np.ones_like', (['... |
import re
from presenters.ClassyPresenter import ClassyPresenter
from models.pyt import PythonTypeDefault as ptd
from lib.Language import Language
class Classy2Presenter(ClassyPresenter):
def __init__(self, cl):
super(Classy2Presenter, self).__init__(cl)
self.initVariableNamesWithCommas = self.get_init_variable_... | [
"models.pyt.PythonTypeDefault.get_python_type_default",
"presenters.ClassyPresenter.ClassyPresenter.unqueue_type"
] | [((2958, 2998), 'presenters.ClassyPresenter.ClassyPresenter.unqueue_type', 'ClassyPresenter.unqueue_type', (['param.type'], {}), '(param.type)\n', (2986, 2998), False, 'from presenters.ClassyPresenter import ClassyPresenter\n'), ((3077, 3114), 'presenters.ClassyPresenter.ClassyPresenter.unqueue_type', 'ClassyPresenter.... |
import re
from typing import Optional
class BaseModel:
r"""
The Base Class for Model objects.
.. container:: operations
.. describe:: x == y
Checks if two models have the same slug.
.. describe:: x != y
Checks if two models do not have the same slug.
.... | [
"re.sub",
"re.compile"
] | [((1594, 1655), 're.compile', 're.compile', (['"""<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});"""'], {}), "('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')\n", (1604, 1655), False, 'import re\n'), ((1677, 1710), 're.sub', 're.sub', (['html_cleaner', '""""""', 'content'], {}), "(html_cleaner, '', content)\n", (168... |
import jax
import jax.numpy as jnp
from flowjax.flows import Flow
from jax.scipy.special import logsumexp
from tqdm import tqdm
# Too memory intensive
# def robust_posterior_log_prob(flow: Flow, theta: jnp.ndarray, denoised: jnp.ndarray):
# """Given a flow q(theta|x), a matrix of theta, and denoised observations,... | [
"jax.numpy.expand_dims",
"tqdm.tqdm",
"jax.numpy.log",
"jax.numpy.array",
"jax.vmap",
"jax.numpy.mean"
] | [((1206, 1222), 'jax.numpy.array', 'jnp.array', (['probs'], {}), '(probs)\n', (1215, 1222), True, 'import jax.numpy as jnp\n'), ((1354, 1384), 'jax.numpy.expand_dims', 'jnp.expand_dims', (['theta_true', '(0)'], {}), '(theta_true, 0)\n', (1369, 1384), True, 'import jax.numpy as jnp\n'), ((1077, 1088), 'tqdm.tqdm', 'tqdm... |
"""
.. module:: sparse_rep
.. moduleauthor:: <NAME>
.. moduleauthor:: <NAME>
The original SparsePZ code to be found at https://github.com/mgckind/SparsePz
This module reorganizes it for usage by DESC within qp, and is python3 compliant.
"""
__author__ = '<NAME>'
import numpy as np
from scipy.special import voigt_prof... | [
"scipy.linalg.cho_solve",
"numpy.ceil",
"scipy.special.voigt_profile",
"scipy.integrate.trapz",
"numpy.sqrt",
"numpy.where",
"numpy.max",
"numpy.array",
"numpy.dot",
"numpy.linspace",
"numpy.zeros",
"scipy.linalg.solve_triangular",
"scipy.linalg.norm",
"numpy.finfo",
"numpy.zeros_like",
... | [((637, 653), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (650, 653), True, 'import numpy as np\n'), ((857, 887), 'numpy.where', 'np.where', (['(pdf >= cut)', 'pdf', '(0.0)'], {}), '(pdf >= cut, pdf, 0.0)\n', (865, 887), True, 'import numpy as np\n'), ((2034, 2064), 'numpy.linspace', 'np.linspace', (['mu... |
#!/usr/bin/env python
"""
@package mi.dataset.parser.test.test_dosta_abcdjm_dcl
@file marine-integrations/mi/dataset/parser/test/test_dosta_abcdjm_dcl.py
@author <NAME>
@brief Test code for a Dosta_abcdjm_dcl data parser
In the following files, Metadata consists of 4 records
and Garbled consist of 3 records.... | [
"nose.plugins.attrib.attr",
"mi.dataset.parser.dosta_abcdjm_dcl.DostaAbcdjmDclTelemeteredInstrumentDataParticle",
"os.path.join",
"mi.core.log.get_logger",
"mi.dataset.parser.dosta_abcdjm_dcl.DostaAbcdjmDclRecoveredParser",
"mi.dataset.parser.dosta_abcdjm_dcl.DostaAbcdjmDclTelemeteredParser",
"mi.datase... | [((1797, 1809), 'mi.core.log.get_logger', 'get_logger', ([], {}), '()\n', (1807, 1809), False, 'from mi.core.log import get_logger\n'), ((28324, 28348), 'nose.plugins.attrib.attr', 'attr', (['"""UNIT"""'], {'group': '"""mi"""'}), "('UNIT', group='mi')\n", (28328, 28348), False, 'from nose.plugins.attrib import attr\n')... |
from rest_framework import routers
import API.viewsets as Viewsets
# these are the API methods
api_router = routers.SimpleRouter(trailing_slash=False)
api_router.register(r'posts', Viewsets.PostsViewSet)
api_router.register(r'author', Viewsets.AuthorViewSet)
api_router.register(r'friendrequest', Viewsets.FriendRequest... | [
"rest_framework.routers.SimpleRouter"
] | [((109, 151), 'rest_framework.routers.SimpleRouter', 'routers.SimpleRouter', ([], {'trailing_slash': '(False)'}), '(trailing_slash=False)\n', (129, 151), False, 'from rest_framework import routers\n')] |
import io
import os
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
img = Image.new('RGB', (300, 28))
d = ImageDraw.Draw(img)
font = ImageFont.truetype('fonts/whitney.ttf', size=20)
d.text(font=font, xy=(4, 4), text='xz72', fill=(255, 255, 255))
img.save('test.png') | [
"PIL.Image.new",
"PIL.ImageDraw.Draw",
"PIL.ImageFont.truetype"
] | [((102, 129), 'PIL.Image.new', 'Image.new', (['"""RGB"""', '(300, 28)'], {}), "('RGB', (300, 28))\n", (111, 129), False, 'from PIL import Image\n'), ((134, 153), 'PIL.ImageDraw.Draw', 'ImageDraw.Draw', (['img'], {}), '(img)\n', (148, 153), False, 'from PIL import ImageDraw\n'), ((161, 209), 'PIL.ImageFont.truetype', 'I... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from __future__ import annotations
import logging
import sys
import warnings
import cloudpickle
import json_tricks
import numpy
import yaml
import nni
def _minor_version_tuple(version_str: str) -> tuple[int, int]:
# If not a number, retur... | [
"logging.getLogger",
"warnings.warn"
] | [((642, 669), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (659, 669), False, 'import logging\n'), ((872, 899), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (889, 899), False, 'import logging\n'), ((1103, 1130), 'logging.getLogger', 'logging.getLogger', ... |
from imghdr import what
from os import getenv
from json import loads, dumps
import flask
from rockset import Client, Q
from flask_cors import CORS
from sys import argv
app = flask.Flask(__name__, static_folder='compendium/images')
CORS(app)
rs = Client(api_key=getenv('RS2_TOKEN') or argv[1], api_server='api.rs2.usw2.r... | [
"rockset.Q",
"os.getenv",
"flask_cors.CORS",
"flask.Flask",
"flask.redirect",
"imghdr.what"
] | [((175, 231), 'flask.Flask', 'flask.Flask', (['__name__'], {'static_folder': '"""compendium/images"""'}), "(__name__, static_folder='compendium/images')\n", (186, 231), False, 'import flask\n'), ((232, 241), 'flask_cors.CORS', 'CORS', (['app'], {}), '(app)\n', (236, 241), False, 'from flask_cors import CORS\n'), ((5246... |
import requests
import os,re,time,random
def download_mp4(url,dir):
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36Name','Referer':'http://91porn.com'}
req=requests.get(url=url)
filename=str(dir)+'/1.mp4'
with ope... | [
"re.findall",
"time.sleep",
"random.randint",
"requests.get"
] | [((255, 276), 'requests.get', 'requests.get', ([], {'url': 'url'}), '(url=url)\n', (267, 276), False, 'import requests\n'), ((586, 607), 'requests.get', 'requests.get', ([], {'url': 'url'}), '(url=url)\n', (598, 607), False, 'import requests\n'), ((708, 730), 'random.randint', 'random.randint', (['(1)', '(255)'], {}), ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# Copyright (c) 2014-2015 Nagravision S.A., Gemalto S.A.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided th... | [
"os.path.basename"
] | [((3595, 3620), 'os.path.basename', 'basename', (['task.targets[0]'], {}), '(task.targets[0])\n', (3603, 3620), False, 'from os.path import basename\n'), ((3448, 3473), 'os.path.basename', 'basename', (['task.targets[0]'], {}), '(task.targets[0])\n', (3456, 3473), False, 'from os.path import basename\n')] |
# Generated by Django 2.1.7 on 2019-03-06 12:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tasks', '0022_auto_20190305_2121'),
]
operations = [
migrations.AlterField(
model_name='tag',
name='username',
... | [
"django.db.models.CharField"
] | [((333, 378), 'django.db.models.CharField', 'models.CharField', ([], {'default': '"""sa"""', 'max_length': '(50)'}), "(default='sa', max_length=50)\n", (349, 378), False, 'from django.db import migrations, models\n')] |
from datetime import datetime
from datetime import timezone
import pytest
from resconfig.fields import Bool
from resconfig.fields import Datetime
from resconfig.fields import Float
from resconfig.fields import Int
from resconfig.fields import NullableBool
from resconfig.fields import NullableDatetime
from resconfig.f... | [
"datetime.datetime.fromtimestamp",
"pytest.raises"
] | [((2817, 2856), 'datetime.datetime.fromtimestamp', 'datetime.fromtimestamp', (['(0)', 'timezone.utc'], {}), '(0, timezone.utc)\n', (2839, 2856), False, 'from datetime import datetime\n'), ((814, 838), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (827, 838), False, 'import pytest\n'), ((1652, ... |
import cv2
import numpy as np
import os
import glob
import pickle
#from sklearn.preprocessing import normalize
current_file_path = os.path.dirname(os.path.abspath(__file__))
def save_obj(obj, name ):
with open(os.path.join(current_file_path,"calib_result", name + '.pkl'), 'wb') as f:
pickle.dump(obj, f)
... | [
"cv2.initUndistortRectifyMap",
"cv2.findChessboardCorners",
"pickle.dump",
"cv2.drawChessboardCorners",
"cv2.stereoRectify",
"cv2.stereoCalibrate",
"pickle.load",
"os.path.join",
"os.path.normpath",
"cv2.getOptimalNewCameraMatrix",
"numpy.zeros",
"cv2.calibrateCamera",
"os.path.abspath",
"... | [((148, 173), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (163, 173), False, 'import os\n'), ((923, 986), 'numpy.zeros', 'np.zeros', (['(1, CHECKERBOARD[0] * CHECKERBOARD[1], 3)', 'np.float32'], {}), '((1, CHECKERBOARD[0] * CHECKERBOARD[1], 3), np.float32)\n', (931, 986), True, 'import num... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-02-11 13:40
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rating', '0001_initial'),
]
operations = [
migrations.AlterField(
... | [
"django.db.models.PositiveSmallIntegerField"
] | [((387, 483), 'django.db.models.PositiveSmallIntegerField', 'models.PositiveSmallIntegerField', ([], {'choices': "[[0, 'RR'], [2, 'CRR'], [1, 'EMA'], [3, 'ONLINE']]"}), "(choices=[[0, 'RR'], [2, 'CRR'], [1, 'EMA'],\n [3, 'ONLINE']])\n", (419, 483), False, 'from django.db import migrations, models\n')] |
import io
import os
from setuptools import setup, find_packages
VERSION = "0.2"
with open(os.path.join(os.path.dirname(__file__), "README.md")) as readme:
README = readme.read()
setup(
name="runcode",
version=VERSION,
author="RunCode",
author_email="<EMAIL>",
url="https://github.com/runcode-... | [
"os.path.dirname",
"setuptools.find_packages"
] | [((471, 514), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['tests', 'tests.*']"}), "(exclude=['tests', 'tests.*'])\n", (484, 514), False, 'from setuptools import setup, find_packages\n'), ((105, 130), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (120, 130), False, 'import... |
import torch.nn as nn
import torch
class ConvLSTM_Cell(nn.Module):
"""
input:[B,in_channels,H,W]
hidden:[B,hidden_channels,H,W]
Ct:[B,hidden_channels,H,W]
:return ht, ct
"""
def __init__(self, in_channels, hidden_channels, kernel_size=3):
super(Co... | [
"torch.nn.Sigmoid",
"torch.mul",
"torch.nn.Tanh",
"torch.nn.ModuleList",
"torch.nn.Conv2d",
"torch.zeros",
"torch.randn",
"torch.cat"
] | [((6437, 6468), 'torch.randn', 'torch.randn', (['(10)', '(5)', '(3)', '(100)', '(200)'], {}), '(10, 5, 3, 100, 200)\n', (6448, 6468), False, 'import torch\n'), ((1091, 1100), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (1098, 1100), True, 'import torch.nn as nn\n'), ((1375, 1408), 'torch.cat', 'torch.cat', (['[input,... |
# example rss: http://www.theverge.com/apple/rss/index.xml
# import needs libs
import clipboard
import requests
import xml.etree.ElementTree as XmlET
# a function that takes in a url and prints rss
def pullRss(url):
# verify its a url
if not url.startswith("http"):
print("ERROR: invalid url")
return ""
# call u... | [
"xml.etree.ElementTree.fromstring",
"clipboard.get",
"requests.get"
] | [((602, 617), 'clipboard.get', 'clipboard.get', ([], {}), '()\n', (615, 617), False, 'import clipboard\n'), ((441, 462), 'xml.etree.ElementTree.fromstring', 'XmlET.fromstring', (['rss'], {}), '(rss)\n', (457, 462), True, 'import xml.etree.ElementTree as XmlET\n'), ((510, 531), 'requests.get', 'requests.get', ([], {'url... |
# 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.
"""Integrations tests for the LLVM CompilerGym environments."""
from typing import List
import gym
import pytest
import compiler_gym
from com... | [
"pytest.fail",
"tests.test_main.main",
"pytest.raises",
"gym.make"
] | [((4634, 4724), 'gym.make', 'gym.make', (['"""llvm-v0"""'], {'observation_space': '"""Autophase"""', 'reward_space': '"""IrInstructionCount"""'}), "('llvm-v0', observation_space='Autophase', reward_space=\n 'IrInstructionCount')\n", (4642, 4724), False, 'import gym\n'), ((4923, 4929), 'tests.test_main.main', 'main',... |
from django.db import models
# Create your models here.
class Quiz(models.Model):
title = models.CharField(max_length=250)
def __str__(self):
return self.title
class Question(models.Model):
CATEGORIES_CHOICES = (
('Inteligencja logiczno-matematyczna', 'Inteligencja logiczno-matematyczna')... | [
"django.db.models.CharField",
"django.db.models.ForeignKey"
] | [((95, 127), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(250)'}), '(max_length=250)\n', (111, 127), False, 'from django.db import models\n'), ((859, 908), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Quiz'], {'on_delete': 'models.CASCADE'}), '(Quiz, on_delete=models.CASCADE)\n', (8... |
import os
import luigi
from bioluigi.scheduled_external_program import ScheduledExternalProgramTask, Scheduler, SlurmScheduler
from distutils.spawn import find_executable
import pytest
class MyTask(ScheduledExternalProgramTask):
def program_args(self):
return ['true']
def test_default_scheduler():
ass... | [
"pytest.skip",
"distutils.spawn.find_executable"
] | [((582, 605), 'distutils.spawn.find_executable', 'find_executable', (['"""srun"""'], {}), "('srun')\n", (597, 605), False, 'from distutils.spawn import find_executable\n'), ((623, 672), 'pytest.skip', 'pytest.skip', (['"""srun is needed to run Slurm tests."""'], {}), "('srun is needed to run Slurm tests.')\n", (634, 67... |