code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
"""A DOM implementation that offers traversal and ranges on top of
minidom, using the 4DOM traversal implementation."""
import minidom, string
class DOMImplementation(minidom.DOMImplementation):
def hasFeature(self, feature, version):
if version not in ("1.0", "2.0"):
return 0
feature ... | [
"minidom.DOMImplementation.hasFeature",
"xml.dom.NodeIterator.NodeIterator",
"string.lower",
"Range.Range",
"TreeWalker.TreeWalker"
] | [((322, 343), 'string.lower', 'string.lower', (['feature'], {}), '(feature)\n', (334, 343), False, 'import minidom, string\n'), ((425, 485), 'minidom.DOMImplementation.hasFeature', 'minidom.DOMImplementation.hasFeature', (['self', 'feature', 'version'], {}), '(self, feature, version)\n', (461, 485), False, 'import mini... |
import redis
from tools.common import test_http_proxy
import threading
def http_task():
# 连接redis数据库
POOL = redis.ConnectionPool(host='127.0.0.1', port=6379)
CONN_REDIS = redis.Redis(connection_pool=POOL)
# 取出一个ip进行测试
# proxy = CONN_REDIS.("freeProxy:AfterVerifyOKhttp")
ip = CONN_REDIS.srandme... | [
"redis.Redis",
"threading.Thread",
"tools.common.test_http_proxy",
"redis.ConnectionPool"
] | [((118, 167), 'redis.ConnectionPool', 'redis.ConnectionPool', ([], {'host': '"""127.0.0.1"""', 'port': '(6379)'}), "(host='127.0.0.1', port=6379)\n", (138, 167), False, 'import redis\n'), ((185, 218), 'redis.Redis', 'redis.Redis', ([], {'connection_pool': 'POOL'}), '(connection_pool=POOL)\n', (196, 218), False, 'import... |
import pytesseract
from pytesseract import Output
import cv2
import os
from shapely.geometry import Polygon
pytesseract.pytesseract.tesseract_cmd = "Tesseract path e.g c:\Tesseract-OCR\tesseract "
import sys
from os import chdir, listdir
from os.path import join
## Hyper Params
L = 'abcdefghijklmno... | [
"cv2.line",
"shapely.geometry.Polygon",
"os.path.basename",
"cv2.imwrite",
"pytesseract.image_to_data",
"cv2.imread",
"cv2.rectangle",
"cv2.imshow",
"os.path.join",
"os.listdir",
"cv2.namedWindow"
] | [((478, 498), 'cv2.imread', 'cv2.imread', (['img_path'], {}), '(img_path)\n', (488, 498), False, 'import cv2\n'), ((520, 575), 'pytesseract.image_to_data', 'pytesseract.image_to_data', (['img'], {'output_type': 'Output.DICT'}), '(img, output_type=Output.DICT)\n', (545, 575), False, 'import pytesseract\n'), ((722, 742),... |
from django.db import models
from django.db.models import Q
from django.utils.translation import gettext_lazy as _
from django.utils import timezone
from django.urls import reverse
from datetime import timedelta
from danceschool.core.models import (
Instructor, Location, Room, DanceRole, Event, PricingTier,
E... | [
"django.db.models.OneToOneField",
"danceschool.core.mixins.EmailRecipientMixin",
"django.db.models.ManyToManyField",
"django.utils.translation.gettext_lazy",
"django.db.models.CharField",
"django.utils.timezone.now",
"django.db.models.Q",
"danceschool.core.utils.timezone.ensure_localtime",
"django.u... | [((601, 660), 'django.db.models.OneToOneField', 'models.OneToOneField', (['StaffMember'], {'on_delete': 'models.CASCADE'}), '(StaffMember, on_delete=models.CASCADE)\n', (621, 660), False, 'from django.db import models\n'), ((841, 886), 'django.db.models.ManyToManyField', 'models.ManyToManyField', (['DanceRole'], {'blan... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Description: Templatetags test units.
"""
__author__ = "<NAME> (<EMAIL>)"
from decimal import Decimal
from django.test import TestCase
from currency.models import Currency
from currency.templatetags.to_currency import to_currency
class ToCurrencyTestCase(TestCase... | [
"currency.models.Currency.objects.get",
"decimal.Decimal"
] | [((690, 722), 'currency.models.Currency.objects.get', 'Currency.objects.get', ([], {'code': '"""ARS"""'}), "(code='ARS')\n", (710, 722), False, 'from currency.models import Currency\n'), ((850, 882), 'currency.models.Currency.objects.get', 'Currency.objects.get', ([], {'code': '"""USD"""'}), "(code='USD')\n", (870, 882... |
import math
import click
import os.path
import shutil
import atoms_simulator
import numpy
import matplotlib.pyplot as plt
def get_project_path():
return os.path.dirname(atoms_simulator.__file__)
def get_path(path):
i = 1
while True:
if not os.path.lexists(f"{path}{i}"):
return f"{pat... | [
"matplotlib.pyplot.title",
"atoms_simulator.Settings",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.clf",
"atoms_simulator.simulate",
"click.option",
"click.echo",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"click.group",
"matplotlib.pyplot.grid",
"shutil.copy",
"matplotlib.pyplot.xlabel"
] | [((345, 358), 'click.group', 'click.group', ([], {}), '()\n', (356, 358), False, 'import click\n'), ((983, 1080), 'click.option', 'click.option', (['"""-g"""', '"""--graphics"""', '"""graphics"""'], {'help': '"""Turn on pygame simulation"""', 'is_flag': '(True)'}), "('-g', '--graphics', 'graphics', help=\n 'Turn on ... |
import numpy as np
from scipy.optimize import linprog
c = [10, 3.8, 1.5]
A_ub = [
[1, 1, 1],
[-1, -1, -1],
[-1, -1. / 3., -1. / 6.]]
b_ub = [18, -12, -9]
res = linprog(c, A_ub=A_ub, b_ub=b_ub)
print(res)
| [
"scipy.optimize.linprog"
] | [((175, 207), 'scipy.optimize.linprog', 'linprog', (['c'], {'A_ub': 'A_ub', 'b_ub': 'b_ub'}), '(c, A_ub=A_ub, b_ub=b_ub)\n', (182, 207), False, 'from scipy.optimize import linprog\n')] |
#!/usr/bin/env python
# Processes OpenEthereum warp snapshot and collects 4-byte code prefixes of all accounts.
#
# openethereum --chain=kovan snapshot --snapshot-threads=8 snapshot.warp
# warp2code-prefixes.py snapshot.warp
import sys
import rlp
import snappy
import collections
prefix_map = collections.defaul... | [
"collections.defaultdict",
"snappy.uncompress",
"rlp.decode"
] | [((302, 330), 'collections.defaultdict', 'collections.defaultdict', (['int'], {}), '(int)\n', (325, 330), False, 'import collections\n'), ((743, 769), 'rlp.decode', 'rlp.decode', (['manifest_bytes'], {}), '(manifest_bytes)\n', (753, 769), False, 'import rlp\n'), ((1362, 1397), 'snappy.uncompress', 'snappy.uncompress', ... |
"""Web Worker script."""
# In web workers, "window" is replaced by "self".
from browser import bind, self
import contextlib
import traceback
class OutputWriter:
def __init__(self, id, window):
self.id = id
self.window = window
self.buf = []
def write(self, text):
"""Write out... | [
"browser.bind",
"contextlib.redirect_stderr",
"browser.self.buf.append",
"contextlib.redirect_stdout",
"traceback.format_exc",
"browser.self.window.send",
"browser.self.send"
] | [((532, 553), 'browser.bind', 'bind', (['self', '"""message"""'], {}), "(self, 'message')\n", (536, 553), False, 'from browser import bind, self\n'), ((350, 371), 'browser.self.buf.append', 'self.buf.append', (['text'], {}), '(text)\n', (365, 371), False, 'from browser import bind, self\n'), ((380, 423), 'browser.self.... |
import numpy as np
import pandas as pd
from typing import Union, Callable
from pandas.core.frame import DataFrame
from NitroFE.time_based_features.indicator_features._AbsolutePriceOscillator import (
AbsolutePriceOscillator,
)
from NitroFE.time_based_features.moving_average_features.moving_average_features... | [
"NitroFE.time_based_features.indicator_features._AbsolutePriceOscillator.AbsolutePriceOscillator",
"NitroFE.time_based_features.moving_average_features.moving_average_features.ExponentialMovingFeature"
] | [((4388, 4750), 'NitroFE.time_based_features.indicator_features._AbsolutePriceOscillator.AbsolutePriceOscillator', 'AbsolutePriceOscillator', ([], {'fast_period': 'self.span_fast', 'slow_period': 'self.span_slow', 'fast_operation': 'self.fast_operation', 'slow_operation': 'self.slow_operation', 'min_periods': 'self.min... |
from pathlib import Path
from typing import Union, List, Dict, Optional
import pandas as pd
from torch.utils.data import DataLoader
import pytorch_lightning as pl
from torchvision.transforms import transforms
from src.utils.utils import get_logger
class ArcheryBowlingDataModule(pl.LightningDataModule):
def __i... | [
"src.utils.utils.get_logger",
"torch.utils.data.DataLoader",
"pandas.read_csv",
"src.datamodules.datasets.archery_bowling_dataset.ArcheryBowlingDataset.create_from_dataframe",
"torchvision.transforms.transforms.ToTensor",
"pathlib.Path",
"pandas.concat"
] | [((1110, 1143), 'src.utils.utils.get_logger', 'get_logger', ([], {'name': '"""A-B-DataModule"""'}), "(name='A-B-DataModule')\n", (1120, 1143), False, 'from src.utils.utils import get_logger\n'), ((1629, 1644), 'pathlib.Path', 'Path', (['data_root'], {}), '(data_root)\n', (1633, 1644), False, 'from pathlib import Path\n... |
import sys
import click
from bulk_import_rename.commands.detect_modifications import track_modifications
from bulk_import_rename.commands.rename_import import run_rename
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.group(context_settings=CONTEXT_SETTINGS)
@click.version_option(vers... | [
"click.version_option",
"click.option",
"bulk_import_rename.commands.detect_modifications.track_modifications",
"bulk_import_rename.commands.rename_import.run_rename",
"click.Path",
"click.group"
] | [((246, 292), 'click.group', 'click.group', ([], {'context_settings': 'CONTEXT_SETTINGS'}), '(context_settings=CONTEXT_SETTINGS)\n', (257, 292), False, 'import click\n'), ((295, 332), 'click.version_option', 'click.version_option', ([], {'version': '"""0.0.1"""'}), "(version='0.0.1')\n", (315, 332), False, 'import clic... |
import thread
import threading
import abc
from time import sleep
class AttackMethod:
"""
The AttackMethod class represents a DOS attack. The AttackMethod class is an abstract class and needs to be
extended by other classes. An AttackMethod runs in its own thread. The thread loop starts when the
... | [
"threading.Lock",
"thread.start_new_thread",
"time.sleep"
] | [((777, 793), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (791, 793), False, 'import threading\n'), ((1171, 1217), 'thread.start_new_thread', 'thread.start_new_thread', (['self._thread_loop', '()'], {}), '(self._thread_loop, ())\n', (1194, 1217), False, 'import thread\n'), ((1899, 1922), 'time.sleep', 'sleep'... |
# This file is needed to initialize the models and migrations
import os
import sys
from nopea.dbobject import DbObject
from nopea import fields
from nopea.migrations import Migration
if 'sqlite' in sys.argv:
from nopea.adaptors.sqlite import SQLiteAdaptor
DbObject.adaptor = SQLiteAdaptor('sqless.db')
elif ... | [
"nopea.adaptors.sqlite.SQLiteAdaptor",
"nopea.adaptors.postgres.PostgreSQLAdaptor",
"nopea.fields.TextField",
"os.getcwd",
"nopea.fields.IntegerField",
"nopea.fields.CharField",
"nopea.adaptors.mysql.MySQLAdaptor",
"nopea.migrations.Migration",
"nopea.fields.BooleanField"
] | [((1397, 1408), 'nopea.migrations.Migration', 'Migration', ([], {}), '()\n', (1406, 1408), False, 'from nopea.migrations import Migration\n'), ((287, 313), 'nopea.adaptors.sqlite.SQLiteAdaptor', 'SQLiteAdaptor', (['"""sqless.db"""'], {}), "('sqless.db')\n", (300, 313), False, 'from nopea.adaptors.sqlite import SQLiteAd... |
import os
import math
import pandas as pd
import datetime
variables = [
'date_stamp',
'age_group',
'cnt_confirmed',
'pct_confirmed'
]
def cleanData(data, fileName):
# source data frame from csv file
source = pd.DataFrame(data)
source.columns = ['v1','v2','v3']
print(source)
# the target d... | [
"pandas.DataFrame",
"os.remove",
"pandas.read_csv",
"datetime.date.today",
"pandas.Int32Dtype",
"datetime.datetime.strptime",
"datetime.timedelta",
"pandas.to_datetime",
"datetime.time",
"os.listdir"
] | [((225, 243), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (237, 243), True, 'import pandas as pd\n'), ((339, 370), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'variables'}), '(columns=variables)\n', (351, 370), True, 'import pandas as pd\n'), ((954, 975), 'datetime.date.today', 'datetime.da... |
import pytest
import requests
from project import create_app, db
from flask import current_app
from project.models import Stock, User
from datetime import datetime
########################
#### Helper Classes ####
########################
class MockSuccessResponse(object):
def __init__(self, url):
self.s... | [
"project.db.session.add",
"project.db.session.commit",
"project.models.User.query.filter_by",
"project.create_app",
"pytest.fixture",
"datetime.datetime",
"project.models.User"
] | [((2827, 2857), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (2841, 2857), False, 'import pytest\n'), ((3430, 3462), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (3444, 3462), False, 'import pytest\n'), ((3567, 3597), 'pytes... |
import email
import pandas as pd
def extract(data, structured_fields=[], extract_payload=True):
r"""This function extracts data for the given header list from the Enron email dataset.
It provides flexibilty to choose which fields needs to be extracted.
The header list provided by the user... | [
"pandas.DataFrame",
"email.message_from_string",
"pandas.concat"
] | [((2387, 2416), 'pandas.DataFrame', 'pd.DataFrame', (['structured_data'], {}), '(structured_data)\n', (2399, 2416), True, 'import pandas as pd\n'), ((2981, 3025), 'pandas.concat', 'pd.concat', (['[emails, structured_data]'], {'axis': '(1)'}), '([emails, structured_data], axis=1)\n', (2990, 3025), True, 'import pandas a... |
"""
domonic.events
====================================
dom events
"""
# from typing import *
import time
# TODO - bring EventTarget here and get rid of this one?
class EventDispatcher(object):
""" EventDispatcher is a class you can extend to give your obj event dispatching abilities """
def __i... | [
"time.time"
] | [((3599, 3610), 'time.time', 'time.time', ([], {}), '()\n', (3608, 3610), False, 'import time\n')] |
import pandas as pd
import numpy as np
import torch
def min_max_x(x):
for index, col in enumerate(x.T):
min_col = np.min(col)
max_col = np.max(col)
if min_col != max_col:
x.T[index] = (x.T[index] - min_col)/(max_col - min_col)
else:
x.T[index] = x.T[index] - min_col
return x
def load_dataset(path='./... | [
"numpy.random.seed",
"pandas.read_csv",
"numpy.min",
"numpy.max",
"numpy.random.shuffle",
"torch.from_numpy"
] | [((384, 404), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (398, 404), True, 'import numpy as np\n'), ((411, 428), 'pandas.read_csv', 'pd.read_csv', (['path'], {}), '(path)\n', (422, 428), True, 'import pandas as pd\n'), ((118, 129), 'numpy.min', 'np.min', (['col'], {}), '(col)\n', (124, 129), Tru... |
"""
This code returns a DFA that is equivalent to the Tree constructed by compressing all the traces into one tree.
"""
import read_traces, DFA_utils_tree_only, time, tree_utils
def solve_tree_only(g_pos, G, Sigma, T, timeout, info, be_quiet=False):
assert g_pos in G, f"Error, g_pos not in G"
# creating the auxil... | [
"DFA_utils_tree_only.add_probabilities",
"tree_utils.get_reachable_nodes",
"tree_utils.create_tree",
"DFA_utils_tree_only.clean_dfa"
] | [((348, 403), 'tree_utils.create_tree', 'tree_utils.create_tree', (['g_pos', 'G', 'Sigma', 'T'], {'prune': '(False)'}), '(g_pos, G, Sigma, T, prune=False)\n', (370, 403), False, 'import read_traces, DFA_utils_tree_only, time, tree_utils\n'), ((413, 449), 'tree_utils.get_reachable_nodes', 'tree_utils.get_reachable_nodes... |
# Source:
# https://www.tensorflow.org/api_guides/python/reading_data
import tensorflow as tf
# creates a FIFO queue for holding the filenames until the reader needs them.
# The following line is equivalent to :
# filename_queue = tf.train.string_input_producer(["file0.csv", "file1.csv"])
filename_queue = tf.tr... | [
"tensorflow.train.Coordinator",
"tensorflow.Session",
"tensorflow.stack",
"tensorflow.train.start_queue_runners",
"tensorflow.TextLineReader",
"tensorflow.decode_csv"
] | [((394, 413), 'tensorflow.TextLineReader', 'tf.TextLineReader', ([], {}), '()\n', (411, 413), True, 'import tensorflow as tf\n'), ((736, 789), 'tensorflow.decode_csv', 'tf.decode_csv', (['value'], {'record_defaults': 'record_defaults'}), '(value, record_defaults=record_defaults)\n', (749, 789), True, 'import tensorflow... |
"""
Author: <NAME>
Github: github.com/yashbmewada
Program for demonstrating simple line fitting using Tensorflow and Gradient Descent Algorithm
This program trains the model to fit two values, slope(m) and x-intercept(b) in the equation
of line y=mx+b. Here we would provide very small dataset of randomly generated po... | [
"tensorflow.global_variables_initializer",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.Variable",
"tensorflow.Session"
] | [((1227, 1249), 'tensorflow.Variable', 'tf.Variable', (['m_initial'], {}), '(m_initial)\n', (1238, 1249), True, 'import tensorflow as tf\n'), ((1254, 1276), 'tensorflow.Variable', 'tf.Variable', (['b_initial'], {}), '(b_initial)\n', (1265, 1276), True, 'import tensorflow as tf\n'), ((2965, 2998), 'tensorflow.global_var... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 23 17:20:22 2019
convert txt to excel
@author: zyb_as
"""
import os
import argparse, textwrap
import xlwt
# set options
parser = argparse.ArgumentParser(description = 'convert txt to excel',
usage = textwrap.dedent('''\
command example:
python %... | [
"textwrap.dedent",
"xlwt.Workbook",
"os.path.exists"
] | [((1536, 1567), 'xlwt.Workbook', 'xlwt.Workbook', ([], {'encoding': '"""utf-8"""'}), "(encoding='utf-8')\n", (1549, 1567), False, 'import xlwt\n'), ((258, 380), 'textwrap.dedent', 'textwrap.dedent', (['""" command example:\n python %(prog)s --file_name=\'test.txt\' --splitter=\'\\\\t\' """'], {}), '(\n ... |
from pybuilder.core import init, use_plugin, Author
use_plugin('python.core')
use_plugin('python.flake8')
use_plugin('python.unittest')
use_plugin('python.coverage')
use_plugin('python.distutils')
use_plugin("python.install_dependencies")
authors = [Author('Dachaz', '<EMAIL>')]
license = 'MIT'
name = 'scenery'
summar... | [
"pybuilder.core.Author",
"pybuilder.core.use_plugin"
] | [((53, 78), 'pybuilder.core.use_plugin', 'use_plugin', (['"""python.core"""'], {}), "('python.core')\n", (63, 78), False, 'from pybuilder.core import init, use_plugin, Author\n'), ((79, 106), 'pybuilder.core.use_plugin', 'use_plugin', (['"""python.flake8"""'], {}), "('python.flake8')\n", (89, 106), False, 'from pybuild... |
from packetraven.packets.structures import DoublyLinkedList
def test_index():
list_1 = DoublyLinkedList([0, 5, 4, 'foo', 5, 6])
assert list_1[0] == 0
assert list_1[0] is list_1.head.value
assert list_1[3] == 'foo'
assert list_1[-2] == 5
assert list_1[-1] == 6
assert list_1[-1] is list_1.t... | [
"packetraven.packets.structures.DoublyLinkedList"
] | [((93, 133), 'packetraven.packets.structures.DoublyLinkedList', 'DoublyLinkedList', (["[0, 5, 4, 'foo', 5, 6]"], {}), "([0, 5, 4, 'foo', 5, 6])\n", (109, 133), False, 'from packetraven.packets.structures import DoublyLinkedList\n'), ((442, 460), 'packetraven.packets.structures.DoublyLinkedList', 'DoublyLinkedList', ([]... |
"""Test functions loading."""
import inspect
from griffe.loader import GriffeLoader
from tests import FIXTURES_DIR
loader = GriffeLoader()
def test_loading_functions_arguments(): # noqa: WPS218
"""Test functions arguments loading."""
module = loader.load_module(FIXTURES_DIR / "functions" / "arguments.py")... | [
"griffe.loader.GriffeLoader"
] | [((127, 141), 'griffe.loader.GriffeLoader', 'GriffeLoader', ([], {}), '()\n', (139, 141), False, 'from griffe.loader import GriffeLoader\n')] |
from flask_wtf import FlaskForm, RecaptchaField
from wtforms import StringField , PasswordField, SubmitField
from wtforms.validators import DataRequired, Email, Length
class SignupForm(FlaskForm):
firstname = StringField("First name", validators=[DataRequired("Enter your name")])
lastname = StringField("Last ... | [
"wtforms.validators.Length",
"wtforms.validators.DataRequired",
"wtforms.validators.Email"
] | [((253, 284), 'wtforms.validators.DataRequired', 'DataRequired', (['"""Enter your name"""'], {}), "('Enter your name')\n", (265, 284), False, 'from wtforms.validators import DataRequired, Email, Length\n'), ((339, 375), 'wtforms.validators.DataRequired', 'DataRequired', (['"""Enter your last name"""'], {}), "('Enter yo... |
import sys
import os
from os.path import *
def pl():
return dirname(dirname(dirname(dirname(os.path.abspath(__file__)))))
class SparkEnv:
def __init__(self, name):
os.environ['HADOOP_HOME'] = dirname(dirname(dirname(dirname(os.path.abspath(__file__))))) + r'/hadoopdir'
os.environ['SPARK_HOME... | [
"sys.path.append",
"os.path.abspath",
"pyspark.sql.SparkSession.builder.appName",
"pyspark.SparkContext"
] | [((383, 459), 'sys.path.append', 'sys.path.append', (['"""D:\\\\assistlibs\\\\hadoop\\\\spark-2.2.3-bin-hadoop2.6\\\\python"""'], {}), "('D:\\\\assistlibs\\\\hadoop\\\\spark-2.2.3-bin-hadoop2.6\\\\python')\n", (398, 459), False, 'import sys\n'), ((516, 543), 'pyspark.SparkContext', 'SparkContext', (['"""local"""', 'nam... |
from scipy.optimize import root
from scipy.integrate import solve_ivp
import numpy as np
def phase_cond(u, dudt):
res= np.array(dudt(0,u))
return res
def periodicity_cond(u, dudt, T):
# integrate the ode for time t from starting position U
res = np.array(u - solve_ivp(dudt, (0, T), u).y[:,-1])
ret... | [
"scipy.optimize.root",
"scipy.integrate.solve_ivp"
] | [((1291, 1336), 'scipy.optimize.root', 'root', (['g', 'state_vec'], {'args': '(dudt,)', 'method': '"""lm"""'}), "(g, state_vec, args=(dudt,), method='lm')\n", (1295, 1336), False, 'from scipy.optimize import root\n'), ((277, 303), 'scipy.integrate.solve_ivp', 'solve_ivp', (['dudt', '(0, T)', 'u'], {}), '(dudt, (0, T), ... |
import logging
import os
from datetime import datetime
import pandas as pd
from analysis import calibrationreport, resource_usage, cpuefficiency, sampling
from analysis import jobreportanalysis
from analysis import jobreportcleaning
from analysis import nodeanalysis
from analysis.demandextraction import FilteredJobCl... | [
"importers.gridkadata.GridKaNodeDataImporter",
"pandas.read_csv",
"analysis.cpuefficiency.calculate_efficiencies",
"analysis.jobreportanalysis.add_missing_node_info",
"importers.wmaimport.SummarizedWMAImporter",
"analysis.calibrationreport.multiple_jobslot_usage",
"os.path.isfile",
"analysis.nodeanaly... | [((1261, 1347), 'utils.report.ReportBuilder', 'ReportBuilder', ([], {'base_path': 'config.outputDirectory', 'filename': '"""calibration-report.md"""'}), "(base_path=config.outputDirectory, filename=\n 'calibration-report.md')\n", (1274, 1347), False, 'from utils.report import ReportBuilder\n'), ((1629, 1661), 'panda... |
from proboscis.asserts import assert_equal
from proboscis import test
from proboscis import before_class
from trove.common.utils import poll_until
from trove.tests.util import create_client
class InstanceGenerator(object):
def __init__(self, client, status=None, name=None, flavor=None,
account... | [
"proboscis.test",
"trove.tests.util.create_client",
"proboscis.asserts.assert_equal"
] | [((1778, 1812), 'proboscis.test', 'test', ([], {'groups': "['smoke', 'positive']"}), "(groups=['smoke', 'positive'])\n", (1782, 1812), False, 'from proboscis import test\n'), ((1003, 1041), 'proboscis.asserts.assert_equal', 'assert_equal', (['instance.status', '"""BUILD"""'], {}), "(instance.status, 'BUILD')\n", (1015,... |
#<NAME>
#CS4375: OS
#3 methods
from os import read #from os library import read method
next = 0
limit = 0
#This method calls read to fill a buffer, and gets one char at at time
def my_getChar(): #define = creating method : use method, loops, tryCatch
global next, limit #initializing 2 variables
if next == l... | [
"os.read"
] | [((359, 372), 'os.read', 'read', (['(0)', '(1000)'], {}), '(0, 1000)\n', (363, 372), False, 'from os import read\n')] |
# Generated by Django 3.1.4 on 2020-12-01 15:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0006_suggestions_from_django_doctor'),
]
operations = [
migrations.AlterField(
model_name='datapackage',
nam... | [
"django.db.models.CharField"
] | [((348, 404), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'default': '""""""', 'max_length': '(500)'}), "(blank=True, default='', max_length=500)\n", (364, 404), False, 'from django.db import migrations, models\n')] |
import random
import logging
import networkx as nx
from tenet.message import (
Message,
DictTransport, MessageSerializer, MessageTypes
)
from tenet.peer import Peer, Friend
from tenet.utils import weighted_choice
log = logging.getLogger(__name__)
class SimulatedPeer(object):
def __init... | [
"matplotlib.pyplot.savefig",
"tenet.peer.Friend",
"networkx.draw_networkx_edges",
"tenet.message.Message",
"random.randint",
"tenet.utils.weighted_choice",
"random.choice",
"networkx.random_geometric_graph",
"matplotlib.pyplot.figure",
"networkx.Graph",
"networkx.draw_networkx_nodes",
"network... | [((246, 273), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (263, 273), False, 'import logging\n'), ((3767, 3777), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (3775, 3777), True, 'import networkx as nx\n'), ((4044, 4088), 'networkx.random_geometric_graph', 'nx.random_geometric_graph'... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This module defines :class:`LicenseMaker` class."""
from __future__ import absolute_import, print_function
import os
import datetime
from . import settings
from .base import BaseMaker
#: Supported licenses, corresponding template file names, and descriptions
_LICENS... | [
"os.path.join",
"datetime.date.today"
] | [((3874, 3914), 'os.path.join', 'os.path.join', (['self.projectDir', '"""LICENSE"""'], {}), "(self.projectDir, 'LICENSE')\n", (3886, 3914), False, 'import os\n'), ((2168, 2189), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (2187, 2189), False, 'import datetime\n'), ((2227, 2248), 'datetime.date.today... |
import unittest
from nes.processors.cpu import Cpu
from nes.bus import Bus
from nes.bus.devices.memory import Ram
class CpuIncrementInstructionsTestCase(unittest.TestCase):
def setUp(self):
bus = Bus()
bus.attach_device('RAM', Ram(256), 0, 256)
self.cpu = Cpu(bus)
def test_inc(self):
... | [
"unittest.main",
"nes.processors.cpu.Cpu",
"nes.bus.devices.memory.Ram",
"nes.bus.Bus"
] | [((1136, 1151), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1149, 1151), False, 'import unittest\n'), ((210, 215), 'nes.bus.Bus', 'Bus', ([], {}), '()\n', (213, 215), False, 'from nes.bus import Bus\n'), ((286, 294), 'nes.processors.cpu.Cpu', 'Cpu', (['bus'], {}), '(bus)\n', (289, 294), False, 'from nes.proces... |
import hashlib
import json
import numpy as np
from jina import Executor, DocumentArray, requests
class TagsHasher(Executor):
"""Convert an arbitrary set of tags into a fixed-dimensional matrix using the hashing trick.
Unlike FeatureHashser, you should only use Jaccard/Hamming distance when searching docume... | [
"numpy.zeros",
"json.dumps",
"numpy.sign"
] | [((2435, 2455), 'numpy.zeros', 'np.zeros', (['self.n_dim'], {}), '(self.n_dim)\n', (2443, 2455), True, 'import numpy as np\n'), ((2582, 2592), 'numpy.sign', 'np.sign', (['h'], {}), '(h)\n', (2589, 2592), True, 'import numpy as np\n'), ((2707, 2719), 'numpy.sign', 'np.sign', (['val'], {}), '(val)\n', (2714, 2719), True,... |
from pdfbuilder import registry
from pdfbuilder.basetemplates import BaseDocTemplateWithHeaderAndFooter as BaseDocTemplate
from pdfbuilder.basetemplates import OneColumnBaseDocTemplateWithHeaderAndFooter as OneColumnDocTemplate
from pdfbuilder.basetemplates import PDFTemplate
from reportlab.lib import colors
from repo... | [
"reportlab.lib.styles.getSampleStyleSheet",
"reportlab.platypus.TableStyle",
"reportlab.platypus.Paragraph",
"reportlab.platypus.Table",
"pdfbuilder.registry.register_template"
] | [((1947, 2078), 'pdfbuilder.registry.register_template', 'registry.register_template', (['ThreeColumnDown', '"""threecolumn_down"""', '"""Three column layout, flowing down the page (newspaper style)"""'], {}), "(ThreeColumnDown, 'threecolumn_down',\n 'Three column layout, flowing down the page (newspaper style)')\n"... |
# Chapter05-04
# 파이썬 심화
# 데코레이터
# 장점
# 1. 중복 제거, 코드 간결, 공통 함수 작성
# 2. 로깅, 프레임워크, 유효성 체크..... -> 공통 기능
# 3. 조합해서 사용 용이
# 단점
# 1. 가독성 감소?
# 2. 특정 기능에 한정된 함수는 -> 단일 함수로 작성하는 것이 유리
# 3. 디버깅 불편
# 데코레이터 실습
import time
def perf_clock(func):
def perf_clocked(*args):
# 함수 시작 시간
st = time.perf_counter()... | [
"time.perf_counter",
"time.sleep"
] | [((706, 725), 'time.sleep', 'time.sleep', (['seconds'], {}), '(seconds)\n', (716, 725), False, 'import time\n'), ((301, 320), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (318, 320), False, 'import time\n'), ((386, 405), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (403, 405), False, 'impo... |
"""A class with static methods which can be used to access the data about
experiments.
This includes reading logs to parse success cases, reading images, costs
and speed.
"""
import numpy as np
from glob import glob
import torch
import pandas
import re
import json
from functools import lru_cache
import imageio
EPISO... | [
"json.load",
"numpy.sum",
"torch.stack",
"numpy.argmax",
"numpy.std",
"imageio.imread",
"torch.load",
"numpy.zeros",
"numpy.mean",
"numpy.array",
"glob.glob",
"numpy.squeeze",
"functools.lru_cache",
"re.search",
"re.compile"
] | [((494, 514), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': '(1)'}), '(maxsize=1)\n', (503, 514), False, 'from functools import lru_cache\n'), ((4233, 4255), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': '(100)'}), '(maxsize=100)\n', (4242, 4255), False, 'from functools import lru_cache\n'), ((13831, 1385... |
# Copyright 2018-2020 Xanadu Quantum Technologies Inc.
# 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... | [
"benchmark_utils.create_qnode",
"numpy.random.randn",
"pennylane.RX",
"numpy.cos",
"pennylane.PauliZ"
] | [((861, 889), 'pennylane.RX', 'qml.RX', (['p[aux][2]'], {'wires': '[0]'}), '(p[aux][2], wires=[0])\n', (867, 889), True, 'import pennylane as qml\n'), ((912, 925), 'pennylane.PauliZ', 'qml.PauliZ', (['(0)'], {}), '(0)\n', (922, 925), True, 'import pennylane as qml\n'), ((2281, 2348), 'benchmark_utils.create_qnode', 'bu... |
from rest_framework.decorators import (
api_view,
permission_classes,
authentication_classes,
renderer_classes,
)
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.authentication import BaseAuthentication
from rest_framework.renderers import... | [
"rest_framework.decorators.renderer_classes",
"rest_framework.decorators.authentication_classes",
"rest_framework.response.Response",
"django.conf.urls.url",
"rest_framework.decorators.permission_classes",
"rest_framework.decorators.api_view"
] | [((1015, 1032), 'rest_framework.decorators.api_view', 'api_view', (["['GET']"], {}), "(['GET'])\n", (1023, 1032), False, 'from rest_framework.decorators import api_view, permission_classes, authentication_classes, renderer_classes\n'), ((1034, 1078), 'rest_framework.decorators.authentication_classes', 'authentication_c... |
#
# Copyright (C) 2020 Arm Mbed. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
"""Text snippet extractor."""
from typing import List, Optional
from snippet import exceptions
from snippet.config import Config
class Example:
"""An example."""
def __init__(self, path: str, line_num: int, example... | [
"snippet.exceptions.CloakMismatch",
"snippet.exceptions.StartEndMismatch",
"snippet.exceptions.ValidationFailure"
] | [((823, 899), 'snippet.exceptions.CloakMismatch', 'exceptions.CloakMismatch', (['f"""Already cloaked at {self.debug_id} ({line_num})"""'], {}), "(f'Already cloaked at {self.debug_id} ({line_num})')\n", (847, 899), False, 'from snippet import exceptions\n'), ((1056, 1134), 'snippet.exceptions.CloakMismatch', 'exceptions... |
import exhaust
def test_double_iteration():
def gen(state: exhaust.State):
return state.maybe()
space = exhaust.space(gen)
assert len(set(space)) == 2
assert len(set(space)) == 2
| [
"exhaust.space"
] | [((122, 140), 'exhaust.space', 'exhaust.space', (['gen'], {}), '(gen)\n', (135, 140), False, 'import exhaust\n')] |
# -*- coding: utf-8 -*-
# vim: sw=4 ts=4 fenc=utf-8
# =============================================================================
# $Id: ispman_helpers.py 84 2006-11-27 04:12:13Z s0undt3ch $
# =============================================================================
# $URL: http://ispmanccp.ufsoft.org... | [
"pylons.g.ispman.getVhostCount",
"pylons.g.ispman.update_user",
"pylons.g.ispman.getDomainInfo",
"string.join",
"pylons.g.ispman.getUserAttributeValues",
"pylons.g.ispman.deleteUser",
"pylons.g.ispman.userExists",
"pylons.g.ispman.getEntriesAsHashRef",
"pylons.decorators.cache.beaker_cache",
"pylo... | [((1095, 1120), 'pylons.cache.get_cache', 'cache.get_cache', (['"""ispman"""'], {}), "('ispman')\n", (1110, 1120), False, 'from pylons import request, g, cache\n'), ((5957, 5998), 'pylons.decorators.cache.beaker_cache', 'beaker_cache', ([], {'expire': '(300)', 'query_args': '(True)'}), '(expire=300, query_args=True)\n'... |
import json
from os.path import join
import requests
from django.conf import settings
def remove_unneeded_properties(feature):
keys_to_remove = [
key for key in feature['properties'].keys()
if key.startswith('osm:') or key.startswith('result:')
]
for key in keys_to_remove:
fea... | [
"os.path.join",
"json.dumps"
] | [((920, 939), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (930, 939), False, 'import json\n'), ((1414, 1457), 'os.path.join', 'join', (['settings.MAP_ROULETTE_API_URL', '"""task"""'], {}), "(settings.MAP_ROULETTE_API_URL, 'task')\n", (1418, 1457), False, 'from os.path import join\n')] |
#!/bin/env python3
import argparse
import zmq
import threading
import json
import time
from libs.mylib import is_prime
def parse_args():
parser = argparse.ArgumentParser(description='Find all prime number in a range (from 2).')
parser.add_argument('max', type=int, default=1000,
help='... | [
"threading.Thread",
"argparse.ArgumentParser",
"json.loads",
"json.dumps",
"time.sleep",
"zmq.Context.instance",
"libs.mylib.is_prime"
] | [((153, 239), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Find all prime number in a range (from 2)."""'}), "(description=\n 'Find all prime number in a range (from 2).')\n", (176, 239), False, 'import argparse\n'), ((1663, 1685), 'zmq.Context.instance', 'zmq.Context.instance', ([]... |
# Copyright 2019 Katteli Inc.
# TestFlows.com Open-Source Software Testing Framework (http://testflows.com)
#
# 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/lice... | [
"functools.partial",
"testflows._core.cli.arg.type.logfile",
"testflows._core.cli.arg.type.file",
"testflows._core.utils.timefuncs.strftimedelta",
"time.time",
"testflows._core.transform.log.report.totals.Counts",
"testflows._core.utils.timefuncs.localfromtimestamp",
"testflows._core.objects.Requireme... | [((14721, 14755), 'testflows._core.transform.log.report.totals.Counts', 'Counts', (['"""requirements"""', '*([0] * 4)'], {}), "('requirements', *([0] * 4))\n", (14727, 14755), False, 'from testflows._core.transform.log.report.totals import Counts\n'), ((11143, 11154), 'time.time', 'time.time', ([], {}), '()\n', (11152,... |
import copy
import os
from http import HTTPStatus
from unittest.mock import MagicMock, patch
import pytest
import responses
from lighthouse import create_app
from lighthouse.constants.events import PE_BECKMAN_SOURCE_ALL_NEGATIVES, PE_BECKMAN_SOURCE_COMPLETED
from lighthouse.constants.fields import (
FIELD_CHERRYT... | [
"lighthouse.helpers.mysql.create_mysql_connection_engine",
"copy.deepcopy",
"lighthouse.helpers.dart.create_dart_connection",
"tests.fixtures.data.biosero.destination_plate_wells.build_cherrytrack_destination_plate_response",
"tests.fixtures.data.biosero.source_plate_wells.build_cherrytrack_source_plates_re... | [((1959, 1971), 'lighthouse.create_app', 'create_app', ([], {}), '()\n', (1969, 1971), False, 'from lighthouse import create_app\n'), ((3595, 3626), 'copy.deepcopy', 'copy.deepcopy', (['PRIORITY_SAMPLES'], {}), '(PRIORITY_SAMPLES)\n', (3608, 3626), False, 'import copy\n'), ((9441, 9479), 'lighthouse.helpers.mysql.get_t... |
from botocore.exceptions import ClientError
from osdu_commons.utils.throttle import throttle_exception, ThrottledBotoResource
class Counter:
def __init__(self):
self.counter = 0
def count(self):
self.counter += 1
def test_throttle_exception():
class BogusException(Exception):
p... | [
"botocore.exceptions.ClientError",
"osdu_commons.utils.throttle.throttle_exception"
] | [((366, 442), 'osdu_commons.utils.throttle.throttle_exception', 'throttle_exception', (['[BogusException]'], {'max_sleep': '(0.1)', 'max_retries': 'max_retries'}), '([BogusException], max_sleep=0.1, max_retries=max_retries)\n', (384, 442), False, 'from osdu_commons.utils.throttle import throttle_exception, ThrottledBot... |
# -*- coding: utf-8 -*-
"""
Navigation properties
---------------------
The entity can define properties that link to other entities. These are known
as navigation properties and are supported in this library.
.. code-block:: python
>>> order = Service.query(Order).first()
>>> order.Shipper
<Entity(Ship... | [
"urlparse.urljoin"
] | [((3062, 3092), 'urlparse.urljoin', 'urljoin', (['parent_url', 'self.name'], {}), '(parent_url, self.name)\n', (3069, 3092), False, 'from urlparse import urljoin\n')] |
from watchdog.events import PatternMatchingEventHandler
from utils import debug
from urllib.parse import unquote
from rtf.Rtf2Markdown import getMarkdown
import watchdog.events
import olefile
import sqlite3
import configparser
import codecs
import threading
class FileHandlerInterface(PatternMatchingEventHandler):
... | [
"rtf.Rtf2Markdown.getMarkdown",
"olefile.OleFileIO",
"sqlite3.connect",
"utils.debug",
"olefile.isOleFile",
"configparser.ConfigParser"
] | [((2407, 2465), 'olefile.OleFileIO', 'olefile.OleFileIO', (['self.sync_engine.sticky_notes_file_path'], {}), '(self.sync_engine.sticky_notes_file_path)\n', (2424, 2465), False, 'import olefile\n'), ((3399, 3492), 'sqlite3.connect', 'sqlite3.connect', (["('file:' + self.sync_engine.sticky_notes_file_path + '?mode=ro')"]... |
# -*- coding: utf-8 -*-
import logging
from scrapy.spiders import Spider
from scrapy.http import Request
logger = logging.getLogger(__name__)
# This spider is a base for those attempting to crawl and parse a specified
# list of URLs rather than using an RSS feed or a sitemap. It needs the
# SPECIFIED_URIS_FILE settin... | [
"scrapy.http.Request",
"logging.getLogger"
] | [((115, 142), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (132, 142), False, 'import logging\n'), ((1162, 1192), 'scrapy.http.Request', 'Request', (['url'], {'dont_filter': '(True)'}), '(url, dont_filter=True)\n', (1169, 1192), False, 'from scrapy.http import Request\n'), ((1442, 1472)... |
# -*- coding: utf-8 -*-
"""
Practical Algorthns
Problem set: Unit 5, 1.1
Problem statement:
4. Modify your binary search algorithm (from #3) to work with words rather
than integers. Test it on a small list of words, e.g.,
["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"].
The search... | [
"timeit.default_timer",
"nltk.corpus.words.words"
] | [((1964, 1977), 'nltk.corpus.words.words', 'words.words', ([], {}), '()\n', (1975, 1977), False, 'from nltk.corpus import words\n'), ((2314, 2321), 'timeit.default_timer', 'timer', ([], {}), '()\n', (2319, 2321), True, 'from timeit import default_timer as timer\n'), ((2380, 2387), 'timeit.default_timer', 'timer', ([], ... |
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
dot_product = np.dot(a, b)
print(dot_product) | [
"numpy.dot",
"numpy.array"
] | [((24, 43), 'numpy.array', 'np.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (32, 43), True, 'import numpy as np\n'), ((48, 67), 'numpy.array', 'np.array', (['[4, 5, 6]'], {}), '([4, 5, 6])\n', (56, 67), True, 'import numpy as np\n'), ((83, 95), 'numpy.dot', 'np.dot', (['a', 'b'], {}), '(a, b)\n', (89, 95), True, 'impo... |
#!/usr/bin/env python
# File: calculate.py
# Initial date: 4 Sept 2020
# Author: <NAME>
# School assignment: For Assignment #0 of class MCDB6440: Software Engineering for Scientists
# Description: Intro to using GitHub Classroom. Practice with creating and uploading files to github etc.
# This file imports funcitons... | [
"math_lib.add",
"math_lib.div"
] | [((680, 692), 'math_lib.add', 'ml.add', (['a', 'b'], {}), '(a, b)\n', (686, 692), True, 'import math_lib as ml\n'), ((756, 768), 'math_lib.div', 'ml.div', (['a', 'b'], {}), '(a, b)\n', (762, 768), True, 'import math_lib as ml\n')] |
import yaml
import os
from opnsense_cli.facades.commands.base import CommandFacade
from opnsense_cli.factories.cli_output_format import CliOutputFormatFactory
from opnsense_cli.formats.base import Format
"""
Click callback methods
See: https://click.palletsprojects.com/en/8.0.x/advanced/#parameter-modifications
"""
... | [
"yaml.load",
"opnsense_cli.factories.cli_output_format.CliOutputFormatFactory._keymap.keys",
"os.path.expanduser",
"opnsense_cli.factories.cli_output_format.CliOutputFormatFactory"
] | [((671, 699), 'os.path.expanduser', 'os.path.expanduser', (['filename'], {}), '(filename)\n', (689, 699), False, 'import os\n'), ((738, 775), 'opnsense_cli.factories.cli_output_format.CliOutputFormatFactory._keymap.keys', 'CliOutputFormatFactory._keymap.keys', ([], {}), '()\n', (773, 775), False, 'from opnsense_cli.fac... |
import psycopg2
import os
class DBHandler:
_max_id_length = 255
_max_record_length = 255
def __init__(self, table_name="intake_records", error_table_name="scan_errors"):
"""
:param table_name: (str) Optional string name of the main db table.
:param error_table_name: (str) Op... | [
"os.environ.get",
"psycopg2.connect"
] | [((407, 448), 'os.environ.get', 'os.environ.get', (['"""CEDA_INTAKE_DB_SETTINGS"""'], {}), "('CEDA_INTAKE_DB_SETTINGS')\n", (421, 448), False, 'import os\n'), ((946, 984), 'psycopg2.connect', 'psycopg2.connect', (['self.connection_info'], {}), '(self.connection_info)\n', (962, 984), False, 'import psycopg2\n'), ((1457,... |
from contextlib import ExitStack as DoesNotRaise
from typing import Tuple, Optional
import numpy as np
import pytest
from onemetric.cv.utils.iou import box_iou, mask_iou, box_iou_batch
@pytest.mark.parametrize(
"box_true, box_detection, expected_result, exception",
[
(None, None, None, pytest.raises... | [
"numpy.testing.assert_array_equal",
"numpy.zeros",
"numpy.ones",
"contextlib.ExitStack",
"pytest.raises",
"numpy.array",
"onemetric.cv.utils.iou.mask_iou",
"onemetric.cv.utils.iou.box_iou_batch",
"onemetric.cv.utils.iou.box_iou"
] | [((1550, 1605), 'onemetric.cv.utils.iou.box_iou', 'box_iou', ([], {'box_true': 'box_true', 'box_detection': 'box_detection'}), '(box_true=box_true, box_detection=box_detection)\n', (1557, 1605), False, 'from onemetric.cv.utils.iou import box_iou, mask_iou, box_iou_batch\n'), ((3366, 3435), 'onemetric.cv.utils.iou.box_i... |
"""
@author: <NAME>,<NAME>
"""
import numpy as np
import streamlit as st
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
st.title("Synapse Unsupervised Models")
uploaded_file = st.file_uploader("Choose a csv file", type="csv")
if uploaded_file is not None:
data = pd.read_csv(... | [
"numpy.sum",
"pandas.read_csv",
"streamlit.title",
"numpy.argmin",
"streamlit.sidebar.selectbox",
"numpy.linalg.svd",
"numpy.mean",
"pandas.DataFrame",
"streamlit.subheader",
"numpy.random.randn",
"streamlit.sidebar.checkbox",
"numpy.std",
"streamlit.info",
"numpy.reshape",
"numpy.cov",
... | [((159, 198), 'streamlit.title', 'st.title', (['"""Synapse Unsupervised Models"""'], {}), "('Synapse Unsupervised Models')\n", (167, 198), True, 'import streamlit as st\n'), ((216, 265), 'streamlit.file_uploader', 'st.file_uploader', (['"""Choose a csv file"""'], {'type': '"""csv"""'}), "('Choose a csv file', type='csv... |
import spam
def TestSystem():
r = spam.system("ls -l")
assert r == 0
def TestNothingDone():
r = spam.nothing_done()
assert r is None
| [
"spam.system",
"spam.nothing_done"
] | [((39, 59), 'spam.system', 'spam.system', (['"""ls -l"""'], {}), "('ls -l')\n", (50, 59), False, 'import spam\n'), ((110, 129), 'spam.nothing_done', 'spam.nothing_done', ([], {}), '()\n', (127, 129), False, 'import spam\n')] |
"""
Checks to see if Makefile follows standards
"""
import re
import os
import pytest
from pytest_repo_health import add_key_to_metadata
from repo_health import get_file_content
module_dict_key = "makefile"
@pytest.fixture(name='makefile')
def fixture_makefile(repo_path):
"""Fixture containing the text content... | [
"pytest.fixture",
"repo_health.get_file_content",
"re.search",
"os.path.join",
"pytest_repo_health.add_key_to_metadata"
] | [((213, 244), 'pytest.fixture', 'pytest.fixture', ([], {'name': '"""makefile"""'}), "(name='makefile')\n", (227, 244), False, 'import pytest\n'), ((430, 479), 'pytest_repo_health.add_key_to_metadata', 'add_key_to_metadata', (["(module_dict_key, 'upgrade')"], {}), "((module_dict_key, 'upgrade'))\n", (449, 479), False, '... |
# --------------------------------------------------------------------------------------------------------------------------------
# Imports and Executables
# --------------------------------------------------------------------------------------------------------------------------... | [
"bs4.BeautifulSoup",
"pandas.read_html",
"splinter.Browser",
"datetime.datetime.now"
] | [((871, 942), 'splinter.Browser', 'Browser', (['"""chrome"""'], {'headless': '(True)'}), "('chrome', **{'executable_path': 'chromedriver'}, headless=True)\n", (878, 942), False, 'from splinter import Browser\n'), ((2537, 2569), 'bs4.BeautifulSoup', 'soupy', (['parse_html', '"""html.parser"""'], {}), "(parse_html, 'html... |
''' models for storing different kinds of Activities '''
from django.utils import timezone
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from model_utils.managers import InheritanceManager
from bookwyrm import activitypub
from .base_model import ActivitypubMixin, ... | [
"django.db.models.ManyToManyField",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.utils.timezone.now",
"model_utils.managers.InheritanceManager",
"django.core.validators.MinValueValidator",
"django.db.models.Q",
"django.db.models.BooleanField",
"django.db.models.IntegerField",... | [((9232, 9339), 'django.db.models.TextChoices', 'models.TextChoices', (['"""NotificationType"""', '"""FAVORITE REPLY MENTION TAG FOLLOW FOLLOW_REQUEST BOOST IMPORT"""'], {}), "('NotificationType',\n 'FAVORITE REPLY MENTION TAG FOLLOW FOLLOW_REQUEST BOOST IMPORT')\n", (9250, 9339), False, 'from django.db import model... |
from __future__ import absolute_import
from unittest import TestCase
from mock import MagicMock, patch
import socket
import tempfile
import os
import shutil
from sfmutils.consumer import MqConfig
from sfmutils.stream_consumer import StreamConsumer
from sfmutils.supervisor import HarvestSupervisor
class TestStreamCons... | [
"sfmutils.consumer.MqConfig",
"os.path.exists",
"mock.patch",
"socket.gethostname",
"tempfile.mkdtemp",
"shutil.rmtree",
"mock.MagicMock"
] | [((380, 431), 'mock.patch', 'patch', (['"""sfmutils.stream_consumer.HarvestSupervisor"""'], {}), "('sfmutils.stream_consumer.HarvestSupervisor')\n", (385, 431), False, 'from mock import MagicMock, patch\n'), ((516, 549), 'mock.MagicMock', 'MagicMock', ([], {'spec': 'HarvestSupervisor'}), '(spec=HarvestSupervisor)\n', (... |
from itertools import count
from aocd import lines
rows = len(lines)
cols = len(lines[0])
_map = {}
east = []
south = []
for y, line in enumerate(lines):
for x, sc in enumerate(line):
if sc == '>':
east.append((x,y))
elif sc == 'v':
south.append((x,y))
_map[(x,y)] ... | [
"itertools.count"
] | [((338, 346), 'itertools.count', 'count', (['(1)'], {}), '(1)\n', (343, 346), False, 'from itertools import count\n')] |
from __future__ import print_function
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
try:
import cPickle as pickle
except ImportError:
import pickle
import copy
import numpy as np
from src.SpectralAnalysis import utils
from src.SpectralAnalysis import powerspectrum
from src.Spect... | [
"matplotlib.pyplot.title",
"src.SpectralAnalysis.posterior.StackPerPosterior",
"pickle.dump",
"src.SpectralAnalysis.utils.TwoPrint",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.close",
"src.SpectralAnalysis.mle.PerMaxLike",
"src.SpectralAnalysis.posterior.PerPosterior",... | [((6349, 6376), 'src.SpectralAnalysis.utils.TwoPrint', 'utils.TwoPrint', (['resfilename'], {}), '(resfilename)\n', (6363, 6376), False, 'from src.SpectralAnalysis import utils\n'), ((6589, 6643), 'src.SpectralAnalysis.mle.PerMaxLike', 'mle.PerMaxLike', (['self.ps'], {'fitmethod': 'fitmethod', 'obs': '(True)'}), '(self.... |
import torch.nn as nn
import torch
import torch.nn.functional as F
from torch.autograd import Variable
class FeatureExtractor(nn.Module):
def __init__(self, voacb_size, embedding_dim=300, hidden_dim=300):
super(FeatureExtractor, self).__init__()
self.embedding_dim = embedding_dim
self.hi... | [
"torch.nn.Dropout",
"torch.nn.ReLU",
"torch.nn.Embedding",
"torch.cat",
"torch.nn.Linear",
"torch.nn.LSTM"
] | [((368, 407), 'torch.nn.Embedding', 'nn.Embedding', (['voacb_size', 'embedding_dim'], {}), '(voacb_size, embedding_dim)\n', (380, 407), True, 'import torch.nn as nn\n'), ((428, 480), 'torch.nn.LSTM', 'nn.LSTM', (['embedding_dim', 'hidden_dim'], {'batch_first': '(True)'}), '(embedding_dim, hidden_dim, batch_first=True)\... |
import warnings
import matplotlib.pyplot as plt
import pandas as pd
import pytask
import seaborn as sns
from src.config import BLD
from src.config import PLOT_END_DATE
from src.config import PLOT_SIZE
from src.config import PLOT_START_DATE
from src.config import SRC
from src.plotting.plotting import style_plot
from s... | [
"seaborn.lineplot",
"pytask.mark.produces",
"warnings.filterwarnings",
"matplotlib.pyplot.close",
"pytask.mark.depends_on",
"src.testing.shared.get_piecewise_linear_interpolation",
"src.plotting.plotting.style_plot",
"warnings.catch_warnings",
"pandas.read_pickle",
"matplotlib.pyplot.subplots"
] | [((383, 605), 'pytask.mark.depends_on', 'pytask.mark.depends_on', (["{'params': BLD / 'params.pkl', 'rki': BLD / 'data' /\n 'processed_time_series' / 'rki.pkl', 'plotting.py': SRC / 'plotting' /\n 'plotting.py', 'testing_shared.py': SRC / 'testing' / 'shared.py'}"], {}), "({'params': BLD / 'params.pkl', 'rki': BL... |
import json
import logging
from typing import Dict
import numpy
class ClientSet:
def __init__(self):
self.sockets_by_host_id = {}
self.route_ids_by_host_id = {}
self.host_ids_by_socket = {}
def add(self, host_id, socket):
logging.info(f"Registered hostID '{host_id}'")
... | [
"logging.info",
"json.loads",
"json.dumps"
] | [((2398, 2443), 'json.dumps', 'json.dumps', (['msg'], {'default': 'default_json_encoder'}), '(msg, default=default_json_encoder)\n', (2408, 2443), False, 'import json\n'), ((2562, 2582), 'json.loads', 'json.loads', (['response'], {}), '(response)\n', (2572, 2582), False, 'import json\n'), ((266, 312), 'logging.info', '... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_utils
----------------------------------
Tests for the various utility operations employed by Magpie.
"""
import os
import unittest
from distutils.version import LooseVersion
import mock
import six
from pyramid.httpexceptions import HTTPBadRequest, HTTPForbidden... | [
"tests.utils.test_request",
"magpie.api.exception.generate_response_http_format",
"tests.utils.check_response_basic_info",
"magpie.api.requests.get_query_param",
"magpie.utils.get_header",
"magpie.api.exception.evaluate_call",
"mock.patch.object",
"pyramid.httpexceptions.HTTPInternalServerError",
"d... | [((4180, 4212), 'tests.utils.mock_request', 'utils.mock_request', (['"""/some/path"""'], {}), "('/some/path')\n", (4198, 4212), False, 'from tests import runner, utils\n'), ((4225, 4258), 'magpie.api.requests.get_query_param', 'ar.get_query_param', (['resp', '"""value"""'], {}), "(resp, 'value')\n", (4243, 4258), True,... |
import os
import csv
from sqlalchemy import Table,literal_column,select
def importVolumes(connection, metadata, source_path):
invVolumes = Table('invVolumes', metadata)
invTypes = Table('invTypes', metadata)
with open(
os.path.join(source_path, 'invVolumes1.csv'), 'r'
) as groupVolumes:
... | [
"sqlalchemy.literal_column",
"sqlalchemy.Table",
"csv.reader",
"os.path.join"
] | [((145, 174), 'sqlalchemy.Table', 'Table', (['"""invVolumes"""', 'metadata'], {}), "('invVolumes', metadata)\n", (150, 174), False, 'from sqlalchemy import Table, literal_column, select\n'), ((190, 217), 'sqlalchemy.Table', 'Table', (['"""invTypes"""', 'metadata'], {}), "('invTypes', metadata)\n", (195, 217), False, 'f... |
# python standard library
from collections import OrderedDict
# third party
from configobj import ConfigObj
# this package
from theape import BasePlugin
from theape.parts.sleep.sleep import TheBigSleep
from theape.infrastructure.timemap import time_validator
SLEEP_SECTION = 'SLEEP'
END_OPTION = 'end'
TOTAL_OPTION =... | [
"collections.OrderedDict",
"theape.parts.sleep.sleep.TheBigSleep",
"configobj.ConfigObj"
] | [((1128, 1141), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (1139, 1141), False, 'from collections import OrderedDict\n'), ((3112, 3185), 'configobj.ConfigObj', 'ConfigObj', (['self.configuration[self.section_header]'], {'configspec': 'configspec'}), '(self.configuration[self.section_header], configspec... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 4 20:13:37 2020
@author: jolsten
"""
import sys, logging
import socket
import time
from abc import ABCMeta, abstractmethod
from .exceptions import *
from .utils import STK_DATEFMT, inherit_docstrings
class _AbstractConnect(metaclass=ABCMeta):
'''An... | [
"logging.error",
"logging.debug",
"socket.socket",
"time.sleep",
"logging.info",
"sys.exit"
] | [((3980, 4029), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (3993, 4029), False, 'import socket\n'), ((4049, 4062), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (4059, 4062), False, 'import time\n'), ((6146, 6185), 'logging.debug', '... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import generators
from __future__ import division
import pipes
from ansible.module_utils.basic import *
class Firebrew(object):
STATUS_SUCCESS = 0
STATUS_FAILURE = 1
... | [
"pipes.quote"
] | [((1008, 1035), 'pipes.quote', 'pipes.quote', (["params['name']"], {}), "(params['name'])\n", (1019, 1035), False, 'import pipes\n'), ((1249, 1273), 'pipes.quote', 'pipes.quote', (['params[opt]'], {}), '(params[opt])\n', (1260, 1273), False, 'import pipes\n')] |
from __future__ import division, print_function, absolute_import
# lookup()
##########
import petl as etl
table1 = [['foo', 'bar'],
['a', 1],
['b', 2],
['b', 3]]
lkp = etl.lookup(table1, 'foo', 'bar')
lkp['a']
lkp['b']
# if no valuespec argument is given, defaults to the whole
# row ... | [
"petl.dictlookup",
"petl.dictlookupone",
"shelve.open",
"petl.lookup",
"petl.lookupone"
] | [((204, 236), 'petl.lookup', 'etl.lookup', (['table1', '"""foo"""', '"""bar"""'], {}), "(table1, 'foo', 'bar')\n", (214, 236), True, 'import petl as etl\n'), ((339, 364), 'petl.lookup', 'etl.lookup', (['table1', '"""foo"""'], {}), "(table1, 'foo')\n", (349, 364), True, 'import petl as etl\n'), ((558, 599), 'petl.lookup... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-10-14 19:45:05
# @Author : jingray (<EMAIL>)
# @Link : http://www.jianshu.com/u/01fb0364467d
# @Version : $Id$
import os
# STRINGS
print("STRINGS")
my_string_1 = "hello"
my_string_2 = 'world'
my_multiline_string = """
Dear World,
Hello. I am a mult... | [
"random.random",
"collections.namedtuple"
] | [((2069, 2116), 'collections.namedtuple', 'namedtuple', (['"""Person"""', "['name', 'age', 'gender']"], {}), "('Person', ['name', 'age', 'gender'])\n", (2079, 2116), False, 'from collections import namedtuple\n'), ((2788, 2799), 'random.random', 'rd.random', ([], {}), '()\n', (2797, 2799), True, 'import random as rd\n'... |
import pytest
from src.lib.time_util import TimeUtil
import datetime
@pytest.fixture(scope="module", autouse=True)
def tmu_object():
tmu = TimeUtil()
yield tmu
class TestTimeUtil:
@pytest.mark.parametrize("test_input, expected_wareki, expected_other", [(
'令和2年10月31日',
'令和',
'2年10... | [
"src.lib.time_util.TimeUtil",
"pytest.fixture",
"pytest.main",
"datetime.datetime",
"pytest.raises",
"datetime.timedelta",
"pytest.mark.parametrize"
] | [((72, 116), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""', 'autouse': '(True)'}), "(scope='module', autouse=True)\n", (86, 116), False, 'import pytest\n'), ((145, 155), 'src.lib.time_util.TimeUtil', 'TimeUtil', ([], {}), '()\n', (153, 155), False, 'from src.lib.time_util import TimeUtil\n'), ((197,... |
#!/usr/bin/env python3
"""
sudo apt-get install libqpdf-dev
"""
import zlib
import argparse
import pikepdf
from pikepdf import Pdf, PdfImage, Name
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib import units
class PdfWater... | [
"reportlab.pdfgen.canvas.Canvas",
"reportlab.pdfbase.ttfonts.TTFont",
"pikepdf.open",
"argparse.ArgumentParser"
] | [((1405, 1430), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1428, 1430), False, 'import argparse\n'), ((936, 969), 'reportlab.pdfgen.canvas.Canvas', 'canvas.Canvas', (['self.pdf_watermark'], {}), '(self.pdf_watermark)\n', (949, 969), False, 'from reportlab.pdfgen import canvas\n'), ((647, 6... |
"""Profiles for Scholarship App"""
__author__ = "<NAME>"
import base64
import bibcat
import datetime
import hashlib
import io
import os
import pprint
import smtplib
import subprocess
import threading
import uuid
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import mimetypes
impo... | [
"subprocess.run",
"threading.Thread.__init__",
"rdflib.Graph",
"rdflib.Literal",
"utilities.Book_Citation",
"email.mime.text.MIMEText",
"click.echo",
"base64.b64decode",
"rdflib.URIRef",
"rdflib.Namespace",
"email.mime.multipart.MIMEMultipart",
"datetime.datetime.utcnow",
"rdflib.BNode",
"... | [((622, 680), 'rdflib.Namespace', 'rdflib.Namespace', (['"""http://id.loc.gov/ontologies/bibframe/"""'], {}), "('http://id.loc.gov/ontologies/bibframe/')\n", (638, 680), False, 'import rdflib\n'), ((688, 760), 'rdflib.Namespace', 'rdflib.Namespace', (['"""https://www.coloradocollege.edu/library/ns/citation/"""'], {}), ... |
'''
Created on Dec 23, 2019
@author: mohammedmostafa
'''
import tensorflow as tf
modelPath = "../model/CNDetector_5.h5"
converter = tf.lite.TFLiteConverter.from_keras_model_file(modelPath)
converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE]
lite_model = converter.convert()
open("../model/CNDetector_Lite_5... | [
"tensorflow.lite.TFLiteConverter.from_keras_model_file"
] | [((135, 191), 'tensorflow.lite.TFLiteConverter.from_keras_model_file', 'tf.lite.TFLiteConverter.from_keras_model_file', (['modelPath'], {}), '(modelPath)\n', (180, 191), True, 'import tensorflow as tf\n')] |
"""USERS - Autoincrement set to PK
Revision ID: d385c3eb6937
Revises: ee2cbe4166fb
Create Date: 2018-02-16 11:23:29.705565
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'd385c3eb6937'
down_revision = 'ee2cbe4166fb'
branch_labels = None
depends_on = None
def... | [
"sqlalchemy.String",
"alembic.op.drop_column",
"alembic.op.f"
] | [((831, 864), 'alembic.op.drop_column', 'op.drop_column', (['"""user"""', '"""surname"""'], {}), "('user', 'surname')\n", (845, 864), False, 'from alembic import op\n'), ((869, 899), 'alembic.op.drop_column', 'op.drop_column', (['"""user"""', '"""name"""'], {}), "('user', 'name')\n", (883, 899), False, 'from alembic im... |
# A large portion of the code came from the COVID-19 Dataset project by Our World in Data
# https://github.com/owid/covid-19-data/tree/master/scripts/scripts/vaccinations/src/vax/manual/twitter
# Mainly contributed by <NAME> https://github.com/lucasrodes
# The code is under completely open access under the Creative Com... | [
"pandas.DataFrame",
"tweepy.API",
"pandas.concat",
"pandas.read_csv",
"os.path.isfile",
"tweepy.Cursor",
"re.findall",
"tweepy.AppAuthHandler",
"re.search",
"os.getenv"
] | [((560, 593), 'os.getenv', 'os.getenv', (['"""TWITTER_CONSUMER_KEY"""'], {}), "('TWITTER_CONSUMER_KEY')\n", (569, 593), False, 'import os\n'), ((624, 660), 'os.getenv', 'os.getenv', (['"""TWITTER_CONSUMER_SECRET"""'], {}), "('TWITTER_CONSUMER_SECRET')\n", (633, 660), False, 'import os\n'), ((883, 935), 'tweepy.AppAuthH... |
from math import pi
import numpy as np
from aleph.consts import *
from reamber.algorithms.generate.sv.generators.svOsuMeasureLineMD import svOsuMeasureLineMD, SvOsuMeasureLineEvent
from reamber.osu.OsuMap import OsuMap
# notes: 01:37:742 (97742|2,125moves993|2) -
SHAKES = np.array(
[100560, 100790, 101018, ... | [
"numpy.sin",
"numpy.array",
"numpy.linspace",
"reamber.algorithms.generate.sv.generators.svOsuMeasureLineMD.svOsuMeasureLineMD"
] | [((277, 896), 'numpy.array', 'np.array', (['[100560, 100790, 101018, 101245, 104124, 104340, 104556, 104770, 107487, \n 107692, 107896, 108099, 110674, 110867, 111059, 111156, 111252, 111348,\n 113698, 113882, 114065, 114248, 116577, 116753, 116928, 117103, 119326,\n 119494, 119661, 119827, 121953, 122114, 122... |
#!/usr/bin/env python3
# Copyright (c) 2017 AT&T Intellectual Property. 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-... | [
"subprocess.Popen",
"pandocfilters.walk",
"os.path.isfile",
"pandocfilters.get_value",
"sys.stderr.write",
"pandocfilters.toJSONFilter",
"re.sub"
] | [((1213, 1287), 'subprocess.Popen', 'Popen', (["['pandoc', '-f', 'markdown', '-t', 'json']"], {'stdin': 'PIPE', 'stdout': 'PIPE'}), "(['pandoc', '-f', 'markdown', '-t', 'json'], stdin=PIPE, stdout=PIPE)\n", (1218, 1287), False, 'from subprocess import Popen, PIPE\n'), ((4618, 4638), 'pandocfilters.toJSONFilter', 'toJSO... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# Copyright (c) 2021
#
# See the LICENSE file for details
# see the AUTHORS file for authors
# ----------------------------------------------------------------------
#--------------------
# System wide imports
# ----------... | [
"streetool.utils.paging",
"logging.getLogger"
] | [((553, 584), 'logging.getLogger', 'logging.getLogger', (['"""streetoool"""'], {}), "('streetoool')\n", (570, 584), False, 'import logging\n'), ((1831, 1871), 'streetool.utils.paging', 'paging', ([], {'iterable': 'cursor', 'headers': 'headers'}), '(iterable=cursor, headers=headers)\n', (1837, 1871), False, 'from street... |
import argparse
import math
import pysam
import shap
import tensorflow
from deeplift.dinuc_shuffle import dinuc_shuffle
from scipy.spatial.distance import jensenshannon
from scipy.special import logit, softmax
tensorflow.compat.v1.disable_v2_behavior()
import kerasAC
import matplotlib
import pandas as pd
from keras... | [
"deeplift.dinuc_shuffle.dinuc_shuffle",
"tensorflow.keras.models.load_model",
"pysam.FastaFile",
"argparse.ArgumentParser",
"pandas.read_csv",
"tensorflow.keras.utils.get_custom_objects",
"shap.DeepExplainer",
"tensorflow.compat.v1.disable_v2_behavior"
] | [((214, 256), 'tensorflow.compat.v1.disable_v2_behavior', 'tensorflow.compat.v1.disable_v2_behavior', ([], {}), '()\n', (254, 256), False, 'import tensorflow\n'), ((623, 693), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Argument Parser for SNP scoring"""'}), "(description='Argument Pa... |
# Generated by Django 1.11.13 on 2019-04-04 01:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("advicer", "0016_auto_20190404_0320")]
operations = [
migrations.AlterField(
model_name="advice",
name="subject",
fie... | [
"django.db.models.CharField"
] | [((323, 402), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(100)', 'null': '(True)', 'verbose_name': '"""Subject"""'}), "(blank=True, max_length=100, null=True, verbose_name='Subject')\n", (339, 402), False, 'from django.db import migrations, models\n')] |
from __future__ import division, print_function, unicode_literals
import streamlit as st
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
st.title('Mô hình dự đoán giá nhà đất tại hồ gươm... | [
"streamlit.set_option",
"streamlit.sidebar.write",
"sklearn.model_selection.train_test_split",
"numpy.ones",
"streamlit.title",
"streamlit.sidebar.title",
"matplotlib.pyplot.figure",
"numpy.array",
"numpy.dot",
"streamlit.sidebar.text_input",
"streamlit.sidebar.button",
"numpy.linalg.pinv",
... | [((271, 323), 'streamlit.title', 'st.title', (['"""Mô hình dự đoán giá nhà đất tại hồ gươm """'], {}), "('Mô hình dự đoán giá nhà đất tại hồ gươm ')\n", (279, 323), True, 'import streamlit as st\n'), ((449, 2354), 'numpy.array', 'np.array', (['[[40, 8, 2, 1800], [36, 3.5, 6, 450], [35, 4.5, 6, 450], [39, 9, 2, 1800],\n... |
#################################################################
# Libraries
#################################################################
import sys, os
import pytest
import bitarray
from granite.toBig import (
main as main_toBig
)
from granite.lib.shared_... | [
"pytest.raises",
"os.remove",
"bitarray.bitarray",
"granite.toBig.main"
] | [((938, 954), 'granite.toBig.main', 'main_toBig', (['args'], {}), '(args)\n', (948, 954), True, 'from granite.toBig import main as main_toBig\n'), ((1095, 1123), 'bitarray.bitarray', 'bitarray.bitarray', (['(11030 + 1)'], {}), '(11030 + 1)\n', (1112, 1123), False, 'import bitarray\n'), ((1622, 1660), 'os.remove', 'os.r... |
from django.conf.urls import url
from django.views.generic import ListView, DetailView
from models import Notas
from .views import *
urlpatterns = [
url(r'^$', list_notas,name='notas_list'),
# url(r'^$', 'lista_notas', name="notas_list"),
url(r'^pais/(?P<id>\d+)/$', lista_notas_pais, name="notas_list_pais"... | [
"django.conf.urls.url"
] | [((154, 194), 'django.conf.urls.url', 'url', (['"""^$"""', 'list_notas'], {'name': '"""notas_list"""'}), "('^$', list_notas, name='notas_list')\n", (157, 194), False, 'from django.conf.urls import url\n'), ((252, 321), 'django.conf.urls.url', 'url', (['"""^pais/(?P<id>\\\\d+)/$"""', 'lista_notas_pais'], {'name': '"""no... |
# -*- coding: utf-8 -*-
#/usr/bin/python2
'''
June 2017 by <NAME>.
<EMAIL>.
https://www.github.com/kyubyong/transformer
'''
from __future__ import print_function
import codecs
import os
import tensorflow as tf
import numpy as np
from hyperparams import Hyperparams as hp
from data_load import load_test_data, load_de... | [
"train.Graph",
"data_load.load_en_vocab",
"numpy.zeros",
"tensorflow.train.Supervisor",
"tensorflow.ConfigProto",
"tensorflow.train.latest_checkpoint",
"numpy.array"
] | [((456, 480), 'train.Graph', 'Graph', ([], {'is_training': '(False)'}), '(is_training=False)\n', (461, 480), False, 'from train import Graph\n'), ((1395, 1410), 'data_load.load_en_vocab', 'load_en_vocab', ([], {}), '()\n', (1408, 1410), False, 'from data_load import load_test_data, load_de_vocab, load_en_vocab\n'), ((1... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "forecastsite.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
try:
import django
except ImportError:
... | [
"os.environ.setdefault",
"django.core.management.execute_from_command_line"
] | [((75, 147), 'os.environ.setdefault', 'os.environ.setdefault', (['"""DJANGO_SETTINGS_MODULE"""', '"""forecastsite.settings"""'], {}), "('DJANGO_SETTINGS_MODULE', 'forecastsite.settings')\n", (96, 147), False, 'import os\n'), ((428, 463), 'django.core.management.execute_from_command_line', 'execute_from_command_line', (... |
import torch.nn as nn
import torch
class LabelSmoothing(nn.Module):
def __init__(self, size, smoothing=0.0):
super(LabelSmoothing, self).__init__()
self.criterion = nn.KLDivLoss(size_average=False)
#self.padding_idx = padding_idx
self.confidence = 1.0 - smoothing
self.smoothi... | [
"torch.nn.KLDivLoss",
"torch.no_grad",
"torch.sum",
"torch.zeros_like"
] | [((185, 217), 'torch.nn.KLDivLoss', 'nn.KLDivLoss', ([], {'size_average': '(False)'}), '(size_average=False)\n', (197, 217), True, 'import torch.nn as nn\n'), ((1400, 1415), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1413, 1415), False, 'import torch\n'), ((1483, 1505), 'torch.zeros_like', 'torch.zeros_like',... |
# -*- coding: utf-8 -*-
from __future__ import division
import unittest
import odelab
from odelab.scheme.stochastic import *
from odelab.system import *
from odelab.solver import *
import numpy as np
class Test_OU(unittest.TestCase):
def test_run(self):
sys = OrnsteinUhlenbeck()
scheme = EulerMaruyama()
sc... | [
"numpy.array"
] | [((397, 412), 'numpy.array', 'np.array', (['[1.0]'], {}), '([1.0])\n', (405, 412), True, 'import numpy as np\n'), ((745, 772), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 0.0]'], {}), '([0, 0, 0, 0, 0.0])\n', (753, 772), True, 'import numpy as np\n')] |
'''
Listing 5.1: Operator usage (and vector usage)
'''
import pyopencl as cl
import pyopencl.array
import utility
kernel_src = '''
__kernel void op_test(__global int4 *output) {
int4 vec = (int4)(1, 2, 3, 4);
/* Adds 4 to every element of vec */
vec += 4;
/* Sets the third element to 0
Doesn't cha... | [
"utility.get_default_device",
"pyopencl.array.vec.zeros_int4",
"pyopencl.enqueue_copy",
"pyopencl.Context",
"pyopencl.CommandQueue",
"pyopencl.Buffer",
"pyopencl.Program"
] | [((775, 803), 'utility.get_default_device', 'utility.get_default_device', ([], {}), '()\n', (801, 803), False, 'import utility\n'), ((814, 839), 'pyopencl.Context', 'cl.Context', ([], {'devices': '[dev]'}), '(devices=[dev])\n', (824, 839), True, 'import pyopencl as cl\n'), ((848, 877), 'pyopencl.CommandQueue', 'cl.Comm... |
import time
from surgeon import *
ori_time=int()
cur_time=int()
pre_time=int()
waves=int()
double_water=False
AUTO=False
def fight_start():
global ori_time,started,double_water,pre_time
ori_time=time.time()
pre_time=0
started=True
double_water=False
def fight_end():
global started
print... | [
"time.sleep",
"time.time"
] | [((207, 218), 'time.time', 'time.time', ([], {}), '()\n', (216, 218), False, 'import time\n'), ((472, 483), 'time.time', 'time.time', ([], {}), '()\n', (481, 483), False, 'import time\n'), ((839, 850), 'time.time', 'time.time', ([], {}), '()\n', (848, 850), False, 'import time\n'), ((1031, 1042), 'time.time', 'time.tim... |
""" https://adventofcode.com/2021/day/17 """
import re
import math
from typing import Tuple
class Rect:
"""A 2D rectangle defined by top-left and bottom-right positions"""
def __init__(self, left, right, bottom, top):
self.left = left
self.right = right
self.bottom = bottom
sel... | [
"re.search",
"math.sqrt"
] | [((567, 643), 're.search', 're.search', (['"""target area: x=(-?\\\\d*)..(-?\\\\d*), y=(-?\\\\d*)..(-?\\\\d*)"""', 'string'], {}), "('target area: x=(-?\\\\d*)..(-?\\\\d*), y=(-?\\\\d*)..(-?\\\\d*)', string)\n", (576, 643), False, 'import re\n'), ((2363, 2393), 'math.sqrt', 'math.sqrt', (['(1 + target.left * 8)'], {}),... |
import numpy as np
from collections import namedtuple
import skimage.measure
#import matplotlib.pyplot as plt
#import ipdb
# could maybe turn this into a generic mutable namedtuple
class Point2D(object):
__slots__ = "x", "y"
def __init__(self, x, y):
self.x = x
self.y = y
def __iter__(self):
'''itera... | [
"numpy.ones_like",
"numpy.empty",
"numpy.zeros",
"numpy.flipud",
"numpy.fliplr",
"collections.namedtuple",
"numpy.atleast_2d"
] | [((4577, 4629), 'collections.namedtuple', 'namedtuple', (['"""BoundingBox"""', '"""min_x max_x min_y max_y"""'], {}), "('BoundingBox', 'min_x max_x min_y max_y')\n", (4587, 4629), False, 'from collections import namedtuple\n'), ((9981, 10033), 'collections.namedtuple', 'namedtuple', (['"""BoundingBox"""', '"""min_x max... |
from common import *
from os.path import join as join_path, isdir
from shutil import rmtree
from os import mkdir
import feedparser
from bs4 import BeautifulSoup as bs
languages_names = [x['name'] for x in languages]
rss_sources = {
'da': [
'https://politiken.dk/rss/senestenyt.rss',
'https://borsen... | [
"feedparser.parse",
"os.mkdir",
"os.path.isdir",
"bs4.BeautifulSoup",
"shutil.rmtree",
"os.path.join"
] | [((2266, 2291), 'os.path.isdir', 'isdir', (['VALIDATION_SET_DIR'], {}), '(VALIDATION_SET_DIR)\n', (2271, 2291), False, 'from os.path import join as join_path, isdir\n'), ((2689, 2714), 'os.mkdir', 'mkdir', (['VALIDATION_SET_DIR'], {}), '(VALIDATION_SET_DIR)\n', (2694, 2714), False, 'from os import mkdir\n'), ((2208, 22... |