code stringlengths 21 1.03M | apis list | extract_api stringlengths 74 8.23M |
|---|---|---|
import json
my_dict = {'Name' : 'Tushar' , 'skills' : ['Python' , 'shell' , 'yaml' , 'AWS']}
req_file = "myinfo.json"
fo = open(req_file , 'w')
json.dump(my_dict , fo , indent = 4)
fo.close() | [
"json.dump"
] | [((147, 179), 'json.dump', 'json.dump', (['my_dict', 'fo'], {'indent': '(4)'}), '(my_dict, fo, indent=4)\n', (156, 179), False, 'import json\n')] |
from django.forms.models import model_to_dict
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from faker import Faker
from resources_portal.models import User
from resources_portal.test.factories import MaterialFactory, OrganizationFactory, UserFactory
fa... | [
"django.urls.reverse",
"resources_portal.test.factories.OrganizationFactory",
"faker.Faker",
"resources_portal.test.factories.MaterialFactory",
"django.forms.models.model_to_dict",
"resources_portal.models.User.objects.get",
"resources_portal.test.factories.UserFactory"
] | [((325, 332), 'faker.Faker', 'Faker', ([], {}), '()\n', (330, 332), False, 'from faker import Faker\n'), ((499, 520), 'resources_portal.test.factories.OrganizationFactory', 'OrganizationFactory', ([], {}), '()\n', (518, 520), False, 'from resources_portal.test.factories import MaterialFactory, OrganizationFactory, User... |
from csv import writer as csvwriter
from numpy import percentile, max as npmax, min as npmin, array as nparray
from cv2 import CAP_PROP_FPS, VideoCapture
from os import path as ospath
import matplotlib.pyplot as plt
from draw import draw
from scipy import stats
from TrackingObjects import Line
from math import atan, pi... | [
"os.path.join",
"math.atan",
"DataReader.read_data",
"TrackingObjects.Line",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.savefig",
"numpy.percentile",
"numpy.max",
"csv.writer",
"matplotlib.pyplot.figure",
"draw.draw",
"cv2.VideoCapture",
"matplotlib.pyplot.t... | [((9787, 9813), 'scipy.stats.linregress', 'stats.linregress', (['pfx', 'pfy'], {}), '(pfx, pfy)\n', (9803, 9813), False, 'from scipy import stats\n'), ((10134, 10151), 'TrackingObjects.Line', 'Line', (['slope', 'yint'], {}), '(slope, yint)\n', (10138, 10151), False, 'from TrackingObjects import Line\n'), ((11351, 11419... |
"""General utility tools."""
import asyncio
import inspect
import random
class Log:
"""Debugging log writer.
Parameters
----------
out_fh : file handle
Output file/stream.
debug : boolean
Log will only be written if True.
"""
def __init__(self, out_fh, debug):
se... | [
"inspect.iscoroutinefunction",
"inspect.isawaitable"
] | [((2511, 2534), 'inspect.isawaitable', 'inspect.isawaitable', (['cb'], {}), '(cb)\n', (2530, 2534), False, 'import inspect\n'), ((2538, 2569), 'inspect.iscoroutinefunction', 'inspect.iscoroutinefunction', (['cb'], {}), '(cb)\n', (2565, 2569), False, 'import inspect\n')] |
"""Get Keys from keyboard."""
import win32api as wapi
import win32con as con
keyList = [con.VK_SPACE, 0x51, con.VK_UP, con.VK_DOWN]
def keys():
"""Retrieves the associated key with snapshot."""
keys_array = []
for key in keyList:
if isinstance(key, int):
if wapi.GetAsyncKeyState(key):
... | [
"win32api.GetAsyncKeyState"
] | [((292, 318), 'win32api.GetAsyncKeyState', 'wapi.GetAsyncKeyState', (['key'], {}), '(key)\n', (313, 318), True, 'import win32api as wapi\n')] |
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
# Geral
tf.set_random_seed(1)
xavier = tf.contrib.layers.xavier_initializer()
# Dados
mnist = input_data.read_data_sets('.')
# Modelo
x = tf.placeholder(tf.float32, [None, 784])
with tf.name_scope('single'):
W = tf.Variable(xav... | [
"tensorflow.contrib.layers.xavier_initializer",
"tensorflow.global_variables_initializer",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.zeros",
"tensorflow.examples.tutorials.mnist.input_data.read_data_sets",
"tensorflow.cast",
"tensorflow.placeholder",
"tensorflow.Session",
"tensorflow.... | [((94, 115), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(1)'], {}), '(1)\n', (112, 115), True, 'import tensorflow as tf\n'), ((125, 163), 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), '()\n', (161, 163), True, 'import tensorflow as tf\n'), ((181, 211), 'te... |
import torch
import os
import numpy as np
USE_CUDA = torch.cuda.is_available()
FLOAT = torch.cuda.FloatTensor if USE_CUDA else torch.FloatTensor
DOUBLE = torch.cuda.DoubleTensor if USE_CUDA else torch.DoubleTensor
LONG = torch.cuda.LongTensor if USE_CUDA else torch.LongTensor
TYPE_LIST = {"FLOAT": (np.float32, FLOAT... | [
"os.path.join",
"os.path.dirname",
"os.path.abspath",
"torch.cuda.is_available",
"torch.from_numpy",
"os.path.exists",
"os.makedirs"
] | [((55, 80), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (78, 80), False, 'import torch\n'), ((618, 643), 'torch.from_numpy', 'torch.from_numpy', (['ndarray'], {}), '(ndarray)\n', (634, 643), False, 'import torch\n'), ((1195, 1220), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(... |
#!/usr/bin/env python
import os
from distutils.core import setup, Extension
additional_libs = None
if os.name == 'nt':
additional_libs = [ 'Advapi32' ]
module_raw = Extension(
'vnpy._libvncxx',
include_dirs = [ 'libvncxx/include', 'libvncxx/libvnc/include' ],
swig_opts = [ '-c++' ],
... | [
"distutils.core.setup",
"distutils.core.Extension"
] | [((183, 1841), 'distutils.core.Extension', 'Extension', (['"""vnpy._libvncxx"""'], {'include_dirs': "['libvncxx/include', 'libvncxx/libvnc/include']", 'swig_opts': "['-c++']", 'libraries': 'additional_libs', 'sources': "['vnpy/libvncxx_wrap.cpp', 'libvncxx/src/attitude.cpp',\n 'libvncxx/src/compositedata.cpp', 'libv... |
from datetime import timedelta
import threading
import time
class GameTimer(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self._paused = False
self._duration = 0
self._stopped = False
def pause(self):
self._paused = True
def stop(self):
... | [
"threading.Thread.__init__",
"datetime.timedelta",
"time.sleep"
] | [((130, 161), 'threading.Thread.__init__', 'threading.Thread.__init__', (['self'], {}), '(self)\n', (155, 161), False, 'import threading\n'), ((534, 547), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (544, 547), False, 'import time\n'), ((660, 693), 'datetime.timedelta', 'timedelta', ([], {'seconds': 'self._dura... |
import logging
import ddtrace
from ddtrace.constants import ENV_KEY, VERSION_KEY
from ddtrace.compat import StringIO
from ddtrace.contrib.logging import patch, unpatch
from ddtrace.vendor import wrapt
from ...base import BaseTracerTestCase
logger = logging.getLogger()
logger.level = logging.INFO
DEFAULT_FORMAT = (... | [
"logging.getLogger",
"logging.Formatter",
"ddtrace.contrib.logging.unpatch",
"ddtrace.contrib.logging.patch",
"logging.StreamHandler",
"ddtrace.compat.StringIO"
] | [((253, 272), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (270, 272), False, 'import logging\n'), ((698, 708), 'ddtrace.compat.StringIO', 'StringIO', ([], {}), '()\n', (706, 708), False, 'from ddtrace.compat import StringIO\n'), ((718, 744), 'logging.StreamHandler', 'logging.StreamHandler', (['out'], {}... |
import requests
from django.core.management.base import BaseCommand
from georiviere.observations.models import Unit
class Command(BaseCommand):
help = "Import reference data as unit and parameters"
urf_url = "https://api.sandre.eaufrance.fr/referentiels/v1/urf.json"
parameters_url = "https://api.sandre.... | [
"requests.get",
"georiviere.observations.models.Unit.objects.get_or_create"
] | [((685, 711), 'requests.get', 'requests.get', (['self.urf_url'], {}), '(self.urf_url)\n', (697, 711), False, 'import requests\n'), ((1148, 1289), 'georiviere.observations.models.Unit.objects.get_or_create', 'Unit.objects.get_or_create', ([], {'code': "urf['CdUniteReference']", 'defaults': "{'label': urf['LbUniteReferen... |
# -*- coding: utf-8 -*-
# (c) Copyright 2021 Sensirion AG, Switzerland
##############################################################################
##############################################################################
# _____ _ _ _______ _____ ____ _ _
# / ____| ... | [
"logging.getLogger",
"sensirion_i2c_sdp.sdp.response_types.SdpTemperature",
"struct.unpack",
"sensirion_i2c_driver.CrcCalculator",
"sensirion_i2c_sdp.sdp.response_types.SdpDifferentialPressure"
] | [((1253, 1280), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1270, 1280), False, 'import logging\n'), ((14115, 14183), 'sensirion_i2c_sdp.sdp.response_types.SdpDifferentialPressure', 'SdpDifferentialPressure', (['differential_pressure_ticks', 'scaling_factor'], {}), '(differential_pres... |
import numpy as np
import pandas as pd
from config import conf
import eigen as eig
import region as reg
import hiperbolica as hyp
import matrices_acoplamiento as m_acop
import distorsionador as v_dist
import matriz_gauss as m_gauss
import v_transpuestos as v_trans
__doc__ = """
Este modulo se determina el flujo y la... | [
"numpy.diag",
"numpy.zeros",
"pandas.read_csv",
"pandas.DataFrame",
"v_transpuestos.calcular_vector_transpuesto"
] | [((716, 737), 'pandas.read_csv', 'pd.read_csv', (['filename'], {}), '(filename)\n', (727, 737), True, 'import pandas as pd\n'), ((2914, 2954), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'recursos_flujo.index'}), '(index=recursos_flujo.index)\n', (2926, 2954), True, 'import pandas as pd\n'), ((3128, 3168), 'pand... |
"""
Example for interactively displaying a molecule using mogli
"""
import mogli
molecules = mogli.read('examples/dna.xyz')
for molecule in molecules:
mogli.show(molecule, bonds_param=1.15)
| [
"mogli.read",
"mogli.show"
] | [((94, 124), 'mogli.read', 'mogli.read', (['"""examples/dna.xyz"""'], {}), "('examples/dna.xyz')\n", (104, 124), False, 'import mogli\n'), ((156, 194), 'mogli.show', 'mogli.show', (['molecule'], {'bonds_param': '(1.15)'}), '(molecule, bonds_param=1.15)\n', (166, 194), False, 'import mogli\n')] |
from google.appengine.ext import db
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from ragendja.dbutils import KeyListProperty
class FlatPage(db.Model):
url = db.StringProperty(required=True, verbose_name=_('URL'))
title = db.StringProperty(required=True, ... | [
"ragendja.dbutils.KeyListProperty",
"django.utils.translation.ugettext_lazy"
] | [((707, 728), 'ragendja.dbutils.KeyListProperty', 'KeyListProperty', (['Site'], {}), '(Site)\n', (722, 728), False, 'from ragendja.dbutils import KeyListProperty\n'), ((769, 783), 'django.utils.translation.ugettext_lazy', '_', (['"""flat page"""'], {}), "('flat page')\n", (770, 783), True, 'from django.utils.translatio... |
from . import views
from django.urls import path
urlpatterns = [
path('quiz/<int:pk>/result/', views.quiz_result_view, name='eng-quiz-result-view'),
path('quiz/<int:pk>/save/', views.quiz_save_view, name='eng-quiz-save-view'),
path('quiz/<int:pk>/data/', views.quiz_data_view, name='eng-quiz-data-view'),
... | [
"django.urls.path"
] | [((70, 157), 'django.urls.path', 'path', (['"""quiz/<int:pk>/result/"""', 'views.quiz_result_view'], {'name': '"""eng-quiz-result-view"""'}), "('quiz/<int:pk>/result/', views.quiz_result_view, name=\n 'eng-quiz-result-view')\n", (74, 157), False, 'from django.urls import path\n'), ((158, 234), 'django.urls.path', 'p... |
#! /usr/bin/env python
"""
MSGR Matching Satellite and Ground Radar
========================================
@author: <NAME>
@date: 2016-12-06 (creation) 2017-10-05 (current version)
@email: <EMAIL>
@company: Monash University/Bureau of Meteorology
"""
# Standard library import
import os
import re
import glob
import t... | [
"pandas.date_range",
"warnings.simplefilter",
"datetime.datetime.strptime",
"re.findall",
"os.path.isdir",
"argparse.ArgumentParser",
"multiprocessing.Pool",
"configparser.ConfigParser",
"time.time",
"msgr.cross_validation.match_volumes",
"traceback.print_exc",
"glob.glob"
] | [((4482, 4509), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (4507, 4509), False, 'import configparser\n'), ((5880, 5923), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['date1', '"""%Y%m%d"""'], {}), "(date1, '%Y%m%d')\n", (5906, 5923), False, 'import datetime\n'), ((5939,... |
from torch.utils.data.dataset import Dataset
from torch.utils.data import DataLoader
from PIL import Image
import sys
import os
import random
import numpy as np
import pandas as pd
class UltrasoundDataset(object):
def __init__(self, data_path, val_size=0.2, random_seed=1):
self.data_path = data_path
... | [
"os.path.join",
"os.listdir",
"os.path.normpath",
"os.path.splitext",
"numpy.array",
"pandas.DataFrame",
"random.Random",
"torch.utils.data.DataLoader",
"pandas.read_csv",
"os.path.split",
"numpy.concatenate",
"sys.exit",
"PIL.Image.open"
] | [((7402, 7502), 'torch.utils.data.DataLoader', 'DataLoader', ([], {'dataset': 'train_dataset', 'batch_size': "params['batch_size']", 'shuffle': '(True)', 'num_workers': '(4)'}), "(dataset=train_dataset, batch_size=params['batch_size'], shuffle=\n True, num_workers=4)\n", (7412, 7502), False, 'from torch.utils.data i... |
import json
# helper functions
def build_response(code, body):
# headers for cors
headers = {
# "Access-Control-Allow-Origin": "amazonaws.com",
# "Access-Control-Allow-Credentials": True,
"Content-Type": "application/json"
}
# lambda proxy integration
response = {
"i... | [
"json.dumps"
] | [((969, 988), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (979, 988), False, 'import json\n'), ((1000, 1018), 'json.dumps', 'json.dumps', (['output'], {}), '(output)\n', (1010, 1018), False, 'import json\n')] |
# Shim for editable install.
import setuptools
setuptools.setup()
| [
"setuptools.setup"
] | [((49, 67), 'setuptools.setup', 'setuptools.setup', ([], {}), '()\n', (65, 67), False, 'import setuptools\n')] |
"""Build and compile a FLASH simulation directory."""
# type annotations
from __future__ import annotations
from typing import Any
# standard libraries
import logging
import os
import sys
from pathlib import Path
# internal libraries
from ...core.error import AutoError
from ...core.parallel import safe, single, squa... | [
"logging.getLogger",
"pathlib.Path"
] | [((508, 535), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (525, 535), False, 'import logging\n'), ((986, 1006), 'pathlib.Path', 'Path', (["args['source']"], {}), "(args['source'])\n", (990, 1006), False, 'from pathlib import Path\n')] |
import warnings
import pandas as pd
import numpy as np
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import Button
from bokeh.models.callbacks import CustomJS
from bokeh.models.layouts import Column
from bokeh.io import output_file, show
from astropy import uni... | [
"bokeh.io.output_file",
"numpy.nan_to_num",
"warnings.filterwarnings",
"dustmaps.bayestar.BayestarWebQuery",
"astropy.coordinates.SkyCoord",
"bokeh.models.widgets.Button",
"numpy.sqrt",
"warnings.catch_warnings",
"numpy.isnan",
"pandas.Series",
"numpy.abs",
"bokeh.models.layouts.Column",
"nu... | [((1294, 1337), 'bokeh.models.widgets.Button', 'Button', ([], {'label': '"""Save"""', 'button_type': '"""success"""'}), "(label='Save', button_type='success')\n", (1300, 1337), False, 'from bokeh.models.widgets import Button\n'), ((2071, 2146), 'bokeh.plotting.figure', 'figure', ([], {'plot_width': '(800)', 'plot_heigh... |
from typing import Optional
import torch
#cuda = torch.cuda.is_available()
dtype = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor
# datasetting
data_dir = "/media/fangxu/Disk4T/LQ/data/"
scene = "chess" #optional "chess",
train_seq_list = [1,2,3,4]#
val_seq_list = [5,6]
aug_mode = 1
mi... | [
"torch.cuda.is_available"
] | [((111, 136), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (134, 136), False, 'import torch\n')] |
import pytest
from fhir2dataset.parser import Parser # noqa
@pytest.mark.parametrize(
"sql_query",
[
"SELECT Patient.name.family FROM Patient",
"SELECT Patient.name.family FROM Patient;",
"SELECT p.name.family FROM Patient as p",
"SELECT p.name.family FROM Patient as p;",
... | [
"pytest.raises",
"pytest.mark.parametrize",
"fhir2dataset.parser.Parser"
] | [((65, 555), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""sql_query"""', '[\'SELECT Patient.name.family FROM Patient\',\n \'SELECT Patient.name.family FROM Patient;\',\n \'SELECT p.name.family FROM Patient as p\',\n \'SELECT p.name.family FROM Patient as p;\',\n \'SELECT Patient.name.family F... |
import os, sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from .cmx import *
from .features import *
from .load_data import *
from .roc_auc import *
from .scoring import *
from .predictor import *
from .nodegraph import *
| [
"os.path.realpath"
] | [((48, 74), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (64, 74), False, 'import os, sys\n')] |
#!/usr/bin/env python3
import subprocess as sp,sys,time,re,string
import threading
from socket import *
from struct import *
idx_read = 0
def read_until(s,c):
global idx_read
print("Read idx %d"%idx_read)
idx_read+=1
cc = s.recv(1)
mes=b""
while cc != c:
mes+=cc
# sys.write(cc.de... | [
"threading.Timer",
"re.findall",
"sys.stderr.flush"
] | [((2463, 2494), 're.findall', 're.findall', (['"""([0-9A-F]+)"""', 'cont'], {}), "('([0-9A-F]+)', cont)\n", (2473, 2494), False, 'import subprocess as sp, sys, time, re, string\n'), ((2612, 2643), 're.findall', 're.findall', (['"""([0-9A-F]+)"""', 'cont'], {}), "('([0-9A-F]+)', cont)\n", (2622, 2643), False, 'import su... |
import os
import sys
import torch
import time
import math
import numpy as np
from torch.autograd import Variable
from utils import render_part_pcs, export_part_pcs, render_pc, export_pc
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(BASE_DIR, 'metrics'))
sys.path.append(os.path.join(... | [
"os.path.join",
"torch.randn",
"subprocess.call",
"torch.rand",
"torch.load",
"os.path.abspath",
"numpy.expand_dims",
"os.mkdir",
"fid.FID",
"torch.arange",
"torch.autograd.grad",
"torch.no_grad",
"time.time",
"torch.Tensor",
"numpy.concatenate",
"sampling.furthest_point_sample",
"to... | [((213, 238), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (228, 238), False, 'import os\n'), ((256, 289), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""metrics"""'], {}), "(BASE_DIR, 'metrics')\n", (268, 289), False, 'import os\n'), ((307, 341), 'os.path.join', 'os.path.join', (['BASE_... |
import uvicorn
from fastapi import FastAPI
from src.api import router
from src.core import get_settings
app = FastAPI(title = get_settings().PROJECT_TITLE)
app.include_router(
router = router,
prefix = get_settings().COMMON_API
)
if __name__ == '__main__':
uvicorn.run('src.main:app', host='0.0.0.0', por... | [
"uvicorn.run",
"src.core.get_settings"
] | [((273, 340), 'uvicorn.run', 'uvicorn.run', (['"""src.main:app"""'], {'host': '"""0.0.0.0"""', 'port': '(8000)', 'reload': '(True)'}), "('src.main:app', host='0.0.0.0', port=8000, reload=True)\n", (284, 340), False, 'import uvicorn\n'), ((128, 142), 'src.core.get_settings', 'get_settings', ([], {}), '()\n', (140, 142),... |
import json, subprocess
from .... pyaz_utils import get_cli_name, get_params
def create(resource_group, route_table_name, name, next_hop_type, address_prefix, next_hop_ip_address=None):
params = get_params(locals())
command = "az network route-table route create " + params
print(command)
output = s... | [
"json.loads",
"subprocess.run"
] | [((319, 407), 'subprocess.run', 'subprocess.run', (['command'], {'shell': '(True)', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), '(command, shell=True, stdout=subprocess.PIPE, stderr=\n subprocess.PIPE)\n', (333, 407), False, 'import json, subprocess\n'), ((811, 899), 'subprocess.run', 'subprocess.run... |
import bpy
import bmesh
import operator
import mathutils
import addon_utils
from . import platform
class Platform(platform.Platform):
extension = 'gltf'
def __init__(self):
super().__init__()
def is_valid(self):
# Plugin available for FLTF?
mode = bpy.context.scene.FBXBundleSettings.target_platform
i... | [
"addon_utils.check",
"bpy.ops.export_scene.gltf"
] | [((568, 654), 'bpy.ops.export_scene.gltf', 'bpy.ops.export_scene.gltf', ([], {'filepath': 'path', 'export_selected': '(True)', 'export_apply': '(True)'}), '(filepath=path, export_selected=True, export_apply\n =True)\n', (593, 654), False, 'import bpy\n'), ((433, 468), 'addon_utils.check', 'addon_utils.check', (['"""... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
# from LaxFriedrichs import LF_flux
from .compute_flux_1d import compute_flux_1d, compute_flux_1d_bis
from .variables import ConservedVars, PrimitiveVars
from .adjoint_function import ALFcons, BLFcons, CLFcons, DLFcons
g = 9.81
# --------------------... | [
"numpy.linspace",
"numpy.append",
"numpy.diag",
"numpy.sum",
"numpy.sqrt",
"numpy.fmax",
"numpy.isnan",
"numpy.zeros",
"numpy.diff",
"numpy.insert",
"numpy.ones",
"numpy.empty",
"numpy.fabs",
"numpy.sign"
] | [((1250, 1298), 'numpy.linspace', 'np.linspace', (['(D[0] + dx / 2.0)', '(D[1] - dx / 2.0)', 'N'], {}), '(D[0] + dx / 2.0, D[1] - dx / 2.0, N)\n', (1261, 1298), True, 'import numpy as np\n'), ((1307, 1337), 'numpy.linspace', 'np.linspace', (['D[0]', 'D[1]', '(N + 1)'], {}), '(D[0], D[1], N + 1)\n', (1318, 1337), True, ... |
from discord.ext import commands
from discord import Member, Embed, Forbidden
from discord_slash import cog_ext, SlashContext, SlashCommandOptionType
from discord_slash.utils import manage_commands
from administrator.check import is_enabled, guild_only, has_permissions
from administrator.logger import logger
from admi... | [
"administrator.check.has_permissions",
"discord.ext.commands.Cog.listener",
"discord_slash.utils.manage_commands.create_choice",
"administrator.check.is_enabled",
"administrator.logger.logger.info",
"administrator.slash.remove_cog_commands",
"administrator.utils.event_is_enabled",
"administrator.db.Se... | [((436, 467), 'administrator.logger.logger.getChild', 'logger.getChild', (['extension_name'], {}), '(extension_name)\n', (451, 467), False, 'from administrator.logger import logger\n'), ((1527, 1539), 'administrator.check.is_enabled', 'is_enabled', ([], {}), '()\n', (1537, 1539), False, 'from administrator.check import... |
"""
This thing should find the reflectance and absorbtance as a function of
angle of incidence. Then it fits these functions to a 4th order polynomial
because that's what EnergyPlus does for some reason.
"""
import numpy as np
from wpv import Layer,Stack
import matplotlib.pyplot as plt
from scipy.optimize import curv... | [
"numpy.linspace",
"matplotlib.pyplot.xlabel",
"wpv.Stack",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure",
"wpv.Layer",
"numpy.array",
"numpy.cos",
"scipy.optimize.curve_fit",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.plot"
] | [((562, 594), 'wpv.Layer', 'Layer', (['(4000)', '"""nkLowFeGlass"""', '"""i"""'], {}), "(4000, 'nkLowFeGlass', 'i')\n", (567, 594), False, 'from wpv import Layer, Stack\n'), ((600, 626), 'wpv.Layer', 'Layer', (['(0.05)', '"""nkTiO2"""', '"""c"""'], {}), "(0.05, 'nkTiO2', 'c')\n", (605, 626), False, 'from wpv import Lay... |
from django.test import TestCase
from django.urls import reverse
from user.forms import (AssociatedEmailChoiceForm, AddEmailForm,
LoginForm, ProfileForm, RegistrationForm)
from user.models import User
class TestForms(TestCase):
def create_test_forms(self, FormClass, valid_dict, invalid_dict, user=None):
... | [
"user.forms.AssociatedEmailChoiceForm",
"user.models.User.objects.get"
] | [((1349, 1382), 'user.models.User.objects.get', 'User.objects.get', ([], {'email': '"""<EMAIL>"""'}), "(email='<EMAIL>')\n", (1365, 1382), False, 'from user.models import User\n'), ((1409, 1514), 'user.forms.AssociatedEmailChoiceForm', 'AssociatedEmailChoiceForm', ([], {'user': 'user', 'selection_type': '"""primary"""'... |
# importing datetime library
import datetime
# get todays date
print(datetime.date.today())
# get current year
print(datetime.date.today().year)
# get current month
print(datetime.date.today().month)
# get current day
print(datetime.date.today().day)
# ctime(const time_t *timer) returns a string representing the l... | [
"datetime.date.today"
] | [((70, 91), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (89, 91), False, 'import datetime\n'), ((119, 140), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (138, 140), False, 'import datetime\n'), ((174, 195), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (193, 195)... |
import logging
from rabbitmq.RBPoolPublisher import *
from rabbitmq.RBAsynPublisher import *
from concurrent.futures import *
import threading
from threading import Thread
LOG_FORMAT = '%(levelname) -10s %(asctime)s %(name) -30s %(funcName) -35s %(lineno) -5d: %(message)s'
logger = logging.getLogger(__name__)
def ru... | [
"logging.getLogger",
"logging.basicConfig"
] | [((284, 311), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (301, 311), False, 'import logging\n'), ((673, 732), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG', 'format': 'LOG_FORMAT'}), '(level=logging.DEBUG, format=LOG_FORMAT)\n', (692, 732), False, 'impor... |
import io
import os
import tempfile
from PIL import Image
from google.cloud import storage
storage_client = storage.Client()
def resize_image(image: Image) -> Image:
"""
scales down the image to 1024x768 or lower, if it's size is bigger than 1024x768
Otherwise, scales it to 90% of the size.
1024x768 ... | [
"io.BytesIO",
"tempfile.mkstemp",
"os.remove",
"os.getenv",
"google.cloud.storage.Client",
"PIL.Image.open"
] | [((109, 125), 'google.cloud.storage.Client', 'storage.Client', ([], {}), '()\n', (123, 125), False, 'from google.cloud import storage\n'), ((1299, 1333), 'tempfile.mkstemp', 'tempfile.mkstemp', ([], {'suffix': 'file_name'}), '(suffix=file_name)\n', (1315, 1333), False, 'import tempfile\n'), ((1455, 1477), 'io.BytesIO',... |
from django.contrib import admin
# Register your models here.
from .models import *
class ChannelAdmin(admin.ModelAdmin):
fieldsets = [
('Identifiers', {'fields': ['name', 'number']}),
('Constraints', {'fields': ['rangeMin', 'rangeMax']}),
('Dynamics', {'fields': ['speed', 'acceleration',... | [
"django.contrib.admin.site.register"
] | [((383, 425), 'django.contrib.admin.site.register', 'admin.site.register', (['Channel', 'ChannelAdmin'], {}), '(Channel, ChannelAdmin)\n', (402, 425), False, 'from django.contrib import admin\n')] |
# Copyright (c) 2021, RF and contributors
# For license information, please see license.txt
import frappe
from frappe import _
from frappe.utils import nowdate
from frappe.model.document import Document
class OrderReceiving(Document):
def on_submit(self):
self.make_purchase_invoice()
@frappe.whitelist()
def ge... | [
"frappe.utils.nowdate",
"frappe.get_doc",
"frappe.whitelist",
"frappe.get_list",
"frappe._",
"frappe.get_value",
"frappe.new_doc"
] | [((4733, 4751), 'frappe.whitelist', 'frappe.whitelist', ([], {}), '()\n', (4749, 4751), False, 'import frappe\n'), ((5191, 5209), 'frappe.whitelist', 'frappe.whitelist', ([], {}), '()\n', (5207, 5209), False, 'import frappe\n'), ((294, 312), 'frappe.whitelist', 'frappe.whitelist', ([], {}), '()\n', (310, 312), False, '... |
#!/usr/bin/env python3
import json
import csv
import os.path
import requests
__author__ = "<NAME>"
__version__ = "2.1.0"
__license__ = "Unlicense"
def get_pages(username, api_key, limit=200):
""" Getting the number of pages with scrobbling data """
response = requests.get(
"https://ws.audioscrobble... | [
"csv.writer",
"json.dumps"
] | [((1686, 1750), 'json.dumps', 'json.dumps', (['tracks'], {'indent': '(4)', 'sort_keys': '(True)', 'ensure_ascii': '(False)'}), '(tracks, indent=4, sort_keys=True, ensure_ascii=False)\n', (1696, 1750), False, 'import json\n'), ((2230, 2289), 'json.dumps', 'json.dumps', (['_'], {'indent': '(4)', 'sort_keys': '(True)', 'e... |
import numpy as np
import os
import torch
import dataset.dataset_factory as dataset_factory
from colorama import Back, Fore
from config import cfg, update_config_from_file
from torch.utils.data import DataLoader
from dataset.collate import collate_test
from lib.model.clf_net import Cls_Net
from lib.model.gradCAM import... | [
"cv2.boundingRect",
"torch.save",
"numpy.sum",
"os.path.exists",
"numpy.zeros",
"lib.model.clf_net.Cls_Net",
"matplotlib.use",
"numpy.uint8",
"os.makedirs",
"torch.device",
"torch.from_numpy",
"dataset.dataset_factory.get_dataset",
"cv2.UMat",
"matplotlib.pyplot.close",
"utils.bbox_trans... | [((426, 440), 'matplotlib.use', 'mpl.use', (['"""Agg"""'], {}), "('Agg')\n", (433, 440), True, 'import matplotlib as mpl\n'), ((980, 1044), 'cv2.resize', 'cv.resize', (['image', '(width, height)'], {'interpolation': 'cv.INTER_LINEAR'}), '(image, (width, height), interpolation=cv.INTER_LINEAR)\n', (989, 1044), True, 'im... |
"""Get the physical parameters for a telescope module"""
from pyfoxsi.telescope import Optic
optic = Optic()
# the total mass of a telescope module is
print(optic.mass)
# get the properties of a particular telescope shell
print(optic.shell(3))
| [
"pyfoxsi.telescope.Optic"
] | [((103, 110), 'pyfoxsi.telescope.Optic', 'Optic', ([], {}), '()\n', (108, 110), False, 'from pyfoxsi.telescope import Optic\n')] |
__author__ = '<NAME>'
from PyQt4.QtCore import pyqtSignal, QObject
class AppointmentAbstract(QObject):
changed = pyqtSignal()
def __init__(self, parent, role):
QObject.__init__(self, parent)
self.role = role
self._note = ''
self._disabled = False
@property
def note(s... | [
"PyQt4.QtCore.pyqtSignal",
"PyQt4.QtCore.QObject.__init__"
] | [((120, 132), 'PyQt4.QtCore.pyqtSignal', 'pyqtSignal', ([], {}), '()\n', (130, 132), False, 'from PyQt4.QtCore import pyqtSignal, QObject\n'), ((733, 745), 'PyQt4.QtCore.pyqtSignal', 'pyqtSignal', ([], {}), '()\n', (743, 745), False, 'from PyQt4.QtCore import pyqtSignal, QObject\n'), ((759, 778), 'PyQt4.QtCore.pyqtSign... |
"""Breadth First Search on a graph"""
from sets import Set
from linked_list import Node
class lightQueue(object):
"""Simple queue"""
def __init__(self):
self.head = None
self.tail = None
def enqueue(self, lst):
"""Enqueue a list of nodes"""
for obj in lst:
if ... | [
"linked_list.Node"
] | [((365, 374), 'linked_list.Node', 'Node', (['obj'], {}), '(obj)\n', (369, 374), False, 'from linked_list import Node\n'), ((465, 474), 'linked_list.Node', 'Node', (['obj'], {}), '(obj)\n', (469, 474), False, 'from linked_list import Node\n')] |
from datetime import datetime
from teamsbot import WebExActions
from smartsheetFunction import ssActions
from clusterDataFetch import runner
# static stuff
tag_column_mapping = {
"Time": 1946804609673092,
"C1-CM": 7236520691165060,
"C1-IMP1": 6450404237043588,
"C1-UC1": 4198604423358340,
"C1-UC2": 8702204050728836,
"C... | [
"smartsheetFunction.ssActions",
"clusterDataFetch.runner",
"datetime.datetime.now",
"teamsbot.WebExActions"
] | [((3072, 3080), 'clusterDataFetch.runner', 'runner', ([], {}), '()\n', (3078, 3080), False, 'from clusterDataFetch import runner\n'), ((3128, 3139), 'smartsheetFunction.ssActions', 'ssActions', ([], {}), '()\n', (3137, 3139), False, 'from smartsheetFunction import ssActions\n'), ((3179, 3193), 'datetime.datetime.now', ... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import time, datetime
from dbConnection import newDbConnection, oldDbConnection
from filesFolderAccess import getAbsDir, importFilesAndSubfolderInFolder
start_time = time.time()
con = oldDbConnection()
cur = con.cursor()
db_cmd = "SELECT * FROM dbo.DocLib WHERE Si... | [
"filesFolderAccess.getAbsDir",
"datetime.datetime.now",
"dbConnection.newDbConnection",
"time.time",
"filesFolderAccess.importFilesAndSubfolderInFolder",
"dbConnection.oldDbConnection"
] | [((220, 231), 'time.time', 'time.time', ([], {}), '()\n', (229, 231), False, 'import time, datetime\n'), ((239, 256), 'dbConnection.oldDbConnection', 'oldDbConnection', ([], {}), '()\n', (254, 256), False, 'from dbConnection import newDbConnection, oldDbConnection\n'), ((391, 408), 'dbConnection.newDbConnection', 'newD... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""RequestData tests"""
# System imports
import logging
from mock import MagicMock
# Project imports
from ..request_data import RequestData
from draalcore.test_utils.basetest import BaseTest
logger = logging.getLogger(__name__)
class RequestDataTestCase(BaseTest):
... | [
"logging.getLogger",
"mock.MagicMock"
] | [((250, 277), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (267, 277), False, 'import logging\n'), ((919, 938), 'mock.MagicMock', 'MagicMock', ([], {'GET': 'data'}), '(GET=data)\n', (928, 938), False, 'from mock import MagicMock\n'), ((666, 677), 'mock.MagicMock', 'MagicMock', ([], {}),... |
'''
BMCPowerConsumptionMap
'''
from Products.DataCollector.plugins.CollectorPlugin import (
SnmpPlugin, GetMap
)
from DeviceDefine import BMCPCESTATUS, BMCPCFA
class BMCPowerConsumptionMap(SnmpPlugin):
'''
BMCPowerConsumptionMap
'''
relname = 'bmcpowerConsumptions'
modname ... | [
"Products.DataCollector.plugins.CollectorPlugin.GetMap"
] | [((394, 847), 'Products.DataCollector.plugins.CollectorPlugin.GetMap', 'GetMap', (["{'.1.3.6.1.4.1.2011.2.235.1.1.1.13.0': 'presentSystemPower',\n '.1.3.6.1.4.1.2011.192.168.3.11.20.1.0': 'peakPower',\n '.1.3.6.1.4.1.2011.192.168.3.11.20.3.0': 'averagePower',\n '.1.3.6.1.4.1.2011.2.235.1.1.20.4.0': 'powerConsu... |
"""
MIT License
Copyright (c) 2020 GamingGeek
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, dis... | [
"discord.ext.commands.Cog.listener",
"chatwatch.cw.ChatWatch"
] | [((1409, 1432), 'discord.ext.commands.Cog.listener', 'commands.Cog.listener', ([], {}), '()\n', (1430, 1432), False, 'from discord.ext import commands\n'), ((1351, 1402), 'chatwatch.cw.ChatWatch', 'ChatWatch', (["bot.config['chatwatch']", 'self.bot.logger'], {}), "(bot.config['chatwatch'], self.bot.logger)\n", (1360, 1... |
"""
Script for get preprocessed data for deepfashion.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import app
from absl import flags
import os
import os.path as osp
import numpy as np
import pickle
import cv2
from ..external.hmr.hmr impor... | [
"os.path.join",
"absl.flags.DEFINE_integer",
"os.path.abspath",
"absl.flags.DEFINE_string",
"pickle.dump",
"absl.app.run"
] | [((327, 372), 'absl.flags.DEFINE_string', 'flags.DEFINE_string', (['"""dataset"""', '"""deepfashion"""'], {}), "('dataset', 'deepfashion')\n", (346, 372), False, 'from absl import flags\n'), ((373, 424), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""img_size"""', '(256)', '"""image size"""'], {}), "('img_s... |
import pywikibot
import re
from arywikibotlib import *
from bs4 import BeautifulSoup
REF_PATTERN = r"<ref>.+</ref>"
#LINK_PATTERN = r"\[(.+)]\]"
LINK_PATTERN = r"\[(\d+)\]"
title = "تاريخ د لمغريب"
site = pywikibot.Site()
page = pywikibot.Page(site,title)
refs = list(re.findall(REF_PATTERN, page.text))+["[145]"]
... | [
"re.findall",
"pywikibot.Site",
"pywikibot.Page",
"re.search"
] | [((208, 224), 'pywikibot.Site', 'pywikibot.Site', ([], {}), '()\n', (222, 224), False, 'import pywikibot\n'), ((233, 260), 'pywikibot.Page', 'pywikibot.Page', (['site', 'title'], {}), '(site, title)\n', (247, 260), False, 'import pywikibot\n'), ((378, 406), 're.search', 're.search', (['LINK_PATTERN', 'ref'], {}), '(LIN... |
"""Set logging level"""
import logging
logging.getLogger().setLevel(logging.INFO)
| [
"logging.getLogger"
] | [((40, 59), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (57, 59), False, 'import logging\n')] |
# Copyright (c) 2021 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute... | [
"numpy.round",
"pandas.read_csv",
"os.path.basename",
"pandas.read_table"
] | [((3650, 3691), 'pandas.read_table', 'pd.read_table', (['file'], {'encoding': '"""shift-jis"""'}), "(file, encoding='shift-jis')\n", (3663, 3691), True, 'import pandas as pd\n'), ((4151, 4199), 'numpy.round', 'np.round', (['(xrd.theta.iat[1] - xrd.theta.iat[0])', '(4)'], {}), '(xrd.theta.iat[1] - xrd.theta.iat[0], 4)\n... |
#!/usr/bin/env python3
# INSTAGRAM DOWNLOADER GUI
# 2021 (c) <NAME>
# https://github.com/michabirklbauer/
# <EMAIL>
from instaload import instaload, get_image, get_video, is_private
from tkinter import filedialog
import tkinter as tk
import urllib.request as ur
import json
import os
def download(type, arg):
if type... | [
"tkinter.Button",
"instaload.is_private",
"tkinter.Entry",
"tkinter.Label",
"os.path.isfile",
"tkinter.filedialog.askopenfilename",
"tkinter.PhotoImage",
"instaload.instaload",
"tkinter.Tk"
] | [((4051, 4079), 'tkinter.filedialog.askopenfilename', 'filedialog.askopenfilename', ([], {}), '()\n', (4077, 4079), False, 'from tkinter import filedialog\n'), ((4139, 4146), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (4144, 4146), True, 'import tkinter as tk\n'), ((4228, 4254), 'tkinter.PhotoImage', 'tk.PhotoImage', ([]... |
from Calculator import Calculator
import CalculatorCommand as cmd
def main(args=None):
"""
This calculator implements the Command, Memento, and Builder pattern
for better extensibility and maintainability.
"""
print_demo()
print("\n")
get_user_command()
def print_demo():
print("=====... | [
"Calculator.Calculator",
"CalculatorCommand.AddCommand",
"CalculatorCommand.MultiplicationCommand",
"CalculatorCommand.DividerCommand",
"CalculatorCommand.SubstractCommand"
] | [((514, 528), 'Calculator.Calculator', 'Calculator', (['(10)'], {}), '(10)\n', (524, 528), False, 'from Calculator import Calculator\n'), ((616, 633), 'CalculatorCommand.AddCommand', 'cmd.AddCommand', (['(5)'], {}), '(5)\n', (630, 633), True, 'import CalculatorCommand as cmd\n'), ((701, 724), 'CalculatorCommand.Substra... |
import math
import random
import gym
import gym.spaces
import numpy as np
#from gym.envs.classic_control import rendering
from gym.utils import seeding
from numba import jit
#from envs.atc.rendering import Label
#from envs.atc.themes import ColorScheme
from . import model
from . import scenarios
@jit(nopython=True)... | [
"gym.utils.seeding.np_random",
"random.seed",
"random.choice",
"numpy.arctan2",
"math.tanh",
"numba.jit",
"numpy.hypot",
"gym.spaces.Box",
"numpy.array"
] | [((302, 320), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (305, 320), False, 'from numba import jit\n'), ((7775, 7793), 'numba.jit', 'jit', ([], {'nopython': '(True)'}), '(nopython=True)\n', (7778, 7793), False, 'from numba import jit\n'), ((9144, 9162), 'numba.jit', 'jit', ([], {'nopython': ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 21 19:07:08 2018
This script contains the implementation of type 1 metaspike bonding, for two type 1 metaspikes to bond
there needs to be at least one connection between dangling nodes in both metaspikes. For two dangling nodes
to combine the sum of the intensity of t... | [
"random.shuffle"
] | [((1723, 1743), 'random.shuffle', 'random.shuffle', (['set1'], {}), '(set1)\n', (1737, 1743), False, 'import random\n'), ((1749, 1769), 'random.shuffle', 'random.shuffle', (['set2'], {}), '(set2)\n', (1763, 1769), False, 'import random\n'), ((3433, 3453), 'random.shuffle', 'random.shuffle', (['set1'], {}), '(set1)\n', ... |
import os
class GameStats:
"""Track stats for alien invasion"""
def __init__(self, ship_limit):
"""Initialize statistics"""
self.ship_limit = ship_limit
# Start in an inactive state
self.active = False
self.reset_stats(ship_limit)
self.high_score = 0
def r... | [
"os.path.isfile"
] | [((1276, 1322), 'os.path.isfile', 'os.path.isfile', (['"""scores/arcade_high_score.txt"""'], {}), "('scores/arcade_high_score.txt')\n", (1290, 1322), False, 'import os\n'), ((1467, 1512), 'os.path.isfile', 'os.path.isfile', (['"""scores/timed_high_score.txt"""'], {}), "('scores/timed_high_score.txt')\n", (1481, 1512), ... |
import re
import nltk
from nltk.corpus import stopwords
class LogTokenizer:
def __init__(self, filters=r"([ |:|\(|\)|=|,])|(core.)|(\.{2,})"):
self.filters = filters
self.word2index = {'[PAD]': 0, '[CLS]': 1, '[MASK]': 2, '[UNK]': 3}
self.index2word = {0: '[PAD]', 1: '[CLS]', 2: '[MASK]', ... | [
"nltk.corpus.stopwords.words",
"nltk.RegexpTokenizer"
] | [((1546, 1582), 'nltk.RegexpTokenizer', 'nltk.RegexpTokenizer', (['""" """'], {'gaps': '(True)'}), "(' ', gaps=True)\n", (1566, 1582), False, 'import nltk\n'), ((407, 433), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (422, 433), False, 'from nltk.corpus import stopwords\n... |
import os
from PIL import Image, ImageDraw, ImageFont
from view.widgets.calendar import CalendarWidget
from view.widgets.event import EventsWidget
from view.widgets.panel import PanelWidget
from view.widgets.weather import WeatherWidget
from view.widgets.weather_icon_lookup import WeatherIconLookup
class Window7in5... | [
"os.path.join",
"view.widgets.calendar.CalendarWidget",
"view.widgets.panel.PanelWidget",
"view.widgets.weather.WeatherWidget",
"PIL.Image.new",
"view.widgets.event.EventsWidget",
"PIL.ImageDraw.Draw"
] | [((1082, 1103), 'view.widgets.panel.PanelWidget', 'PanelWidget', (['(640)', '(384)'], {}), '(640, 384)\n', (1093, 1103), False, 'from view.widgets.panel import PanelWidget\n'), ((1205, 1295), 'view.widgets.event.EventsWidget', 'EventsWidget', (['(384)', '(640 - calendar_size)'], {'header_font': 'font_large', 'event_fon... |
import unittest
import pinq
class queryable_first_or_default_tests(unittest.TestCase):
def setUp(self):
self.queryable0 = pinq.as_queryable([])
self.queryable1 = pinq.as_queryable(range(1))
self.queryable2 = pinq.as_queryable(range(1, 11))
def test_first_or_default_only_element(self)... | [
"pinq.as_queryable"
] | [((137, 158), 'pinq.as_queryable', 'pinq.as_queryable', (['[]'], {}), '([])\n', (154, 158), False, 'import pinq\n')] |
#!/usr/bin/python
''' Mapper operation for calculating the frequency of each URL
USAGE: ./P2_mapper.py < ../files/access_log | sort | ./P2_reducer.py '''
import sys
import re
for line in sys.stdin:
line = re.sub(r'^\W+|\W+$', '', line)
#Split by double commas to get the GET sentence
words = line.split... | [
"re.sub"
] | [((215, 246), 're.sub', 're.sub', (['"""^\\\\W+|\\\\W+$"""', '""""""', 'line'], {}), "('^\\\\W+|\\\\W+$', '', line)\n", (221, 246), False, 'import re\n')] |
from typing import Dict, Any, List
import tensorflow as tf
import numpy as np
from ..model.model import Model as BaseModel
from ..model.config import LossOpt
from ..graph_encoder.embeddings import NodeEmbeddings
from ..name_encoder.scope_encoder import Encoder as ScopeEncoder
from ..utils.segment import segment_s... | [
"tensorflow.ones_initializer",
"tensorflow.concat",
"tensorflow.glorot_uniform_initializer",
"tensorflow.variable_scope",
"tensorflow.gather",
"tensorflow.placeholder",
"tensorflow.matmul",
"tensorflow.name_scope",
"tensorflow.reduce_sum",
"tensorflow.expand_dims",
"tensorflow.identity"
] | [((3456, 3550), 'tensorflow.gather', 'tf.gather', (['self._nodes.embeddings', 'self._placeholders.prediction_nodes'], {'name': '"""site_state"""'}), "(self._nodes.embeddings, self._placeholders.prediction_nodes, name\n ='site_state')\n", (3465, 3550), True, 'import tensorflow as tf\n'), ((3720, 3818), 'tensorflow.ga... |
import psyneulink as pnl
import numpy as np
import matplotlib.pyplot as plt
#sample Hebb
FeatureNames=['small','medium','large','red','yellow','blue','circle','rectangle','triangle']
# create a variable that corresponds to the size of our feature space
sizeF = len(FeatureNames)
small_red_circle = [1,0,0,1,0,0,1,0,0]
... | [
"matplotlib.pyplot.stem",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.show",
"psyneulink.Composition",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.colorbar",
"psyneulink.RecurrentTransferMechanism",
"matplotlib.pyplot.title",
"numpy.a... | [((357, 374), 'psyneulink.Composition', 'pnl.Composition', ([], {}), '()\n', (372, 374), True, 'import psyneulink as pnl\n'), ((386, 535), 'psyneulink.RecurrentTransferMechanism', 'pnl.RecurrentTransferMechanism', ([], {'size': 'sizeF', 'function': 'pnl.Linear', 'enable_learning': '(True)', 'learning_rate': '(0.1)', 'n... |
import pandas as pd
df1 = pd.read_excel("table_join_exp.xlsx", sheet_name='Sheet1')
print(df1)
df2 = pd.read_excel("table_join_exp.xlsx", sheet_name='Sheet2')
print(df2)
print(pd.merge(df1, df2))
df3 = pd.read_excel("table_join_exp.xlsx", sheet_name='Sheet3')
print(df3)
print(pd.merge(df1, df3, on='编号... | [
"pandas.concat",
"pandas.read_excel",
"pandas.merge"
] | [((29, 86), 'pandas.read_excel', 'pd.read_excel', (['"""table_join_exp.xlsx"""'], {'sheet_name': '"""Sheet1"""'}), "('table_join_exp.xlsx', sheet_name='Sheet1')\n", (42, 86), True, 'import pandas as pd\n'), ((108, 165), 'pandas.read_excel', 'pd.read_excel', (['"""table_join_exp.xlsx"""'], {'sheet_name': '"""Sheet2"""'}... |
from ft.db.dbtestcase import DbTestCase
from passerine.db.common import ProxyObject
from passerine.db.entity import entity
from passerine.db.exception import ReadOnlyProxyException
from passerine.db.mapper import link, CascadingType, AssociationType
@link(
mapped_by='destinations',
inverted_by='origin',
ta... | [
"passerine.db.entity.entity",
"passerine.db.mapper.link"
] | [((252, 478), 'passerine.db.mapper.link', 'link', ([], {'mapped_by': '"""destinations"""', 'inverted_by': '"""origin"""', 'target': '"""ft.db.test_mapper_bidirectional_mapping.Destination"""', 'association': 'AssociationType.ONE_TO_MANY', 'cascading': '[CascadingType.PERSIST, CascadingType.DELETE]'}), "(mapped_by='dest... |
from flask import render_template, flash, redirect
from nlservice import app
from .forms import SubscribeForm, UnsubscribeForm
from .models import Subscriber
# Main/index endpoint for Subscribe form
@app.route('/', methods = ['GET', 'POST'])
@app.route('/index', methods = ['GET', 'POST'])
def index():
form = Subscrib... | [
"nlservice.app.route",
"flask.render_template"
] | [((201, 240), 'nlservice.app.route', 'app.route', (['"""/"""'], {'methods': "['GET', 'POST']"}), "('/', methods=['GET', 'POST'])\n", (210, 240), False, 'from nlservice import app\n'), ((244, 288), 'nlservice.app.route', 'app.route', (['"""/index"""'], {'methods': "['GET', 'POST']"}), "('/index', methods=['GET', 'POST']... |
"""
This module contains tests for programs-related signals and signal handlers.
"""
import datetime
from unittest import mock
from django.test import TestCase
from opaque_keys.edx.keys import CourseKey
from common.djangoapps.student.tests.factories import UserFactory
from openedx.core.djangoapps.programs.signals im... | [
"openedx.core.djangoapps.signals.signals.COURSE_CERT_AWARDED.send",
"openedx.core.djangoapps.programs.signals.handle_course_cert_awarded",
"openedx.core.djangoapps.signals.signals.COURSE_CERT_CHANGED.send",
"openedx.core.djangoapps.site_configuration.tests.factories.SiteConfigurationFactory.create",
"opened... | [((827, 879), 'opaque_keys.edx.keys.CourseKey.from_string', 'CourseKey.from_string', (['"""course-v1:edX+test_course+1"""'], {}), "('course-v1:edX+test_course+1')\n", (848, 879), False, 'from opaque_keys.edx.keys import CourseKey\n'), ((951, 1041), 'unittest.mock.patch', 'mock.patch', (['"""openedx.core.djangoapps.prog... |
import os
from copy import deepcopy
from typing import Dict, Iterable, List
import numpy as np
import torch
import torchvision
from PIL import Image
from torch.utils.data import DataLoader
from utils import DistributedSampler, MeanAccumulator
from . import cifar_architectures
class Batch:
def __init__(self, x,... | [
"torchvision.transforms.RandomHorizontalFlip",
"torch.random.manual_seed",
"utils.MeanAccumulator",
"torch.nn.CrossEntropyLoss",
"torchvision.transforms.ToTensor",
"numpy.argsort",
"utils.DistributedSampler",
"torch.random.fork_rng",
"numpy.random.RandomState",
"torch.no_grad",
"torch.isnan",
... | [((6092, 6109), 'utils.MeanAccumulator', 'MeanAccumulator', ([], {}), '()\n', (6107, 6109), False, 'from utils import DistributedSampler, MeanAccumulator\n'), ((6923, 6944), 'copy.deepcopy', 'deepcopy', (['self._model'], {}), '(self._model)\n', (6931, 6944), False, 'from copy import deepcopy\n'), ((9074, 9098), 'numpy.... |
# coding=utf-8
"""Headcount."""
import calendar
from dataclasses import dataclass
from datetime import date
@dataclass
class Date(object):
"""Date."""
_year: int = date.today().year
_month: int = date.today().month
_day: int = date.today().day
def date_name(self) -> str:
"""Returns month... | [
"calendar.LocaleTextCalendar",
"datetime.date.today"
] | [((175, 187), 'datetime.date.today', 'date.today', ([], {}), '()\n', (185, 187), False, 'from datetime import date\n'), ((211, 223), 'datetime.date.today', 'date.today', ([], {}), '()\n', (221, 223), False, 'from datetime import date\n'), ((246, 258), 'datetime.date.today', 'date.today', ([], {}), '()\n', (256, 258), F... |
# -*- coding: utf-8 -*-
import cv2
from __init__ import Square
from face import facefrontal, warp_mapping, get_landmark, LandmarkIndex as LI, fronter, LandmarkFetcher, get_projM, resize
from mouth import sharpen
import numpy as np
def getGaussianPyr(img, layers):
g = img.astype(np.float64)
pyramid =... | [
"numpy.sum",
"numpy.where",
"__init__.Square",
"numpy.zeros",
"numpy.ones",
"numpy.arange",
"numpy.linalg.norm",
"cv2.imwrite",
"cv2.resize",
"cv2.pyrDown",
"face.LandmarkFetcher",
"mouth.sharpen",
"cv2.inpaint",
"numpy.max",
"cv2.imread",
"numpy.exp",
"face.facefrontal",
"cv2.pyrU... | [((2911, 2965), 'numpy.zeros', 'np.zeros', (['(sWH, sWH, syntxtr.shape[2])'], {'dtype': 'np.uint8'}), '((sWH, sWH, syntxtr.shape[2]), dtype=np.uint8)\n', (2919, 2965), True, 'import numpy as np\n'), ((4201, 4243), 'numpy.linalg.norm', 'np.linalg.norm', (['(coords - pt)'], {'ord': '(2)', 'axis': '(1)'}), '(coords - pt, ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 7 08:13:28 2020
@author: esteban
"""
from mapaIndiceContagio import mapaIndiceContagio
fechaAAnalizar='2020-05-11'
lista_indices='var1periodo'
#['riesgo_activos',
# 'var1periodo',
# 'riesgo_activos_variacion']
mapaInd... | [
"mapaIndiceContagio.mapaIndiceContagio"
] | [((313, 362), 'mapaIndiceContagio.mapaIndiceContagio', 'mapaIndiceContagio', (['fechaAAnalizar', 'lista_indices'], {}), '(fechaAAnalizar, lista_indices)\n', (331, 362), False, 'from mapaIndiceContagio import mapaIndiceContagio\n')] |
"""Test Axis Motion Guard API.
pytest --cov-report term-missing --cov=axis.applications.motion_guard tests/applications/test_motion_guard.py
"""
import json
import pytest
import respx
from axis.applications.motion_guard import MotionGuard
from ..conftest import HOST
@pytest.fixture
def motion_guard(axis_device) ... | [
"json.loads",
"axis.applications.motion_guard.MotionGuard",
"respx.post"
] | [((395, 433), 'axis.applications.motion_guard.MotionGuard', 'MotionGuard', (['axis_device.vapix.request'], {}), '(axis_device.vapix.request)\n', (406, 433), False, 'from axis.applications.motion_guard import MotionGuard\n'), ((900, 944), 'json.loads', 'json.loads', (['route.calls.last.request.content'], {}), '(route.ca... |
__author__ = 'Eric'
import pygame
import random
pygame.init()
white = (255, 255, 255)
black = (0, 0, 0)
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Basic Snake")
block_size = 10
FPS = 15
font = pygame.font.SysFont(None, 25)
def snake(block... | [
"pygame.time.Clock",
"random.randrange",
"pygame.draw.rect",
"pygame.display.update",
"pygame.display.set_caption",
"pygame.font.SysFont",
"pygame.quit",
"pygame.display.set_mode",
"pygame.event.get",
"pygame.init"
] | [((49, 62), 'pygame.init', 'pygame.init', ([], {}), '()\n', (60, 62), False, 'import pygame\n'), ((162, 197), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(800, 600)'], {}), '((800, 600))\n', (185, 197), False, 'import pygame\n'), ((198, 239), 'pygame.display.set_caption', 'pygame.display.set_caption', (['"... |
import unittest
import torchaudio
from torchaudio_augmentations import (
Compose,
RandomApply,
RandomResizedCrop,
PolarityInversion,
Noise,
Gain,
Delay,
PitchShift,
Reverb,
)
from clmr.datasets import AUDIO
class TestAudioSet(unittest.TestCase):
sample_rate = 16000
def get... | [
"torchaudio.save",
"torchaudio_augmentations.RandomResizedCrop",
"clmr.datasets.AUDIO",
"torchaudio_augmentations.Reverb",
"torchaudio_augmentations.PolarityInversion",
"torchaudio_augmentations.Noise",
"torchaudio_augmentations.Delay",
"torchaudio_augmentations.PitchShift",
"torchaudio_augmentation... | [((1051, 1081), 'clmr.datasets.AUDIO', 'AUDIO', (['"""./tests/data/audioset"""'], {}), "('./tests/data/audioset')\n", (1056, 1081), False, 'from clmr.datasets import AUDIO\n'), ((1423, 1499), 'torchaudio.save', 'torchaudio.save', (['"""augmented_sample.wav"""', 'audio'], {'sample_rate': 'self.sample_rate'}), "('augment... |
import os
import threading
import logging
log = logging.getLogger('testutils.py')
try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import ConfigParser
from stomp import StatsListener, WaitingListener
from stomp.backward import *
config = ConfigParser()
config.read(os.path.jo... | [
"ConfigParser.ConfigParser",
"logging.getLogger",
"stomp.StatsListener.__init__",
"os.path.dirname",
"stomp.WaitingListener.__init__",
"threading.Condition",
"stomp.StatsListener.on_error",
"stomp.StatsListener.on_message",
"threading.Thread"
] | [((48, 81), 'logging.getLogger', 'logging.getLogger', (['"""testutils.py"""'], {}), "('testutils.py')\n", (65, 81), False, 'import logging\n'), ((283, 297), 'ConfigParser.ConfigParser', 'ConfigParser', ([], {}), '()\n', (295, 297), False, 'from ConfigParser import ConfigParser\n'), ((323, 348), 'os.path.dirname', 'os.p... |
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free ... | [
"django.db.models.ForeignKey",
"django.db.models.IntegerField",
"django.db.models.ImageField",
"django_pgjsonb.JSONField",
"django.db.models.BigIntegerField",
"django.db.models.TextField",
"django.db.models.AutoField"
] | [((630, 664), 'django.db.models.AutoField', 'models.AutoField', ([], {'primary_key': '(True)'}), '(primary_key=True)\n', (646, 664), False, 'from django.db import models\n'), ((682, 717), 'django.db.models.BigIntegerField', 'models.BigIntegerField', ([], {'unique': '(True)'}), '(unique=True)\n', (704, 717), False, 'fro... |
# coding: utf-8
import os
import time
import csv
import itertools as itt
def CheckDir(*args):
paths = map(os.path.dirname, args)
for path in itt.ifilter(None, paths):
if not os.path.exists(path):
os.makedirs(path)
def Read(path, start=0, stop=None, step=None, mode='r'):
data = []
... | [
"itertools.islice",
"os.path.join",
"itertools.ifilter",
"csv.writer",
"os.path.exists",
"time.time",
"os.makedirs"
] | [((151, 175), 'itertools.ifilter', 'itt.ifilter', (['None', 'paths'], {}), '(None, paths)\n', (162, 175), True, 'import itertools as itt\n'), ((369, 401), 'itertools.islice', 'itt.islice', (['f', 'start', 'stop', 'step'], {}), '(f, start, stop, step)\n', (379, 401), True, 'import itertools as itt\n'), ((715, 749), 'csv... |
import json
from abc import ABC, abstractmethod
class JSONParser(ABC):
@abstractmethod
def get_model_class(self):
pass
@property
@abstractmethod
def parse_field_function_map(self):
pass
def parse_json(self, json_str):
json_object = json.loads(json_str)
field... | [
"json.loads"
] | [((286, 306), 'json.loads', 'json.loads', (['json_str'], {}), '(json_str)\n', (296, 306), False, 'import json\n')] |
from datetime import datetime
import sys, os
import argparse
parser = argparse.ArgumentParser(description='Create a file')
parser.add_argument('fname', metavar='N',
help='file name')
parser.add_argument('-d', dest='folder', help='folder')
args = parser.parse_args()
file = '%s-%s.md'%(datetime.tod... | [
"argparse.ArgumentParser",
"datetime.datetime.today",
"os.system",
"os.path.isfile"
] | [((71, 123), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Create a file"""'}), "(description='Create a file')\n", (94, 123), False, 'import argparse\n'), ((450, 470), 'os.path.isfile', 'os.path.isfile', (['file'], {}), '(file)\n', (464, 470), False, 'import sys, os\n'), ((574, 598), 'o... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# dphutils.py
"""
This is for small utility functions that don't have a proper home yet
Copyright (c) 2016, <NAME>
"""
import subprocess
import numpy as np
import scipy as sp
import re
import io
import os
import requests
import tifffile as tif
from scipy.fftpack.helper im... | [
"tqdm.trange",
"numpy.ones_like",
"numpy.asarray",
"numpy.round",
"scipy.stats.nbinom",
"numpy.vstack",
"pyfftw.interfaces.cache.enable",
"numpy.nanmin",
"numpy.sum",
"numpy.repeat",
"numpy.imag",
"numpy.fft.ifftn",
"numpy.zeros",
"numpy.log",
"numpy.concatenate",
"numpy.arange",
"sc... | [((1146, 1173), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1163, 1173), False, 'import logging\n'), ((958, 990), 'pyfftw.interfaces.cache.enable', 'pyfftw.interfaces.cache.enable', ([], {}), '()\n', (988, 990), False, 'import pyfftw\n'), ((1181, 1196), 'numpy.finfo', 'np.finfo', (['f... |
"""
日本のコロナ感染者数を可視化するサンプルコード
https://docs.streamlit.io/en/stable/api.html#display-data の公式ドキュメント見ながらつくった
"""
import io
import datetime
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# streamlitの警告を非表示にする
st.set_option("deprecation.showfileUploaderEnco... | [
"datetime.date",
"streamlit.write",
"streamlit.sidebar.text_area",
"streamlit.balloons",
"streamlit.sidebar.file_uploader",
"datetime.date.today",
"pandas.crosstab",
"streamlit.checkbox",
"pandas.read_csv",
"streamlit.set_option",
"streamlit.sidebar.selectbox",
"streamlit.text",
"streamlit.s... | [((273, 333), 'streamlit.set_option', 'st.set_option', (['"""deprecation.showfileUploaderEncoding"""', '(False)'], {}), "('deprecation.showfileUploaderEncoding', False)\n", (286, 333), True, 'import streamlit as st\n'), ((522, 561), 'streamlit.title', 'st.title', (['"""Coronavirus Trends in Japan"""'], {}), "('Coronavi... |
from flask import Flask, jsonify, request, render_template,session,redirect,url_for,flash,Blueprint
import os
import re
import json
# line bot 相關元件
from linebot import LineBotApi
from linebot.models import *
from linebot.exceptions import LineBotApiError
# Model
from data_model.manager import *
from data_model.channel ... | [
"flask.session.get",
"linebot.LineBotApi",
"flask.Blueprint",
"flask.request.values.get",
"flask.request.get_json"
] | [((494, 524), 'flask.Blueprint', 'Blueprint', (['"""api_sys"""', '__name__'], {}), "('api_sys', __name__)\n", (503, 524), False, 'from flask import Flask, jsonify, request, render_template, session, redirect, url_for, flash, Blueprint\n'), ((697, 722), 'flask.session.get', 'session.get', (['"""manager_id"""'], {}), "('... |
import numpy as np
import matplotlib.pyplot as plt
import csv
#PATH1 = '/Users/alihanks/Google Drive/NQUAKE_analysis/PERM/PERM_data/lbnl_sensor_60.csv'
PATH1 = '/Users/alihanks/k40_test_2019-02-06_D3S.csv'
def make_int(lst):
'''
Makes all entries of a list an integer
'''
y = []
for i in lst:
y.app... | [
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.yscale",
"matplotlib.pyplot.show",
"matplotlib.pyplot.xlim",
"numpy.sqrt",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.title",
"csv.reader"
] | [((2569, 2582), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (2579, 2582), False, 'import csv\n'), ((1499, 1513), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1511, 1513), True, 'import matplotlib.pyplot as plt\n'), ((1555, 1580), 'matplotlib.pyplot.title', 'plt.title', (['"""PERM Spectra"""'],... |
from collections import defaultdict
from configparser import ConfigParser
import re
import simplejson
# Function for reading configuration
def config_reader(config, section):
"""
Reading configuration file
Input :
- config (str) : path to the configuration file
- section (str) : section to ... | [
"simplejson.JSONDecoder",
"collections.defaultdict",
"configparser.ConfigParser",
"re.compile"
] | [((740, 774), 're.compile', 're.compile', (['"""[ \\\\t\\\\n\\\\r]*"""', 'FLAGS'], {}), "('[ \\\\t\\\\n\\\\r]*', FLAGS)\n", (750, 774), False, 'import re\n'), ((444, 458), 'configparser.ConfigParser', 'ConfigParser', ([], {}), '()\n', (456, 458), False, 'from configparser import ConfigParser\n'), ((918, 942), 'simplejs... |
# -*- coding: UTF-8 -*-
"""Misc. work"""
import os
import utils
import ml_tools
import numpy as np
import pandas as pd
def get_psd_rois():
ipsd_comp_file = './results/infraslow_PSD_model_comparison.xlsx'
ipsd_comp = utils.load_xls(ipsd_comp_file)
psd_rois, algorithm = ml_tools.pick_algorithm(ipsd_comp)
... | [
"os.path.join",
"ml_tools.pick_algorithm",
"os.listdir",
"utils.load_phase_amp_coupling",
"os.path.isdir",
"os.path.abspath",
"utils.load_xls",
"utils.load_phase_phase_coupling",
"utils.create_custom_roi",
"os.mkdir",
"pandas.read_excel",
"numpy.max",
"utils.nice_perf_df_v1",
"utils.plot_b... | [((226, 256), 'utils.load_xls', 'utils.load_xls', (['ipsd_comp_file'], {}), '(ipsd_comp_file)\n', (240, 256), False, 'import utils\n'), ((283, 317), 'ml_tools.pick_algorithm', 'ml_tools.pick_algorithm', (['ipsd_comp'], {}), '(ipsd_comp)\n', (306, 317), False, 'import ml_tools\n'), ((468, 508), 'utils.load_phase_amp_cou... |
# -*- coding: utf-8 -*-
import importlib
import numbers
from ..adapter.oleacc_h import ROLE_SYSTEM, ROLE_SYSTEM_rev
class RegisteredControlClasses:
"""
TODO: Improme registration machinery and criteria structure.
"""
_by_class_name = {}
_by_control_type = {}
_by_legacy_role = {}
@class... | [
"importlib.import_module"
] | [((1939, 2013), 'importlib.import_module', 'importlib.import_module', (['module_loc'], {'package': '"""pikuli.uia.control_wrappers"""'}), "(module_loc, package='pikuli.uia.control_wrappers')\n", (1962, 2013), False, 'import importlib\n')] |
import csv
import json
import time
from os import path
base_dir = path.dirname(path.realpath('__file__'))
def csv_makedict(f_dir, f_name, k_col, v_col, enc):
with open(path.join(f_dir, f_name), mode='r', encoding=enc) as csv_input:
csv_read = csv.reader(csv_input)
csv_dict = {rows[k_col]: rows[v_... | [
"os.path.join",
"json.dump",
"os.path.realpath",
"time.time",
"csv.reader"
] | [((80, 105), 'os.path.realpath', 'path.realpath', (['"""__file__"""'], {}), "('__file__')\n", (93, 105), False, 'from os import path\n'), ((258, 279), 'csv.reader', 'csv.reader', (['csv_input'], {}), '(csv_input)\n', (268, 279), False, 'import csv\n'), ((608, 649), 'json.dump', 'json.dump', (['data_input', 'f_output'],... |
import logging
# from logging__.foo import foo2
from rich.logging import RichHandler
if __name__ == '__main__':
use_rich_handler = True
logging.basicConfig(filename=r'D:\some_log.log',
filemode="w",
format='%(levelname)s\t%(message)s\t%(asctime)s\t%(pathn... | [
"logging.getLogger",
"logging.warning",
"logging.exception",
"rich.logging.RichHandler",
"logging.basicConfig",
"logging.StreamHandler",
"logging.debug",
"logging.info"
] | [((151, 324), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': '"""D:\\\\some_log.log"""', 'filemode': '"""w"""', 'format': '"""%(levelname)s\t%(message)s\t%(asctime)s\t%(pathname)s\tLine:%(lineno)d"""', 'level': 'logging.DEBUG'}), "(filename='D:\\\\some_log.log', filemode='w', format=\n '%(levelname)... |
from typing import List, Optional
from overrides import overrides
import spacy
import ftfy
from pytorch_pretrained_bert.tokenization import BasicTokenizer as BertTokenizer
from allennlp.common.util import get_spacy_model
from allennlp.data.tokenizers.token import Token
from allennlp.data.tokenizers.tokenizer import T... | [
"allennlp.data.tokenizers.token.Token",
"pytorch_pretrained_bert.tokenization.BasicTokenizer",
"ftfy.fix_text",
"allennlp.common.util.get_spacy_model",
"allennlp.data.tokenizers.tokenizer.Tokenizer.register"
] | [((427, 455), 'allennlp.data.tokenizers.tokenizer.Tokenizer.register', 'Tokenizer.register', (['"""openai"""'], {}), "('openai')\n", (445, 455), False, 'from allennlp.data.tokenizers.tokenizer import Tokenizer\n'), ((1416, 1448), 'allennlp.data.tokenizers.tokenizer.Tokenizer.register', 'Tokenizer.register', (['"""bert-... |
#######################################################################
# This file is part of Pyblosxom.
#
# Copyright (C) 2010-2011 by the Pyblosxom team. See AUTHORS.
#
# Pyblosxom is distributed under the MIT license. See the file
# LICENSE for distribution details.
###############################################... | [
"os.path.join",
"os.path.dirname",
"Pyblosxom.tests.PluginTest.setUp",
"Pyblosxom.plugins.pycategories.cb_prepare",
"Pyblosxom.tests.PluginTest.tearDown"
] | [((610, 646), 'Pyblosxom.tests.PluginTest.setUp', 'PluginTest.setUp', (['self', 'pycategories'], {}), '(self, pycategories)\n', (626, 646), False, 'from Pyblosxom.tests import PluginTest, TIMESTAMP\n'), ((748, 773), 'Pyblosxom.tests.PluginTest.tearDown', 'PluginTest.tearDown', (['self'], {}), '(self)\n', (767, 773), Fa... |
import csv
import os
import os.path as osp
import torch as to
from abc import ABC, abstractmethod
from contextlib import contextmanager
from tabulate import tabulate
import pyrado
from pyrado.logger import resolve_log_path
class StepLogger:
"""
Step-based progress logger.
This class collects progress val... | [
"os.path.join",
"tabulate.tabulate",
"os.path.dirname",
"pyrado.ShapeErr",
"csv.writer",
"pyrado.logger.resolve_log_path"
] | [((4672, 4701), 'os.path.join', 'osp.join', (['save_dir', 'file_name'], {}), '(save_dir, file_name)\n', (4680, 4701), True, 'import os.path as osp\n'), ((5439, 5506), 'tabulate.tabulate', 'tabulate', (['[(k, values[k]) for k in ordered_keys]'], {'tablefmt': '"""simple"""'}), "([(k, values[k]) for k in ordered_keys], ta... |
# three_charts.py
#
# CHART 1 (PIE)
#
pie_data = [
{"company": "Company X", "market_share": 0.55},
{"company": "Company Y", "market_share": 0.30},
{"company": "Company Z", "market_share": 0.15}
]
print("----------------")
print("GENERATING PIE CHART...")
print(pie_data) # TODO: create a pie chart based o... | [
"plotly.graph_objects.Bar",
"plotly.graph_objects.Scatter",
"plotly.offline.plot",
"plotly.graph_objects.Layout",
"plotly.graph_objects.Pie"
] | [((1713, 1749), 'plotly.graph_objects.Pie', 'go.Pie', ([], {'labels': 'labels', 'values': 'values'}), '(labels=labels, values=values)\n', (1719, 1749), True, 'import plotly.graph_objects as go\n'), ((1751, 1828), 'plotly.offline.plot', 'plotly.offline.plot', (['[trace]'], {'filename': '"""basic_pie_chart.html"""', 'aut... |
import numpy as np
from scipy.integrate import odeint
class simulation:
def __init__(self, t):
self.t = t
self.ix = {}
self.flows = {}
self.current = []
self.done = False
self.results = None
def __getattr__(self,key):
if not self.done: return self.current[self.ix[key]]
else: return... | [
"scipy.integrate.odeint"
] | [((1392, 1431), 'scipy.integrate.odeint', 'odeint', (['self.xdot', 'self.current', 'self.t'], {}), '(self.xdot, self.current, self.t)\n', (1398, 1431), False, 'from scipy.integrate import odeint\n')] |
import os
import math
from utct.common.data_source_template import DataSourceTemplate
class MnistDataSourceTemplate(DataSourceTemplate):
def __init__(self,
use_augmentation=True,
data_h5_path=None):
super(MnistDataSourceTemplate, self).__init__(use_augmentation)
... | [
"os.path.join",
"os.path.exists",
"os.makedirs"
] | [((1407, 1450), 'os.path.join', 'os.path.join', (['project_dirname', '"""cache_data"""'], {}), "(project_dirname, 'cache_data')\n", (1419, 1450), False, 'import os\n'), ((1466, 1505), 'os.path.exists', 'os.path.exists', (['self.cache_data_dirname'], {}), '(self.cache_data_dirname)\n', (1480, 1505), False, 'import os\n'... |
import unittest
import os
import json
from languages import Language, filter_languages, open_json_language_file, create_languages_from_json_data, get_google_translate_languages, get_google_play_languages
class LanguageMatcher:
expected: Language
def __init__(self, expected):
self.expected = expected
def __rep... | [
"languages.open_json_language_file",
"languages.filter_languages",
"languages.Language",
"languages.get_google_play_languages",
"languages.get_google_translate_languages",
"json.loads",
"os.remove",
"languages.create_languages_from_json_data"
] | [((921, 960), 'languages.Language', 'Language', (['""" Test Language """', '""" tl """'], {}), "(' Test Language ', ' tl ')\n", (929, 960), False, 'from languages import Language, filter_languages, open_json_language_file, create_languages_from_json_data, get_google_translate_languages, get_google_play_language... |
try:
from functools import lru_cache
except ImportError:
from backports.functools_lru_cache import lru_cache
try:
from collections import ChainMap
except ImportError:
from chainmap import ChainMap
from pyecore.resources.json import JsonResource
from . import eClassifiers, datasources, types, values, var... | [
"backports.functools_lru_cache.lru_cache",
"chainmap.ChainMap"
] | [((564, 583), 'chainmap.ChainMap', 'ChainMap', (['*packages'], {}), '(*packages)\n', (572, 583), False, 'from chainmap import ChainMap\n'), ((658, 669), 'backports.functools_lru_cache.lru_cache', 'lru_cache', ([], {}), '()\n', (667, 669), False, 'from backports.functools_lru_cache import lru_cache\n')] |
import pickle
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import tensorflow as tf
matplotlib.use('svg')
new_rc_params = {
"font.family": 'Times',
"font.size": 12,
"font.serif": [],
"svg.fonttype": 'none'}
matplotlib.rcParams.update(new_rc_params)
np.random.seed(1)
n_obs_pts... | [
"matplotlib.rcParams.update",
"numpy.shape",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"numpy.random.seed",
"matplotlib.use",
"numpy.exp",
"numpy.sin"
] | [((110, 131), 'matplotlib.use', 'matplotlib.use', (['"""svg"""'], {}), "('svg')\n", (124, 131), False, 'import matplotlib\n'), ((249, 290), 'matplotlib.rcParams.update', 'matplotlib.rcParams.update', (['new_rc_params'], {}), '(new_rc_params)\n', (275, 290), False, 'import matplotlib\n'), ((292, 309), 'numpy.random.seed... |
from django.shortcuts import render
# Create your views here.
# http://www.airnowapi.org/aq/forecast/zipCode/?format=application/json&zipCode=20002&date=2020-01-19&distance=25&API_KEY=<KEY>
def home(request):
import json
import requests
if request.method == 'POST':
zipcode = request.POST['zipcode']
api_req... | [
"json.loads",
"django.shortcuts.render",
"requests.get"
] | [((4384, 4417), 'django.shortcuts.render', 'render', (['request', '"""about.html"""', '{}'], {}), "(request, 'about.html', {})\n", (4390, 4417), False, 'from django.shortcuts import render\n'), ((327, 472), 'requests.get', 'requests.get', (["(\n 'http://www.airnowapi.org/aq/forecast/zipCode/?format=application/json&... |
import zmq
def zmq_s():
try:
print('s')
context = zmq.Context()
subscriber = context.socket(zmq.SUB)
subscriber.bind("ipc://test")
subscriber.setsockopt(zmq.SUBSCRIBE, b'')
while 1:
print(subscriber.recv())
except Exception as e:
print(e)
zm... | [
"zmq.Context"
] | [((72, 85), 'zmq.Context', 'zmq.Context', ([], {}), '()\n', (83, 85), False, 'import zmq\n')] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.