code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | [
"rdflib.URIRef",
"pyaff4.rdfvalue.URN"
] | [((6622, 6668), 'rdflib.URIRef', 'rdflib.URIRef', (['"""http://aff4.org/Schema#SHA512"""'], {}), "('http://aff4.org/Schema#SHA512')\n", (6635, 6668), False, 'import rdflib\n'), ((6683, 6729), 'rdflib.URIRef', 'rdflib.URIRef', (['"""http://aff4.org/Schema#SHA256"""'], {}), "('http://aff4.org/Schema#SHA256')\n", (6696, 6... |
import queue
import threading
from subprocess import PIPE, Popen
procs = []
stdout = queue.Queue()
def process_stdout(proc):
while (line := proc.stdout.readline()) != b"":
stdout.put(line.decode().strip())
procs.remove(proc)
def create_proc(uri):
proc = Popen(["unbuffer", "xdg-open", uri], stdo... | [
"subprocess.Popen",
"queue.Queue"
] | [((86, 99), 'queue.Queue', 'queue.Queue', ([], {}), '()\n', (97, 99), False, 'import queue\n'), ((279, 341), 'subprocess.Popen', 'Popen', (["['unbuffer', 'xdg-open', uri]"], {'stdout': 'PIPE', 'stderr': 'PIPE'}), "(['unbuffer', 'xdg-open', uri], stdout=PIPE, stderr=PIPE)\n", (284, 341), False, 'from subprocess import P... |
import torch
import numpy as np
import matplotlib.pyplot as plt
from lib.utils import moving_average, check_numpy
@torch.no_grad()
def visualize_pdf(maml):
i = 0
plt.figure(figsize=[22, 34])
for name, (weight_maml_init, bias_maml_init) in maml.initializers.items():
weight_base_init, _ = maml.untra... | [
"matplotlib.pyplot.title",
"torch.distributions.Normal",
"matplotlib.pyplot.xticks",
"lib.utils.check_numpy",
"matplotlib.pyplot.plot",
"lib.utils.moving_average",
"torch.tensor",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.yticks",
"torch.linspace",
"torch.no_grad",
"matplotlib.pyplot.xlim... | [((117, 132), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (130, 132), False, 'import torch\n'), ((1674, 1689), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1687, 1689), False, 'import torch\n'), ((172, 200), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '[22, 34]'}), '(figsize=[22, 34])\n',... |
import os
import re
import glob
import argparse
import pandas as pd
list_test = ['alexnet',
'inception3',
'inception4',
'resnet152',
'resnet50',
'vgg16']
# Naming convention
# Key: log name
# Value: ([num_gpus], [names])
# num_gpus: Since each log... | [
"pandas.DataFrame",
"glob.glob",
"argparse.ArgumentParser"
] | [((4377, 4441), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Gather benchmark results."""'}), "(description='Gather benchmark results.')\n", (4400, 4441), False, 'import argparse\n'), ((5443, 5488), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'list_row', 'columns': 'columns'}), ... |
# This is an automatically generated file.
# DO NOT EDIT or your changes may be overwritten
import base64
from xdrlib import Packer, Unpacker
from ..type_checked import type_checked
from .survey_message_command_type import SurveyMessageCommandType
from .topology_response_body import TopologyResponseBody
__all__ = ["S... | [
"xdrlib.Packer",
"base64.b64encode",
"xdrlib.Unpacker"
] | [((1621, 1629), 'xdrlib.Packer', 'Packer', ([], {}), '()\n', (1627, 1629), False, 'from xdrlib import Packer, Unpacker\n'), ((1793, 1806), 'xdrlib.Unpacker', 'Unpacker', (['xdr'], {}), '(xdr)\n', (1801, 1806), False, 'from xdrlib import Packer, Unpacker\n'), ((1928, 1955), 'base64.b64encode', 'base64.b64encode', (['xdr... |
# Generated by Django 3.1.5 on 2021-01-14 22:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('poll', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Topic',
fields=[
('id', model... | [
"django.db.models.AutoField",
"django.db.models.ManyToManyField",
"django.db.models.CharField"
] | [((679, 744), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'related_name': '"""questions"""', 'to': '"""poll.Topic"""'}), "(related_name='questions', to='poll.Topic')\n", (701, 744), False, 'from django.db import migrations, models\n'), ((315, 408), 'django.db.models.AutoField', 'models.AutoField... |
import wikipedia
from topicblob import TopicBlob
#get random wikipeida summaries
wiki_pages = ["Facebook","New York City","Barack Obama","Wikipedia","Topic Modeling","Python (programming language)","Snapchat"]
wiki_pages = ["Facebook","New York City","Barack Obama"]
texts = []
for page in wiki_pages:
text = ... | [
"topicblob.TopicBlob",
"wikipedia.summary"
] | [((393, 417), 'topicblob.TopicBlob', 'TopicBlob', (['texts', '(20)', '(50)'], {}), '(texts, 20, 50)\n', (402, 417), False, 'from topicblob import TopicBlob\n'), ((320, 343), 'wikipedia.summary', 'wikipedia.summary', (['page'], {}), '(page)\n', (337, 343), False, 'import wikipedia\n')] |
from sanic_jwt import exceptions
class User:
def __init__(self, id, username, password):
self.user_id = id
self.username = username
self.password = password
def __repr__(self):
return "User(id='{}')".format(self.user_id)
def to_dict(self):
return {"user_id": self.... | [
"sanic_jwt.exceptions.AuthenticationFailed"
] | [((708, 772), 'sanic_jwt.exceptions.AuthenticationFailed', 'exceptions.AuthenticationFailed', (['"""Missing username or password."""'], {}), "('Missing username or password.')\n", (739, 772), False, 'from sanic_jwt import exceptions\n'), ((884, 949), 'sanic_jwt.exceptions.AuthenticationFailed', 'exceptions.Authenticati... |
# coding=utf-8
def pdf2text(pdf_path,encoding="ASCII7"):
import subprocess
import os.path
pdf_path = os.path.abspath(pdf_path)
subprocess.call(["pdftotext","-l","1","-enc",encoding,"-q",pdf_path])
text = os.path.splitext(pdf_path)[0] + ".txt"
return text
def pick_out_doi(txt):
import re
... | [
"urllib2.urlopen",
"re.compile",
"urllib2.Request",
"urllib2.quote",
"subprocess.call"
] | [((144, 219), 'subprocess.call', 'subprocess.call', (["['pdftotext', '-l', '1', '-enc', encoding, '-q', pdf_path]"], {}), "(['pdftotext', '-l', '1', '-enc', encoding, '-q', pdf_path])\n", (159, 219), False, 'import subprocess\n'), ((349, 423), 're.compile', 're.compile', (['"""\\\\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?![... |
# Copyright 2017 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... | [
"tensorflow.python.data.kernel_tests.test_base.default_test_combinations",
"tensorflow.python.data.ops.readers.TextLineDataset",
"tensorflow.python.platform.test.main"
] | [((2301, 2312), 'tensorflow.python.platform.test.main', 'test.main', ([], {}), '()\n', (2310, 2312), False, 'from tensorflow.python.platform import test\n'), ((1520, 1620), 'tensorflow.python.data.ops.readers.TextLineDataset', 'core_readers.TextLineDataset', (['test_filenames'], {'compression_type': 'compression_type',... |
#Author:<NAME>
from django import forms
from apps.forms import FormMixin
class PublicCommentForm(forms.Form,FormMixin):
#CharField字长在form可不定义,但是在model模型中必须定义
content=forms.CharField()
news_id=forms.IntegerField()
| [
"django.forms.IntegerField",
"django.forms.CharField"
] | [((176, 193), 'django.forms.CharField', 'forms.CharField', ([], {}), '()\n', (191, 193), False, 'from django import forms\n'), ((206, 226), 'django.forms.IntegerField', 'forms.IntegerField', ([], {}), '()\n', (224, 226), False, 'from django import forms\n')] |
### Data Preprocessing
## 1. Json to Transcript
## 2. Aligner
## 3. Text Replace
from jamo import h2j
import json
import os, re, tqdm
import unicodedata
from tqdm import tqdm
import hparams as hp
name = hp.dataset
first_dir = os.getcwd()
transcript = name + '_transcript.txt'
dict_name = name + '_k... | [
"jamo.h2j",
"os.listdir",
"re.compile",
"os.rename",
"tqdm.tqdm",
"os.path.join",
"os.getcwd",
"os.chdir",
"json.load",
"os.mkdir",
"re.sub",
"os.system"
] | [((244, 255), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (253, 255), False, 'import os, re, tqdm\n'), ((494, 514), 'os.listdir', 'os.listdir', (['base_dir'], {}), '(base_dir)\n', (504, 514), False, 'import os, re, tqdm\n'), ((1843, 1858), 'os.chdir', 'os.chdir', (['"""../"""'], {}), "('../')\n", (1851, 1858), False, '... |
#!/usr/bin/env python3
import requests
import os
import json
CACHET_HOSTNAME = os.environ.get("CACHET_HOSTNAME")
URL = f"https://{CACHET_HOSTNAME}/api/v1/components"
HEADERS = {
'X-Cachet-Token': os.environ.get("CACHET_TOKEN")
}
with requests.Session() as session:
session.headers.update(HEADERS)
respon... | [
"os.environ.get",
"requests.Session"
] | [((81, 114), 'os.environ.get', 'os.environ.get', (['"""CACHET_HOSTNAME"""'], {}), "('CACHET_HOSTNAME')\n", (95, 114), False, 'import os\n'), ((203, 233), 'os.environ.get', 'os.environ.get', (['"""CACHET_TOKEN"""'], {}), "('CACHET_TOKEN')\n", (217, 233), False, 'import os\n'), ((242, 260), 'requests.Session', 'requests.... |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
# Copyright (c) 2016 France-IOI, MIT license
#
# http://opensource.org/licenses/MIT
# This tool launches an isolated execution. It is intended as a wrapper around
# the execution of any command.
import argparse, os, sys
DEFAULT_EXECPARAMS = {
'timeLimitMs': 60000... | [
"argparse.ArgumentParser",
"os.path.join",
"sys.stderr.write",
"sys.exit",
"os.path.abspath",
"taskgrader.IsolatedExecution"
] | [((577, 605), 'os.path.join', 'os.path.join', (['SELFDIR', '"""../"""'], {}), "(SELFDIR, '../')\n", (589, 605), False, 'import argparse, os, sys\n'), ((694, 856), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Makes a \'standalone\' JSON file, bundling files referenced by path into the J... |
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
from collections import deque
n, m = map(int, readline().split())
s = readline().rstrip().decode()[::-1]
index = 0
ans = deque([])
for i in range(n):
for j in range(m,... | [
"sys.setrecursionlimit",
"collections.deque"
] | [((116, 146), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(10 ** 7)'], {}), '(10 ** 7)\n', (137, 146), False, 'import sys\n'), ((270, 279), 'collections.deque', 'deque', (['[]'], {}), '([])\n', (275, 279), False, 'from collections import deque\n')] |
"""Unit test to test app."""
import os
from unittest import TestCase
import mock
from src import app
class TestApp(TestCase):
"""Unit test class to test other methods in the app."""
def test_valid_env(self):
key = 'ENV_1'
os.environ[key] = 'test'
app.get_or_raise(key)
del os... | [
"src.app.run",
"mock.patch",
"src.app.str_to_bool",
"src.app.get_or_raise"
] | [((940, 973), 'mock.patch', 'mock.patch', (['"""src.app.prepare_avd"""'], {}), "('src.app.prepare_avd')\n", (950, 973), False, 'import mock\n'), ((979, 1009), 'mock.patch', 'mock.patch', (['"""subprocess.Popen"""'], {}), "('subprocess.Popen')\n", (989, 1009), False, 'import mock\n'), ((1365, 1398), 'mock.patch', 'mock.... |
#!/usr/bin/python3
import os
import sys
from http.server import HTTPServer, BaseHTTPRequestHandler
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
# do not change paths
if self.path == '/apis/apps.openshift.io/v1/namespaces/testNamespace/deploymentconfigs?labelSelector=services.server... | [
"http.server.HTTPServer",
"os.path.join",
"sys.exit"
] | [((2158, 2200), 'http.server.HTTPServer', 'HTTPServer', (["('localhost', 8080)", 'MyHandler'], {}), "(('localhost', 8080), MyHandler)\n", (2168, 2200), False, 'from http.server import HTTPServer, BaseHTTPRequestHandler\n'), ((525, 581), 'os.path.join', 'os.path.join', (['sys.path[0]', '"""responses/kieserver-dc.json"""... |
# coding: utf-8
"""
Octopus Server API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 2019.6.7+Branch.tags-2019.6.7.Sha.aa18dc6809953218c66f57eff7d26481d9b23d6a
Generated by: https://github.com/swagger-api... | [
"six.iteritems"
] | [((8635, 8668), 'six.iteritems', 'six.iteritems', (['self.swagger_types'], {}), '(self.swagger_types)\n', (8648, 8668), False, 'import six\n')] |
import re
def str2bool(my_str):
"""returns a reasonable boolean from a string so that "False" will result in False"""
if my_str is None:
return False
elif isinstance(my_str, str) and my_str.lower() == "false":
return False
elif isinstance(my_str, str) and my_str.lower() == "off":
... | [
"re.compile"
] | [((470, 499), 're.compile', 're.compile', (['"""(?<!^)(?=[A-Z])"""'], {}), "('(?<!^)(?=[A-Z])')\n", (480, 499), False, 'import re\n')] |
import collections
from typing import Optional
import numpy as np
from astromodels import Parameter, Model
from astromodels.functions.priors import Cosine_Prior, Uniform_prior
from threeML import PluginPrototype
from threeML.io.file_utils import sanitize_filename
from threeML.plugins.DispersionSpectrumLike import Dis... | [
"astromodels.functions.priors.Uniform_prior",
"threeML.io.logging.setup_logger",
"astromodels.functions.priors.Cosine_Prior"
] | [((494, 516), 'threeML.io.logging.setup_logger', 'setup_logger', (['__name__'], {}), '(__name__)\n', (506, 516), False, 'from threeML.io.logging import setup_logger\n'), ((2602, 2649), 'astromodels.functions.priors.Uniform_prior', 'Uniform_prior', ([], {'lower_bound': '(0.0)', 'upper_bound': '(360)'}), '(lower_bound=0.... |
import matplotlib.pyplot as plt
def _determine_vmax(max_data_value):
vmax = 1
if max_data_value > 255:
vmax = None
elif max_data_value > 1:
vmax = 255
return vmax
def plot_image(heatmap, original_data=None, heatmap_cmap=None, data_cmap=None, show_plot=True, output_filename=None): # ... | [
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((1415, 1429), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1427, 1429), True, 'import matplotlib.pyplot as plt\n'), ((1809, 1819), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1817, 1819), True, 'import matplotlib.pyplot as plt\n'), ((1852, 1880), 'matplotlib.pyplot.savefig', 'plt.save... |
""" All Available Module on Server Belong to Here """
AVAILABLE_MODULES = (
"api",
)
def init_app(app, **kwargs):
from importlib import import_module
for module in AVAILABLE_MODULES:
import_module(
f".{module}",
package=__name__
).init_app(app, **kwargs) | [
"importlib.import_module"
] | [((205, 250), 'importlib.import_module', 'import_module', (['f""".{module}"""'], {'package': '__name__'}), "(f'.{module}', package=__name__)\n", (218, 250), False, 'from importlib import import_module\n')] |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 19 23:19:43 2020
@author: elif.ayvali
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
class deep_Q_net(nn.Module):
"""Actor (Policy) Model."""
def __init__(self, state_size, action_size, seed):
... | [
"torch.manual_seed",
"torch.nn.ReLU",
"torch.nn.Linear"
] | [((749, 772), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (766, 772), False, 'import torch\n'), ((863, 889), 'torch.nn.Linear', 'nn.Linear', (['state_size', '(256)'], {}), '(state_size, 256)\n', (872, 889), True, 'import torch.nn as nn\n'), ((918, 927), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '(... |
import numpy as np
import pandas as pd
from typing import Tuple, Dict
from .load_csv import load_raw_classes, load_raw_epigenomic_data, load_raw_nucleotides_sequences
from .store_csv import store_raw_classes, store_raw_epigenomic_data, store_raw_nucleotides_sequences
from auto_tqdm import tqdm
def drop_unknown_datapoi... | [
"auto_tqdm.tqdm"
] | [((1060, 1112), 'auto_tqdm.tqdm', 'tqdm', (["settings['cell_lines']"], {'desc': '"""Sanitizing data"""'}), "(settings['cell_lines'], desc='Sanitizing data')\n", (1064, 1112), False, 'from auto_tqdm import tqdm\n')] |
# -*- coding: utf-8 -*-
'''
plexOdus Add-on
'''
import json
from resources.lib.modules import client
from resources.lib.modules import control
user = control.setting('fanart.tv.user')
if user == '' or user is None:
user = 'cf0ebcc2f7b824bd04cf3a318f15c17d'
headers = {'api-key': '3eb5ed2c401a206391ea8d1a031... | [
"resources.lib.modules.control.setting",
"resources.lib.modules.client.request",
"resources.lib.modules.control.apiLanguage",
"json.loads"
] | [((158, 191), 'resources.lib.modules.control.setting', 'control.setting', (['"""fanart.tv.user"""'], {}), "('fanart.tv.user')\n", (173, 191), False, 'from resources.lib.modules import control\n'), ((446, 467), 'resources.lib.modules.control.apiLanguage', 'control.apiLanguage', ([], {}), '()\n', (465, 467), False, 'from... |
"""
nuqql conversation helpers
"""
import datetime
import logging
from typing import TYPE_CHECKING
import nuqql.win
from .conversation import CONVERSATIONS
from .logmessage import LogMessage
if TYPE_CHECKING: # imports for typing
# pylint: disable=cyclic-import
from nuqql.backend import Backend # noqa
... | [
"logging.getLogger",
"datetime.datetime.now"
] | [((329, 356), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (346, 356), False, 'import logging\n'), ((996, 1019), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1017, 1019), False, 'import datetime\n')] |
import vaex
import pytest
@pytest.mark.skipif(vaex.utils.devmode, reason='runs too slow when developing')
def test_gcs():
df = vaex.open('gs://vaex-data/testing/xys.hdf5?cache=false&token=anon')
assert df.x.tolist() == [1, 2]
assert df.y.tolist() == [3, 4]
assert df.s.tolist() == ['5', '6']
df = ... | [
"vaex.open",
"pytest.mark.skipif"
] | [((29, 107), 'pytest.mark.skipif', 'pytest.mark.skipif', (['vaex.utils.devmode'], {'reason': '"""runs too slow when developing"""'}), "(vaex.utils.devmode, reason='runs too slow when developing')\n", (47, 107), False, 'import pytest\n'), ((499, 577), 'pytest.mark.skipif', 'pytest.mark.skipif', (['vaex.utils.devmode'], ... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals, print_function
from datetime import datetime
import os
from os.path import dirname, join
import sys
import time
import unittest
import uuid
import logging
LOGGING_FORMAT = '\n%(levelname)s %(asctime)s %(message)s'
logging.basicConfig(lev... | [
"logging.basicConfig",
"os.environ.setdefault",
"logging.getLogger",
"django.setup",
"six.BytesIO",
"qiniustorage.backends.get_qiniu_config",
"os.environ.get",
"os.path.join",
"uuid.uuid4",
"os.path.dirname",
"sys.path.append",
"qiniu.BucketManager"
] | [((297, 359), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': 'LOGGING_FORMAT'}), '(level=logging.INFO, format=LOGGING_FORMAT)\n', (316, 359), False, 'import logging\n'), ((369, 396), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (386, 396), False, ... |
# This file implements functions model_fn, input_fn, predict_fn and output_fn.
# Function model_fn is mandatory. The other functions can be omitted so the standard sagemaker function will be used.
# An alternative to the last 3 functions is to use function transform_fn(model, data, input_content_type, output_content_ty... | [
"torch.cuda.is_available",
"torch.load",
"mnist_demo.models.model.Net",
"os.path.join"
] | [((891, 896), 'mnist_demo.models.model.Net', 'Net', ([], {}), '()\n', (894, 896), False, 'from mnist_demo.models.model import Net\n'), ((911, 947), 'os.path.join', 'os.path.join', (['model_dir', '"""model.pth"""'], {}), "(model_dir, 'model.pth')\n", (923, 947), False, 'import os\n'), ((1045, 1058), 'torch.load', 'torch... |
# -*- coding: utf-8 -*-
import kicad
import model
from stackups import JLCPCB6Layers
#from dram import lp4
# IMX8MM
# Diff pairs should be matched within 1ps
# CK_t/CK_c max 200 ps
# CA[5:0]
# CS[1:0] min: CK_t - 25ps, max: CK_t + 25ps
# CKE[1:0]
# DQS0_t/DQS0_c min: CK_t - 85ps, max CK_t + 85ps
# DQ[7:0]... | [
"stackups.JLCPCB6Layers"
] | [((562, 577), 'stackups.JLCPCB6Layers', 'JLCPCB6Layers', ([], {}), '()\n', (575, 577), False, 'from stackups import JLCPCB6Layers\n')] |
import os
import urllib.request
from zipfile import ZipFile
HOME_DIRECTORY = os.path.join('datasets','raw')
ROOT_URL = 'https://os.unil.cloud.switch.ch/fma/fma_metadata.zip'
if not os.path.isdir(HOME_DIRECTORY):
os.makedirs(HOME_DIRECTORY)
zip_path = os.path.join(HOME_DIRECTORY, 'data.zip')
urllib.request.urlretr... | [
"os.path.isdir",
"os.path.join",
"zipfile.ZipFile",
"os.makedirs"
] | [((78, 109), 'os.path.join', 'os.path.join', (['"""datasets"""', '"""raw"""'], {}), "('datasets', 'raw')\n", (90, 109), False, 'import os\n'), ((257, 297), 'os.path.join', 'os.path.join', (['HOME_DIRECTORY', '"""data.zip"""'], {}), "(HOME_DIRECTORY, 'data.zip')\n", (269, 297), False, 'import os\n'), ((183, 212), 'os.pa... |
# Copyright 2019 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... | [
"tempfile.TemporaryDirectory",
"tensorflow.compat.v2.compat.v1.lite.TFLiteConverter.from_saved_model",
"tensorflow.compat.v2.lite.TFLiteConverter.from_keras_model",
"tensorflow.compat.v2.compat.v1.logging.info",
"os.path.join",
"tensorflow.compat.v2.io.gfile.GFile",
"tensorflow_examples.lite.model_maker... | [((5206, 5284), 'tensorflow.compat.v2.compat.v1.logging.info', 'tf.compat.v1.logging.info', (['"""Exporting to tflite model in %s."""', 'tflite_filepath'], {}), "('Exporting to tflite model in %s.', tflite_filepath)\n", (5231, 5284), True, 'import tensorflow.compat.v2 as tf\n'), ((5342, 5366), 'tensorflow_examples.lite... |
import os
import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from src.architectures.readout import READOUTS
from src.architectures.embedding import EMBEDDINGS
from .attention_pooling import POOLING_LAYERS
from ..message_passing import MP_LAYERS
from ..... | [
"torch.nn.ModuleList",
"torch.bmm"
] | [((2614, 2644), 'torch.nn.ModuleList', 'nn.ModuleList', (['([m1] + matrices)'], {}), '([m1] + matrices)\n', (2627, 2644), True, 'import torch.nn as nn\n'), ((2953, 2974), 'torch.bmm', 'torch.bmm', (['attns', 'dij'], {}), '(attns, dij)\n', (2962, 2974), False, 'import torch\n')] |
#!/usr/bin/env python3
import lib
N=1000000
sieve = lib.get_prime_sieve(N)
primes = lib.primes(N, sieve)
primes = primes[4:]
def is_truncatable(n):
num = n
c = 0
while num:
if not sieve[num]:
return False
num = int(num / 10)
c += 1
while c:
num = n % 10**c
if not sieve[num]:
r... | [
"lib.get_prime_sieve",
"lib.primes"
] | [((53, 75), 'lib.get_prime_sieve', 'lib.get_prime_sieve', (['N'], {}), '(N)\n', (72, 75), False, 'import lib\n'), ((85, 105), 'lib.primes', 'lib.primes', (['N', 'sieve'], {}), '(N, sieve)\n', (95, 105), False, 'import lib\n')] |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""Tests for utility classes."""
import datetime
import sys
import unittest
from absl import app
from absl.testing import absltest
from grr_response_core.lib import rdfvalue
from grr.test_lib import test_lib
long_string = (
"迎欢迎\n"
"Lorem ipsum dolor sit amet... | [
"grr_response_core.lib.rdfvalue.RDFDatetime.FromMicrosecondsSinceEpoch",
"unittest.skipIf",
"grr_response_core.lib.rdfvalue.Duration.From",
"grr_response_core.lib.rdfvalue.RDFDatetimeSeconds.FromDatetime",
"datetime.datetime",
"grr_response_core.lib.rdfvalue.RDFInteger.FromHumanReadable",
"absl.app.run"... | [((2607, 2767), 'unittest.skipIf', 'unittest.skipIf', (['(sys.maxunicode <= 65535)', '"""Your Python installation does not properly support Unicode (likely: Python with no UCS4 support on Windows."""'], {}), "(sys.maxunicode <= 65535,\n 'Your Python installation does not properly support Unicode (likely: Python with... |
#!/usr/bin/python
# coding=UTF-8
# ex:ts=4:sw=4:et=on
# Copyright (c) 2013, <NAME>
# All rights reserved.
# Complete license can be found in the LICENSE file.
import os
from pyxrd.data import settings
from pyxrd.project.models import Project
from pyxrd.phases.models import Component, Phase
def generate_expandables(... | [
"pyxrd.project.models.Project",
"os.path.exists",
"pyxrd.phases.models.Phase.save_phases",
"pyxrd.phases.models.Phase",
"threading.Event",
"os.path.dirname",
"os.mkdir",
"threading.Thread",
"queue.Queue",
"pyxrd.data.settings.DATA_REG.get_directory_path"
] | [((22450, 22463), 'queue.Queue', 'queue.Queue', ([], {}), '()\n', (22461, 22463), False, 'import queue\n'), ((22478, 22495), 'threading.Event', 'threading.Event', ([], {}), '()\n', (22493, 22495), False, 'import threading\n'), ((22511, 22572), 'threading.Thread', 'threading.Thread', ([], {'target': 'ioworker', 'args': ... |
"""
Some persistent maps (gdbm) require special encoding of keys
and/or values. This is an abstraction for these kinds of quirks.
"""
from itertools import imap
import collections
import gdbm as dbm
import json
from sqlitedict import SqliteDict
import os
class EncodedDict(collections.MutableMapping):
"""
Sub... | [
"os.path.exists",
"gdbm.open",
"sqlitedict.SqliteDict"
] | [((2463, 2483), 'sqlitedict.SqliteDict', 'SqliteDict', (['filename'], {}), '(filename)\n', (2473, 2483), False, 'from sqlitedict import SqliteDict\n'), ((1926, 1950), 'os.path.exists', 'os.path.exists', (['filename'], {}), '(filename)\n', (1940, 1950), False, 'import os\n'), ((2009, 2033), 'gdbm.open', 'dbm.open', (['f... |
from PySide6.QtGui import QColor
from PySide6.QtWidgets import QFrame, QHBoxLayout, QWidget
from PySide6.QtCore import Qt, QSettings, QEvent
from utils import colors
import pyqtgraph as pg
import numpy as np
class ScrollablePlotWidget(pg.PlotWidget):
"""
Subclass of `pg.PlotWidget` that overrides `wheelEven... | [
"PySide6.QtWidgets.QHBoxLayout",
"PySide6.QtCore.QSettings",
"pyqtgraph.mkPen",
"pyqtgraph.ImageView",
"PySide6.QtGui.QColor"
] | [((1875, 1886), 'PySide6.QtCore.QSettings', 'QSettings', ([], {}), '()\n', (1884, 1886), False, 'from PySide6.QtCore import Qt, QSettings, QEvent\n'), ((2240, 2260), 'pyqtgraph.ImageView', 'pg.ImageView', (['parent'], {}), '(parent)\n', (2252, 2260), True, 'import pyqtgraph as pg\n'), ((3351, 3387), 'pyqtgraph.mkPen', ... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from collections import OrderedDict
from torch import nn
from maskrcnn_benchmark.modeling import registry
from maskrcnn_benchmark.modeling.make_layers import conv_with_kaiming_uniform
from . import fpn as fpn_module
from . import res2net
@regis... | [
"collections.OrderedDict",
"maskrcnn_benchmark.modeling.registry.BACKBONES.register",
"maskrcnn_benchmark.modeling.make_layers.conv_with_kaiming_uniform"
] | [((315, 354), 'maskrcnn_benchmark.modeling.registry.BACKBONES.register', 'registry.BACKBONES.register', (['"""R2-50-C4"""'], {}), "('R2-50-C4')\n", (342, 354), False, 'from maskrcnn_benchmark.modeling import registry\n'), ((356, 395), 'maskrcnn_benchmark.modeling.registry.BACKBONES.register', 'registry.BACKBONES.regist... |
"""Memory watchdog: periodically read the memory usage of the main test process
and print it out, until terminated."""
import os
import sys
import time
try:
page_size = os.sysconf('SC_PAGESIZE')
except (ValueError, AttributeError):
try:
page_size = os.sysconf('SC_PAGE_SIZE')
except (ValueError, Attr... | [
"time.sleep",
"sys.stdin.read",
"os.sysconf",
"sys.stdout.flush",
"sys.stdin.seek"
] | [((173, 198), 'os.sysconf', 'os.sysconf', (['"""SC_PAGESIZE"""'], {}), "('SC_PAGESIZE')\n", (183, 198), False, 'import os\n'), ((374, 391), 'sys.stdin.seek', 'sys.stdin.seek', (['(0)'], {}), '(0)\n', (388, 391), False, 'import sys\n'), ((404, 420), 'sys.stdin.read', 'sys.stdin.read', ([], {}), '()\n', (418, 420), False... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... | [
"pulumi.getter",
"pulumi.set",
"pulumi.ResourceOptions",
"pulumi.get"
] | [((4837, 4873), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""accessControls"""'}), "(name='accessControls')\n", (4850, 4873), False, 'import pulumi\n'), ((5784, 5815), 'pulumi.getter', 'pulumi.getter', ([], {'name': '"""clusterId"""'}), "(name='clusterId')\n", (5797, 5815), False, 'import pulumi\n'), ((6114, 615... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: <NAME>
"""
import sys
sys.path.insert(0, '../PGP/')
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from parametric_GP import PGP
if __name__ == "__main__":
# Import the data
data = pd.read_pickle('airline.pickle')
... | [
"pandas.read_pickle",
"sys.path.insert",
"matplotlib.pyplot.savefig",
"parametric_GP.PGP",
"numpy.floor",
"numpy.exp",
"matplotlib.pyplot.rcParams.update",
"numpy.random.seed",
"numpy.mod",
"matplotlib.pyplot.subplots",
"numpy.random.permutation"
] | [((83, 112), 'sys.path.insert', 'sys.path.insert', (['(0)', '"""../PGP/"""'], {}), "(0, '../PGP/')\n", (98, 112), False, 'import sys\n'), ((285, 317), 'pandas.read_pickle', 'pd.read_pickle', (['"""airline.pickle"""'], {}), "('airline.pickle')\n", (299, 317), True, 'import pandas as pd\n'), ((749, 766), 'numpy.random.se... |
#!/usr/bin/env python3
# Copyright 2018 Brocade Communications Systems LLC. 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 also obtain a copy of the License at
# http://www.apache.org/licenses/LICENS... | [
"pyfos.pyfos_brocade_security.security_certificate",
"pyfos.pyfos_auth.logout",
"pyfos.utils.brcd_util.getsession",
"pyfos.utils.brcd_util.parse",
"pyfos.pyfos_util.response_print"
] | [((2800, 2822), 'pyfos.pyfos_brocade_security.security_certificate', 'security_certificate', ([], {}), '()\n', (2820, 2822), False, 'from pyfos.pyfos_brocade_security import security_certificate\n'), ((3140, 3192), 'pyfos.utils.brcd_util.parse', 'brcd_util.parse', (['argv', 'security_certificate', 'filters'], {}), '(ar... |
from flask import Flask, render_template, session, redirect, url_for, request, flash, abort, current_app, make_response
from flask_login import login_user, logout_user, login_required, current_user
from . import admin
from .. import db
from ..models import User, Post
from ..form import PostForm
from functools import wr... | [
"flask.render_template",
"flask.flash",
"flask.url_for"
] | [((834, 889), 'flask.render_template', 'render_template', (['"""admin.html"""'], {'title': '"""Admin"""', 'form': 'form'}), "('admin.html', title='Admin', form=form)\n", (849, 889), False, 'from flask import Flask, render_template, session, redirect, url_for, request, flash, abort, current_app, make_response\n'), ((784... |
"""!
@brief Neural Network: Self-Organized Feature Map
@details Implementation based on paper @cite article::nnet::som::1, @cite article::nnet::som::2.
@authors <NAME> (<EMAIL>)
@date 2014-2020
@copyright BSD-3-Clause
"""
import math
import random
import matplotlib.pyplot as plt
import pyclusterin... | [
"pyclustering.utils.dimension.dimension_info",
"matplotlib.pyplot.grid",
"math.floor",
"pyclustering.core.som_wrapper.som_get_neighbors",
"pyclustering.core.wrapper.ccore_library.workable",
"pyclustering.core.som_wrapper.som_train",
"pyclustering.core.som_wrapper.som_load",
"pyclustering.core.som_wrap... | [((13291, 13317), 'pyclustering.utils.dimension.dimension_info', 'dimension_info', (['self._data'], {}), '(self._data)\n', (13305, 13317), False, 'from pyclustering.utils.dimension import dimension_info\n'), ((13736, 13774), 'random.seed', 'random.seed', (['self._params.random_state'], {}), '(self._params.random_state)... |
import rospy
from styx_msgs.msg import TrafficLight
import numpy as np
from keras.models import Model
from keras import applications
from keras.models import load_model
from keras.preprocessing import image as img_preprocessing
import cv2
# load the trained model
from keras.utils.generic_utils import CustomObjectScop... | [
"keras.preprocessing.image.img_to_array",
"keras.models.load_model",
"rospy.logwarn",
"keras.utils.generic_utils.CustomObjectScope",
"numpy.expand_dims",
"cv2.resize",
"rospy.loginfo"
] | [((605, 652), 'rospy.loginfo', 'rospy.loginfo', (['"""TLClassifier: Loading model..."""'], {}), "('TLClassifier: Loading model...')\n", (618, 652), False, 'import rospy\n'), ((1010, 1061), 'rospy.loginfo', 'rospy.loginfo', (['"""TLClassifier: Model loaded - READY"""'], {}), "('TLClassifier: Model loaded - READY')\n", (... |
# -*- coding: utf-8 -*-
"""Cluster plotting tools"""
__author__ = ["<NAME>", "<NAME>"]
__all__ = ["plot_cluster_algorithm"]
import pandas as pd
from sktime.clustering.base._typing import NumpyOrDF
from sktime.clustering.base.base import BaseClusterer
from sktime.clustering.partitioning._lloyds_partitioning import (
... | [
"sktime.utils.validation._dependencies._check_soft_dependencies",
"sktime.datatypes._panel._convert.from_nested_to_2d_array",
"matplotlib.pyplot.figure",
"matplotlib.patches.Patch",
"matplotlib.pyplot.tight_layout",
"sktime.clustering.partitioning._lloyds_partitioning.TimeSeriesLloydsPartitioning.get_clus... | [((1045, 1083), 'sktime.utils.validation._dependencies._check_soft_dependencies', '_check_soft_dependencies', (['"""matplotlib"""'], {}), "('matplotlib')\n", (1069, 1083), False, 'from sktime.utils.validation._dependencies import _check_soft_dependencies\n'), ((1300, 1327), 'matplotlib.pyplot.figure', 'plt.figure', ([]... |
from django.test import TestCase
from transductor.forms import EnergyForm
from transductor.models import TransductorModel
class EnergyTransductorForm(TestCase):
def setUp(self):
t_model = TransductorModel()
t_model.name = "TR 4020"
t_model.transport_protocol = "UDP"
t_model.serial_... | [
"transductor.models.TransductorModel",
"transductor.forms.EnergyForm"
] | [((202, 220), 'transductor.models.TransductorModel', 'TransductorModel', ([], {}), '()\n', (218, 220), False, 'from transductor.models import TransductorModel\n'), ((734, 755), 'transductor.forms.EnergyForm', 'EnergyForm', ([], {'data': 'data'}), '(data=data)\n', (744, 755), False, 'from transductor.forms import Energy... |
from typing import Any, List, Optional
import hydra
import torch
import torchmetrics
from omegaconf import DictConfig
from pytorch_lightning import LightningModule
from ..optimizer.scheduler import create_scheduler
from ..utils import utils
from ..utils.misc import mixup_data
log = utils.get_logger(__name__)
class... | [
"hydra.utils.instantiate",
"torch.load"
] | [((636, 722), 'hydra.utils.instantiate', 'hydra.utils.instantiate', (['config.module'], {'num_classes': 'config.datamodule.num_classes'}), '(config.module, num_classes=config.datamodule.\n num_classes)\n', (659, 722), False, 'import hydra\n'), ((1276, 1312), 'hydra.utils.instantiate', 'hydra.utils.instantiate', (['c... |
from everett.component import RequiredConfigMixin, ConfigOptions
from everett.manager import ConfigManager, ConfigOSEnv
class BotConfig(RequiredConfigMixin):
required_config = ConfigOptions()
required_config.add_option('flask_loglevel', parser=str, default='info', doc='Set the log level for Flask.')
requi... | [
"everett.manager.ConfigOSEnv",
"everett.component.ConfigOptions"
] | [((182, 197), 'everett.component.ConfigOptions', 'ConfigOptions', ([], {}), '()\n', (195, 197), False, 'from everett.component import RequiredConfigMixin, ConfigOptions\n'), ((1616, 1629), 'everett.manager.ConfigOSEnv', 'ConfigOSEnv', ([], {}), '()\n', (1627, 1629), False, 'from everett.manager import ConfigManager, Co... |
try:
import MyTable
except NameError as e:
print(e)
import importlib
importlib.import_module('Constraints')
# 現在 locals() にある module に Constraints.py モジュールを加える。
# (MyTableにConstraintsを加える。`from Constraints import PK,UK,FK,NN,D,C`する)
# トレースバックで例外発生モジュールを補足
import sys, traceback
exc_t... | [
"sys.exc_info",
"importlib.import_module",
"traceback.extract_tb",
"pathlib.Path"
] | [((85, 123), 'importlib.import_module', 'importlib.import_module', (['"""Constraints"""'], {}), "('Constraints')\n", (108, 123), False, 'import importlib\n'), ((352, 366), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (364, 366), False, 'import sys, traceback\n'), ((400, 435), 'traceback.extract_tb', 'traceback.ext... |
import click, requests, sys
bootstrap_ip = '192.168.0.2'
bootstrap_port = '8000'
base_url = 'http://' + bootstrap_ip + ':' + bootstrap_port
@click.group()
def toychord():
"""CLI client for toy-chord."""
pass
@toychord.command()
@click.option('--key', required=True, type=str)
@click.option('--value', requir... | [
"requests.post",
"click.group",
"click.option",
"requests.get",
"click.echo"
] | [((144, 157), 'click.group', 'click.group', ([], {}), '()\n', (155, 157), False, 'import click, requests, sys\n'), ((242, 288), 'click.option', 'click.option', (['"""--key"""'], {'required': '(True)', 'type': 'str'}), "('--key', required=True, type=str)\n", (254, 288), False, 'import click, requests, sys\n'), ((290, 33... |
import networkx as nx
class _CentralityMetrics:
def __init__(self, G, metrics):
self.G = G
self.metrics = metrics
def _compute_metrics(self):
metrics = self.metrics
if metrics == 'degree_centrality':
c = self.degree_centrality()
elif... | [
"networkx.closeness_centrality",
"networkx.betweenness_centrality",
"networkx.eigenvector_centrality",
"networkx.degree_centrality"
] | [((699, 744), 'networkx.degree_centrality', 'nx.degree_centrality', (['self.G'], {'weight': '"""weight"""'}), "(self.G, weight='weight')\n", (719, 744), True, 'import networkx as nx\n'), ((839, 889), 'networkx.betweenness_centrality', 'nx.betweenness_centrality', (['self.G'], {'weight': '"""weight"""'}), "(self.G, weig... |
###############################################################################
# Copyright (C) 2016 <NAME>
# This is part of <NAME>'s PoDoCo project.
#
# This file is licensed under the MIT License.
###############################################################################
"""
Particle filters for tracking the in... | [
"numpy.random.normal",
"numpy.tile",
"numpy.repeat",
"numpy.sqrt",
"numpy.log",
"numpy.max",
"numpy.exp",
"scipy.special.gammaln",
"resampling.residual_resample"
] | [((755, 774), 'numpy.repeat', 'np.repeat', (['(1 / N)', 'N'], {}), '(1 / N, N)\n', (764, 774), True, 'import numpy as np\n'), ((1700, 1807), 'numpy.random.normal', 'np.random.normal', (["(params['base'][1, :] + params['A_x'] * (x - params['base'][0, :]))", "params['sqrtQ_x']"], {}), "(params['base'][1, :] + params['A_x... |
from inspect import cleandoc
from textwrap import indent
from lark import Lark, Transformer
from lark.exceptions import LarkError
from .interval import Interval
from . import errors
def parse(ctx, fname):
with open(fname, "r") as f:
t = f.read()
try:
l = Lark(open(ctx.implfile("s... | [
"inspect.cleandoc"
] | [((3644, 3664), 'inspect.cleandoc', 'cleandoc', (['t[0][3:-3]'], {}), '(t[0][3:-3])\n', (3652, 3664), False, 'from inspect import cleandoc\n')] |
from template import Template
from template.test import TestCase, main
class Stringy:
def __init__(self, text):
self.text = text
def asString(self):
return self.text
__str__ = asString
class TextTest(TestCase):
def testText(self):
tt = (("basic", Template()),
("interp", Template({ "I... | [
"template.Template"
] | [((273, 283), 'template.Template', 'Template', ([], {}), '()\n', (281, 283), False, 'from template import Template\n'), ((307, 335), 'template.Template', 'Template', (["{'INTERPOLATE': 1}"], {}), "({'INTERPOLATE': 1})\n", (315, 335), False, 'from template import Template\n')] |
# Copyright (c) 2021 <NAME>
import math
from pprint import pprint
import matplotlib.pyplot as plt
from frispy import Disc
from frispy import Discs
model = Discs.destroyer
mph_to_mps = 0.44704
v = 70 * mph_to_mps
rot = -v / model.diameter * 1.2
x0 = [6, -3, 25]
a, nose_up, hyzer = x0
disc = Disc(model, {"vx": math.c... | [
"matplotlib.pyplot.plot",
"math.cos",
"math.sin",
"pprint.pprint",
"matplotlib.pyplot.show"
] | [((606, 631), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'result.theta'], {}), '(x, result.theta)\n', (614, 631), True, 'import matplotlib.pyplot as plt\n'), ((632, 646), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {}), '(x, y)\n', (640, 646), True, 'import matplotlib.pyplot as plt\n'), ((647, 661), 'matplotli... |
#
# This file is part of LiteX.
#
# Copyright (c) 2018-2020 <NAME> <<EMAIL>>
# SPDX-License-Identifier: BSD-2-Clause
from migen import *
from migen.genlib.resetsync import AsyncResetSynchronizer
from litex.build.io import DifferentialInput
from litex.soc.interconnect.csr import *
from litex.soc.cores.clock.common i... | [
"migen.genlib.resetsync.AsyncResetSynchronizer",
"litex.build.io.DifferentialInput"
] | [((1616, 1656), 'migen.genlib.resetsync.AsyncResetSynchronizer', 'AsyncResetSynchronizer', (['cd', '(~self.locked)'], {}), '(cd, ~self.locked)\n', (1638, 1656), False, 'from migen.genlib.resetsync import AsyncResetSynchronizer\n'), ((1146, 1193), 'litex.build.io.DifferentialInput', 'DifferentialInput', (['clkin.p', 'cl... |
__all__ = (
'des_encrypt',
'des_decrypt',
)
from typing import List, Any
from ._tools import *
from ._constant import *
from rich import print
from rich.text import Text
from rich.panel import Panel
def keygen(key: bytes) -> List[List[int]]:
res = []
key = bytes_to_binlist(key)
key = permute_wit... | [
"rich.print",
"rich.text.Text"
] | [((1332, 1341), 'rich.print', 'print', (['""""""'], {}), "('')\n", (1337, 1341), False, 'from rich import print\n'), ((2603, 2612), 'rich.print', 'print', (['""""""'], {}), "('')\n", (2608, 2612), False, 'from rich import print\n'), ((2766, 2815), 'rich.print', 'print', (['"""[white]Finally we got our ciphertext:[/]"""... |
from time import time
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))
from singly_linkedlist.singly_linkedlist import SinglyLinkedList
start = time()
linked_list = SinglyLinkedList()
for i in range(100000):
linked_list.insert_head(111111111111)
end = time()
print("Took {0} sec... | [
"singly_linkedlist.singly_linkedlist.SinglyLinkedList",
"os.path.dirname",
"time.time"
] | [((182, 188), 'time.time', 'time', ([], {}), '()\n', (186, 188), False, 'from time import time\n'), ((203, 221), 'singly_linkedlist.singly_linkedlist.SinglyLinkedList', 'SinglyLinkedList', ([], {}), '()\n', (219, 221), False, 'from singly_linkedlist.singly_linkedlist import SinglyLinkedList\n'), ((294, 300), 'time.time... |
import pytest
from ..iocsh import IocshRedirect, IocshSplit, split_words
@pytest.mark.parametrize(
"line, expected",
[
pytest.param(
"""dbLoadRecords(a, "b", "c")""",
["dbLoadRecords", "a", "b", "c"],
id="basic_paren"
),
pytest.param(
"... | [
"pytest.param"
] | [((138, 238), 'pytest.param', 'pytest.param', (['"""dbLoadRecords(a, "b", "c")"""', "['dbLoadRecords', 'a', 'b', 'c']"], {'id': '"""basic_paren"""'}), '(\'dbLoadRecords(a, "b", "c")\', [\'dbLoadRecords\', \'a\', \'b\', \'c\'\n ], id=\'basic_paren\')\n', (150, 238), False, 'import pytest\n'), ((293, 394), 'pytest.p... |
import os
import numpy as np
import pandas as pd
from Base import Train, Predict
def getTest(boolNormalize, boolDeep, boolBias, strProjectFolder):
if boolNormalize:
if boolDeep:
strOutputPath = "02-Output/" + "Deep" + "Normal"
else:
if boolBias:
strOutputPa... | [
"numpy.mean",
"os.path.join",
"Base.Predict.makePredict",
"os.path.dirname",
"Base.Train.getTrain",
"numpy.std",
"pandas.DataFrame"
] | [((1585, 1968), 'Base.Train.getTrain', 'Train.getTrain', ([], {'arrayTrainUser': 'arrayUsers', 'arrayTrainMovie': 'arrayMovies', 'arrayTrainRate': 'arrayRate', 'arrayValidUser': 'arrayUsers', 'arrayValidMovie': 'arrayMovies', 'arrayValidRate': 'arrayRate', 'intUserSize': 'intUserSize', 'intMovieSize': 'intMovieSize', '... |
import re
import subprocess
import shutil
import sys
import json
import argparse
from typing import List, NamedTuple, Optional, Sequence
PATTERN_IMPORT_TIME = re.compile(r"^import time:\s+(\d+) \|\s+(\d+) \|(\s+.*)")
class InvalidInput(Exception):
pass
class Import(dict):
def __init__(self, name: str, t_s... | [
"argparse.ArgumentParser",
"re.compile",
"subprocess.run",
"json.dumps",
"shutil.get_terminal_size",
"typing.NamedTuple"
] | [((161, 224), 're.compile', 're.compile', (['"""^import time:\\\\s+(\\\\d+) \\\\|\\\\s+(\\\\d+) \\\\|(\\\\s+.*)"""'], {}), "('^import time:\\\\s+(\\\\d+) \\\\|\\\\s+(\\\\d+) \\\\|(\\\\s+.*)')\n", (171, 224), False, 'import re\n'), ((3396, 3430), 'json.dumps', 'json.dumps', (['exclude_root'], {'indent': '(2)'}), '(exclu... |
import csv
import collections
import pandas as pd
from random import shuffle
from tqdm import tqdm
def get_all_tokens_conll(conll_file):
"""
Reads a CoNLL-2011 file and returns all tokens with their annotations in a dataframe including the original
sentence identifiers from OntoNotes
"""
all_toke... | [
"pandas.DataFrame",
"random.shuffle"
] | [((2379, 2417), 'pandas.DataFrame', 'pd.DataFrame', (['all_tokens'], {'columns': 'cols'}), '(all_tokens, columns=cols)\n', (2391, 2417), True, 'import pandas as pd\n'), ((5165, 5205), 'pandas.DataFrame', 'pd.DataFrame', (['instances'], {'columns': 'columns'}), '(instances, columns=columns)\n', (5177, 5205), True, 'impo... |
from setuptools import find_packages, setup
import re
VERSIONFILE = "{{ cookiecutter.project_name }}/__init__.py"
with open(VERSIONFILE, "rt") as versionfle:
verstrline = versionfle.read()
version_re = r"^__version__ = ['\"]([^'\"]*)['\"]"
mo = re.search(version_re, verstrline, re.M)
if mo:
ver_str = mo.group(... | [
"setuptools.find_packages",
"re.search"
] | [((250, 289), 're.search', 're.search', (['version_re', 'verstrline', 're.M'], {}), '(version_re, verstrline, re.M)\n', (259, 289), False, 'import re\n'), ((630, 645), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (643, 645), False, 'from setuptools import find_packages, setup\n')] |
import os
from setuptools import setup
try:
import concurrent.futures
except ImportError:
CONCURRENT_FUTURES_PRESENT = False
else:
CONCURRENT_FUTURES_PRESENT = True
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="threadedprocess",
version="0.... | [
"os.path.dirname"
] | [((226, 251), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (241, 251), False, 'import os\n')] |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
import numpy as np
from coremltools.converters.mil.mil import Builder as mb... | [
"coremltools.converters.mil.mil.passes.pass_registry.register_pass"
] | [((1907, 1940), 'coremltools.converters.mil.mil.passes.pass_registry.register_pass', 'register_pass', ([], {'namespace': '"""common"""'}), "(namespace='common')\n", (1920, 1940), False, 'from coremltools.converters.mil.mil.passes.pass_registry import register_pass\n')] |
from simcse import SimCSE
from esimcse import ESimCSE
from promptbert import PromptBERT
from sbert import SBERT
from cosent import CoSent
from config import Params
from log import logger
import torch
from transformers import AutoTokenizer
class SimCSERetrieval(object):
def __init__(self, pretrained_model_path, si... | [
"promptbert.PromptBERT",
"torch.load",
"torch.cosine_similarity",
"simcse.SimCSE",
"log.logger.info",
"esimcse.ESimCSE",
"sbert.SBERT",
"cosent.CoSent",
"transformers.AutoTokenizer.from_pretrained"
] | [((11630, 11677), 'log.logger.info', 'logger.info', (['"""start simcse model succussfully!"""'], {}), "('start simcse model succussfully!')\n", (11641, 11677), False, 'from log import logger\n'), ((11807, 11862), 'log.logger.info', 'logger.info', (['"""start esimcse repeat model succussfully!"""'], {}), "('start esimcs... |
from collections import OrderedDict
import pandas as pd
from bokeh.charts import Horizon, output_file, show
# read in some stock data from the Yahoo Finance API
AAPL = pd.read_csv(
"http://ichart.yahoo.com/table.csv?s=AAPL&a=0&b=1&c=2000&d=0&e=1&f=2010",
parse_dates=['Date'])
MSFT = pd.read_csv(
"http://... | [
"collections.OrderedDict",
"pandas.read_csv",
"bokeh.charts.output_file",
"bokeh.charts.Horizon",
"bokeh.charts.show"
] | [((171, 287), 'pandas.read_csv', 'pd.read_csv', (['"""http://ichart.yahoo.com/table.csv?s=AAPL&a=0&b=1&c=2000&d=0&e=1&f=2010"""'], {'parse_dates': "['Date']"}), "(\n 'http://ichart.yahoo.com/table.csv?s=AAPL&a=0&b=1&c=2000&d=0&e=1&f=2010',\n parse_dates=['Date'])\n", (182, 287), True, 'import pandas as pd\n'), ((... |
# from __future__ import print_function
import pymzn
import time
from pprint import pprint
from collections import OrderedDict
import openrouteservice
from openrouteservice.geocode import pelias_search
from openrouteservice.distance_matrix import distance_matrix
client = openrouteservice.Client(key='')
# routes = cli... | [
"collections.OrderedDict",
"openrouteservice.geocode.pelias_search",
"pymzn.minizinc",
"openrouteservice.Client",
"openrouteservice.distance_matrix.distance_matrix",
"pprint.pprint"
] | [((274, 305), 'openrouteservice.Client', 'openrouteservice.Client', ([], {'key': '""""""'}), "(key='')\n", (297, 305), False, 'import openrouteservice\n'), ((395, 433), 'openrouteservice.geocode.pelias_search', 'pelias_search', (['client', 'address'], {'size': '(1)'}), '(client, address, size=1)\n', (408, 433), False, ... |
import random
import requests
import time
HOSTS = [
'us-east-1',
'us-west-1',
'eu-west-1',
]
VEHICLES = [
'bike',
'scooter',
'car',
]
if __name__ == "__main__":
print(f"starting load generator")
time.sleep(15)
print('done sleeping')
while True:
host = HOSTS[random.rand... | [
"requests.get",
"random.uniform",
"time.sleep"
] | [((230, 244), 'time.sleep', 'time.sleep', (['(15)'], {}), '(15)\n', (240, 244), False, 'import time\n'), ((475, 517), 'requests.get', 'requests.get', (['f"""http://web:8000/{vehicle}"""'], {}), "(f'http://web:8000/{vehicle}')\n", (487, 517), False, 'import requests\n'), ((571, 595), 'random.uniform', 'random.uniform', ... |
from django.contrib import admin
from . import models
class ReadOnlyAdminMixin():
def get_readonly_fields(self, request, obj=None):
return list(set(
[field.name for field in self.opts.local_fields] +
[field.name for field in self.opts.local_many_to_many]
))
class ReadOnl... | [
"django.contrib.admin.site.register"
] | [((1086, 1149), 'django.contrib.admin.site.register', 'admin.site.register', (['models.DerivationCode', 'DerivationCodeAdmin'], {}), '(models.DerivationCode, DerivationCodeAdmin)\n', (1105, 1149), False, 'from django.contrib import admin\n'), ((1150, 1215), 'django.contrib.admin.site.register', 'admin.site.register', (... |
from decimal import Decimal
def Binominal(n: int, k: int) -> int:
if k > n:
return 0
result = 1
if k > n - k:
k = n - k
i = 1
while i <= k:
result *= n
result //= i
n -= 1
i += 1
return result
def pvalue(a: int, b: int,
c: int, d: in... | [
"decimal.Decimal"
] | [((1577, 1587), 'decimal.Decimal', 'Decimal', (['(1)'], {}), '(1)\n', (1584, 1587), False, 'from decimal import Decimal\n')] |
# Copyright 2019 NEC Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | [
"logging.getLogger",
"json.loads",
"requests.post",
"django.views.decorators.http.require_http_methods",
"django.http.response.JsonResponse"
] | [((1318, 1345), 'logging.getLogger', 'logging.getLogger', (['"""apilog"""'], {}), "('apilog')\n", (1335, 1345), False, 'import logging\n'), ((1348, 1377), 'django.views.decorators.http.require_http_methods', 'require_http_methods', (["['GET']"], {}), "(['GET'])\n", (1368, 1377), False, 'from django.views.decorators.htt... |
import unittest
import pygame
from chip8_pygame_integration.config import get_config, KeyBind, to_text
DEFAULT = [KeyBind(pygame.K_o, pygame.KMOD_CTRL, 'some_command')]
class ConfigLoadTest(unittest.TestCase):
def setUp(self):
self.default = None
def test_empty_pattern_returns_empty_array(self):
... | [
"unittest.main",
"chip8_pygame_integration.config.KeyBind",
"chip8_pygame_integration.config.get_config",
"chip8_pygame_integration.config.to_text"
] | [((116, 169), 'chip8_pygame_integration.config.KeyBind', 'KeyBind', (['pygame.K_o', 'pygame.KMOD_CTRL', '"""some_command"""'], {}), "(pygame.K_o, pygame.KMOD_CTRL, 'some_command')\n", (123, 169), False, 'from chip8_pygame_integration.config import get_config, KeyBind, to_text\n'), ((5970, 5985), 'unittest.main', 'unitt... |
'''
Preorder Binary Tree
For a given Binary Tree of integers, print the pre-order traversal.
Input Format:
The first and the only line of input will contain the nodes data, all separated by a single space. Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of t... | [
"sys.stdin.readline",
"sys.setrecursionlimit",
"queue.Queue"
] | [((766, 792), 'sys.setrecursionlimit', 'setrecursionlimit', (['(10 ** 6)'], {}), '(10 ** 6)\n', (783, 792), False, 'from sys import stdin, setrecursionlimit\n'), ((1377, 1390), 'queue.Queue', 'queue.Queue', ([], {}), '()\n', (1388, 1390), False, 'import queue\n'), ((1225, 1241), 'sys.stdin.readline', 'stdin.readline', ... |
#!/usr/bin/env python3
"""
This script has been tested on various custom google forms and other various forms with
few alteratios ..
Google forms which does include the input type "token" attribute are found
to be safer than those who don't.
Any form contains various fields.
1. input text fields
2. radio
3. checkb... | [
"bs4.BeautifulSoup",
"requests.session",
"requests.post",
"urllib.request.urlopen"
] | [((534, 546), 'urllib.request.urlopen', 'urlopen', (['url'], {}), '(url)\n', (541, 546), False, 'from urllib.request import urlopen\n'), ((557, 591), 'bs4.BeautifulSoup', 'BeautifulSoup', (['page', '"""html.parser"""'], {}), "(page, 'html.parser')\n", (570, 591), False, 'from bs4 import BeautifulSoup\n'), ((665, 683), ... |
import dataset
import logging
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from .config import TOKEN, DB_URI
from .commands import HANDLERS
logging.basicConfig()
def save_message(message, db):
replied = None
if message.reply_to_message is not None:
replied = message.rep... | [
"logging.basicConfig",
"telegram.ext.MessageHandler",
"telegram.ext.CommandHandler",
"telegram.ext.Updater",
"dataset.connect"
] | [((172, 193), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (191, 193), False, 'import logging\n'), ((1360, 1383), 'dataset.connect', 'dataset.connect', (['DB_URI'], {}), '(DB_URI)\n', (1375, 1383), False, 'import dataset\n'), ((1503, 1526), 'dataset.connect', 'dataset.connect', (['DB_URI'], {}), '(DB... |
from pymp3decoder import Decoder
import contextlib
import os
import math
import pyaudio
CHUNK_SIZE = 4096
def take_chunk(content):
""" Split a buffer of data into chunks """
num_blocks = int(math.ceil(1.0*len(content)/CHUNK_SIZE))
for start in range(num_blocks):
yield content[CHUNK_SIZE*start:... | [
"os.path.abspath",
"pymp3decoder.Decoder",
"pyaudio.PyAudio"
] | [((443, 460), 'pyaudio.PyAudio', 'pyaudio.PyAudio', ([], {}), '()\n', (458, 460), False, 'import pyaudio\n'), ((489, 513), 'pymp3decoder.Decoder', 'Decoder', (['(CHUNK_SIZE * 20)'], {}), '(CHUNK_SIZE * 20)\n', (496, 513), False, 'from pymp3decoder import Decoder\n'), ((984, 1009), 'os.path.abspath', 'os.path.abspath', ... |
import telegram.ext
import messsages as msg
import functions as f
import matplotlib.pyplot as plt
import traceback
import os
import os.path
from os import path
def start(update, context):
nombre = update.message.chat.first_name
mensaje = "Bienvenido {}, para conocer lo que puedo hacer utiliza el comando /Help... | [
"os.remove",
"functions.starsAndContellations",
"functions.searchFile",
"functions.stars"
] | [((625, 634), 'functions.stars', 'f.stars', ([], {}), '()\n', (632, 634), True, 'import functions as f\n'), ((765, 795), 'os.remove', 'os.remove', (['"""./files/stars.png"""'], {}), "('./files/stars.png')\n", (774, 795), False, 'import os\n'), ((1655, 1680), 'functions.starsAndContellations', 'f.starsAndContellations',... |
# -*- coding: UTF-8 -*-
import numpy as np
import pandas as pd
def countnum():
dates = pd.date_range(start="2019-01-01", end="2019-05-31", freq='M')
# print(dates)
# print(dates[0])
# print(type(dates[0]))
col1 = [i for i in range(1, len(dates) + 1)]
# print(col1)
col2 = [i + 1 for i in ra... | [
"pandas.DataFrame",
"pandas.date_range"
] | [((93, 154), 'pandas.date_range', 'pd.date_range', ([], {'start': '"""2019-01-01"""', 'end': '"""2019-05-31"""', 'freq': '"""M"""'}), "(start='2019-01-01', end='2019-05-31', freq='M')\n", (106, 154), True, 'import pandas as pd\n'), ((354, 409), 'pandas.DataFrame', 'pd.DataFrame', (["{'col1': col1, 'col2': col2}"], {'in... |
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import base64
import os
import zlib
from .environment import get_environment
from . import util
def iter_results_paths... | [
"os.path.join",
"base64.b64decode",
"zlib.compress",
"os.walk",
"os.remove"
] | [((495, 511), 'os.walk', 'os.walk', (['results'], {}), '(results)\n', (502, 511), False, 'import os\n'), ((2241, 2268), 'os.path.join', 'os.path.join', (['root', 'machine'], {}), '(root, machine)\n', (2253, 2268), False, 'import os\n'), ((1020, 1055), 'os.path.join', 'os.path.join', (['results', 'machine_name'], {}), '... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from typing import Tuple
def clean_df_headers(df: pd.DataFrame) -> pd.DataFrame:
"""Remove leading and trailing spaces in DataFrame headers."""
headers = pd.Series(df.columns)
new_headers = [header.strip() for header in headers]
... | [
"pandas.Series",
"pandas.read_csv",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show"
] | [((236, 257), 'pandas.Series', 'pd.Series', (['df.columns'], {}), '(df.columns)\n', (245, 257), True, 'import pandas as pd\n'), ((334, 356), 'pandas.Series', 'pd.Series', (['new_headers'], {}), '(new_headers)\n', (343, 356), True, 'import pandas as pd\n'), ((1233, 1288), 'pandas.read_csv', 'pd.read_csv', (['"""step_03_... |
import os
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from common.tflogs2pandas import tflog2pandas, many_logs2pandas
from common.gym_interface import template
bodies = [300]
all_seeds = list(range(20))
all_stackframe = [0,4]
cache_filename = "output_data/tmp/plot0"
try:
df = pd.rea... | [
"pandas.read_pickle",
"os.path.exists",
"matplotlib.pyplot.savefig",
"common.tflogs2pandas.tflog2pandas",
"matplotlib.pyplot.tight_layout",
"pandas.DataFrame",
"seaborn.barplot",
"pandas.concat",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.legend"
] | [((1337, 1369), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'df.columns'}), '(columns=df.columns)\n', (1349, 1369), True, 'import pandas as pd\n'), ((2448, 2509), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(1)', 'ncols': '(1)', 'sharey': '(True)', 'figsize': '[10, 10]'}), '(nrows=1, ncols=1,... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import torch
from archai.nas.model import Model
from archai.nas.macro_builder import MacroBuilder
from archai.common.common import common_init
def test_darts_zero_model():
conf = common_init(config_filepath='confs/algos/darts.yaml')... | [
"archai.common.common.common_init",
"archai.nas.model.Model",
"torch.rand",
"archai.nas.macro_builder.MacroBuilder"
] | [((267, 320), 'archai.common.common.common_init', 'common_init', ([], {'config_filepath': '"""confs/algos/darts.yaml"""'}), "(config_filepath='confs/algos/darts.yaml')\n", (278, 320), False, 'from archai.common.common import common_init\n'), ((429, 453), 'archai.nas.macro_builder.MacroBuilder', 'MacroBuilder', (['model... |
import logging
import datetime
class DatasetReports(object):
def __init__(self, dataverse_api=None, dataverse_database=None, config=None):
if dataverse_api is None:
print('Dataverse API required to create dataset reports.')
return
if dataverse_database is None:
p... | [
"logging.getLogger",
"datetime.datetime.now",
"datetime.timedelta"
] | [((847, 885), 'logging.getLogger', 'logging.getLogger', (['"""dataverse-reports"""'], {}), "('dataverse-reports')\n", (864, 885), False, 'import logging\n'), ((13290, 13313), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (13311, 13313), False, 'import datetime\n'), ((13361, 13387), 'datetime.timed... |
import json
import aiohttp
from copy import deepcopy
class Resource(object):
"""
A base class for API resources
"""
# """List of allowed methods, allowed values are
# ```['GET', 'PUT', 'POST', 'DELETE']``"""
# ALLOWED_METHODS = []
def __init__(self, url, auth):
"""
:param... | [
"aiohttp.ClientSession",
"aiohttp.BasicAuth",
"json.dumps",
"copy.deepcopy"
] | [((1423, 1445), 'copy.deepcopy', 'deepcopy', (['self.headers'], {}), '(self.headers)\n', (1431, 1445), False, 'from copy import deepcopy\n'), ((2174, 2196), 'copy.deepcopy', 'deepcopy', (['self.headers'], {}), '(self.headers)\n', (2182, 2196), False, 'from copy import deepcopy\n'), ((3007, 3029), 'copy.deepcopy', 'deep... |
from link_extractor import run_enumeration
from colorama import Fore
from utils.headers import HEADERS
from time import sleep
import requests
import database
import re
import json
from bs4 import BeautifulSoup
import colorama
print(Fore.GREEN + '-----------------------------------' + Fore.RESET, Fore.RED)
print('尸闩㇄尸㠪... | [
"link_extractor.run_enumeration",
"time.sleep"
] | [((465, 473), 'time.sleep', 'sleep', (['(1)'], {}), '(1)\n', (470, 473), False, 'from time import sleep\n'), ((585, 595), 'time.sleep', 'sleep', (['(0.5)'], {}), '(0.5)\n', (590, 595), False, 'from time import sleep\n'), ((684, 724), 'link_extractor.run_enumeration', 'run_enumeration', (["('http://' + target_host)"], {... |
from setuptools import setup
from pathlib import Path
from lightkube.models import __version__
setup(
name='lightkube-models',
version=__version__,
description='Models and Resources for lightkube module',
long_description=Path("README.md").read_text(),
long_description_content_type="text/markdown... | [
"pathlib.Path"
] | [((241, 258), 'pathlib.Path', 'Path', (['"""README.md"""'], {}), "('README.md')\n", (245, 258), False, 'from pathlib import Path\n')] |
# Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB), and the INTEL Visual Computing Lab.
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
import datetime
import sys
from contextlib import contextmanage... | [
"shutil.get_terminal_size",
"datetime.datetime.now",
"sys.stdout.flush",
"sys.stdout.write"
] | [((734, 757), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (755, 757), False, 'import datetime\n'), ((822, 845), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (843, 845), False, 'import datetime\n'), ((1248, 1297), 'sys.stdout.write', 'sys.stdout.write', (["('\\r' + text + e... |
from cms.extensions import PageExtension
from cms.extensions.extension_pool import extension_pool
from django.utils.translation import ugettext as _
from filer.fields.image import FilerImageField
class SimplePageExtension(PageExtension):
"""
A generic website page.
"""
image = FilerImageField(verbose_... | [
"django.utils.translation.ugettext",
"cms.extensions.extension_pool.extension_pool.register"
] | [((339, 383), 'cms.extensions.extension_pool.extension_pool.register', 'extension_pool.register', (['SimplePageExtension'], {}), '(SimplePageExtension)\n', (362, 383), False, 'from cms.extensions.extension_pool import extension_pool\n'), ((325, 335), 'django.utils.translation.ugettext', '_', (['"""image"""'], {}), "('i... |
import re
from . import tables
from .instr import Instruction
from .instr.nop import *
from .instr.alu import *
from .instr.bcd import *
from .instr.bit import *
from .instr.flag import *
from .instr.mov import *
from .instr.smov import *
from .instr.ld_st import *
from .instr.stack import *
from .instr.jmp import *
f... | [
"re.sub",
"re.match",
"re.search"
] | [((8856, 8887), 're.match', 're.match', (['"""^[a-z]+$"""', 'parts[-1]'], {}), "('^[a-z]+$', parts[-1])\n", (8864, 8887), False, 'import re\n'), ((7048, 7074), 're.sub', 're.sub', (['"""[A-Z]"""', '"""0"""', 'part'], {}), "('[A-Z]', '0', part)\n", (7054, 7074), False, 'import re\n'), ((7111, 7146), 're.sub', 're.sub', ... |
from abc import ABCMeta, abstractmethod
import numpy as np
__all__ = ['Law', 'Bin', 'Poi', 'Gau']
class Law(metaclass=ABCMeta):
@staticmethod
@abstractmethod
def sample(n, d):
pass
@staticmethod
@abstractmethod
def loglikely(n, d, k):
pass
@staticmethod
def likeli... | [
"numpy.random.poisson",
"numpy.log",
"numpy.random.randn",
"numpy.random.binomial"
] | [((432, 456), 'numpy.random.binomial', 'np.random.binomial', (['n', 'd'], {}), '(n, d)\n', (450, 456), True, 'import numpy as np\n'), ((592, 616), 'numpy.random.poisson', 'np.random.poisson', (['(n * d)'], {}), '(n * d)\n', (609, 616), True, 'import numpy as np\n'), ((507, 516), 'numpy.log', 'np.log', (['d'], {}), '(d)... |
from unittest import TestCase
from schemer import Schema, Array, ValidationException
from dusty.schemas.base_schema_class import DustySchema, DustySpecs
from ...testcases import DustyTestCase
class TestDustySchemaClass(TestCase):
def setUp(self):
self.base_schema = Schema({'street': {'type': basestring},... | [
"schemer.Schema",
"dusty.schemas.base_schema_class.DustySchema",
"dusty.schemas.base_schema_class.DustySpecs"
] | [((281, 370), 'schemer.Schema', 'Schema', (["{'street': {'type': basestring}, 'house_number': {'type': int, 'default': 1}}"], {}), "({'street': {'type': basestring}, 'house_number': {'type': int,\n 'default': 1}})\n", (287, 370), False, 'from schemer import Schema, Array, ValidationException\n'), ((431, 612), 'schem... |
from abc import ABCMeta, abstractmethod, abstractproperty
from datetime import datetime, date
class Item(metaclass=ABCMeta):
def __init__(self, code, name, quantity, cost, offer):
self.item_code=code
self.item_name=name
self.quantity_on_hand=quantity
self.cost_price=cost
sel... | [
"datetime.datetime.now",
"datetime.date"
] | [((4440, 4458), 'datetime.date', 'date', (['(2018)', '(12)', '(10)'], {}), '(2018, 12, 10)\n', (4444, 4458), False, 'from datetime import datetime, date\n'), ((4600, 4618), 'datetime.date', 'date', (['(2018)', '(11)', '(26)'], {}), '(2018, 11, 26)\n', (4604, 4618), False, 'from datetime import datetime, date\n'), ((194... |
#!/usr/bin/env python3
host = 'mongodb'
port = 27017
ssl_ca_cert='/run/secrets/rootCA.pem'
ssl_certfile='/run/secrets/tls_cert.pem'
ssl_keyfile='/run/secrets/tls_key.pem'
# don't turn these signal into exceptions, just die.
# necessary for integrating into bash script pipelines seamlessly.
import signal
signal.signal(... | [
"pymongo.MongoClient",
"signal.signal"
] | [((306, 350), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'signal.SIG_DFL'], {}), '(signal.SIGINT, signal.SIG_DFL)\n', (319, 350), False, 'import signal\n'), ((351, 396), 'signal.signal', 'signal.signal', (['signal.SIGPIPE', 'signal.SIG_DFL'], {}), '(signal.SIGPIPE, signal.SIG_DFL)\n', (364, 396), False, 'impo... |
"""
The weak_script annotation needs to be here instead of inside torch/jit/ so it
can be used in other places in torch/ (namely torch.nn) without running into
circular dependency problems
"""
import weakref
import inspect
try:
import builtins # PY3
except Exception:
import __builtin__ as builtins # PY2
# T... | [
"weakref.WeakKeyDictionary",
"inspect.currentframe"
] | [((380, 407), 'weakref.WeakKeyDictionary', 'weakref.WeakKeyDictionary', ([], {}), '()\n', (405, 407), False, 'import weakref\n'), ((493, 520), 'weakref.WeakKeyDictionary', 'weakref.WeakKeyDictionary', ([], {}), '()\n', (518, 520), False, 'import weakref\n'), ((612, 639), 'weakref.WeakKeyDictionary', 'weakref.WeakKeyDic... |
import re, requests
def parse_page(url):
headers = {
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36"
}
response = requests.get(url, headers=headers)
text = response.content.decode("utf-8")
contents = re.finda... | [
"re.sub",
"re.findall",
"requests.get"
] | [((218, 252), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (230, 252), False, 'import re, requests\n'), ((312, 385), 're.findall', 're.findall', (['"""<div class="content">.*?<span>(.*?)</span>"""', 'text', 're.DOTALL'], {}), '(\'<div class="content">.*?<span>(.*?)</spa... |
__all__ = ['plot_cum_error_dist']
import numpy as np
# import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from mpl_toolkits.axes_grid.inset_locator import inset_axes
import itertools
from . import palettes
# colors = itertools.cycle(npl.palettes.color_palette(palette="sweet",... | [
"matplotlib.pyplot.gca",
"numpy.ceil",
"mpl_toolkits.axes_grid.inset_locator.inset_axes",
"numpy.argwhere"
] | [((1188, 1197), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (1195, 1197), True, 'import matplotlib.pyplot as plt\n'), ((2724, 2797), 'mpl_toolkits.axes_grid.inset_locator.inset_axes', 'inset_axes', ([], {'parent_axes': 'ax', 'width': '"""60%"""', 'height': '"""50%"""', 'loc': '(4)', 'borderpad': '(2)'}), "(pa... |
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://localhost:8000')
try:
assert 'Django' in browser.title
finally:
browser.close()
| [
"selenium.webdriver.Firefox"
] | [((42, 61), 'selenium.webdriver.Firefox', 'webdriver.Firefox', ([], {}), '()\n', (59, 61), False, 'from selenium import webdriver\n')] |