code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import behave
@behave.when(u"I list triggers")
def step_impl(context):
context.trigger_list = context.service.triggers.list()
@behave.then(u'I receive a Trigger list of "{count}" objects')
def step_impl(context, count):
assert context.trigger_list.items_count == int(count)
if int(count) > 0:
for... | [
"behave.when",
"behave.then"
] | [((17, 48), 'behave.when', 'behave.when', (['u"""I list triggers"""'], {}), "(u'I list triggers')\n", (28, 48), False, 'import behave\n'), ((135, 196), 'behave.then', 'behave.then', (['u"""I receive a Trigger list of "{count}" objects"""'], {}), '(u\'I receive a Trigger list of "{count}" objects\')\n', (146, 196), Fals... |
# Combinatoric selections
# https://projecteuler.net/problem=53
from collections import defaultdict
from copy import deepcopy
from itertools import permutations
from math import fmod, sqrt, factorial
from time import time
start = time()
f = [factorial(i) for i in range(101)]
ans = 0
for n in range(1, 101):
for r... | [
"math.factorial",
"time.time"
] | [((232, 238), 'time.time', 'time', ([], {}), '()\n', (236, 238), False, 'from time import time\n'), ((245, 257), 'math.factorial', 'factorial', (['i'], {}), '(i)\n', (254, 257), False, 'from math import fmod, sqrt, factorial\n'), ((411, 417), 'time.time', 'time', ([], {}), '()\n', (415, 417), False, 'from time import t... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.animation as animation
class animacija2D:
def __init__(self, f, xInterval, yInterval, fN=20):
""" Priprava grafa in skiciranje funkcije. """
self.f = f
self.xlim = xInterval
self.ylim = y... | [
"numpy.amin",
"numpy.linspace",
"matplotlib.pyplot.figure",
"numpy.zeros",
"numpy.meshgrid",
"numpy.amax",
"matplotlib.pyplot.show"
] | [((386, 429), 'numpy.linspace', 'np.linspace', (['self.xlim[0]', 'self.xlim[1]', '(30)'], {}), '(self.xlim[0], self.xlim[1], 30)\n', (397, 429), True, 'import numpy as np\n'), ((442, 485), 'numpy.linspace', 'np.linspace', (['self.ylim[0]', 'self.ylim[1]', '(30)'], {}), '(self.ylim[0], self.ylim[1], 30)\n', (453, 485), ... |
'''
本模块用于数据预处理
This module is used for data preproccessing
'''
import numpy as np
from maysics.utils import e_distances
from matplotlib import pyplot as plt
plt.rcParams['font.sans-serif'] = ['FangSong']
plt.rcParams['axes.unicode_minus'] = False
from io import BytesIO
from lxml import etree
import base64
import math
... | [
"numpy.random.get_state",
"numpy.random.set_state",
"numpy.hstack",
"base64.b64encode",
"io.BytesIO",
"numpy.ascontiguousarray",
"maysics.utils.e_distances",
"numpy.array",
"numpy.argsort",
"lxml.etree.HTML",
"numpy.cov",
"lxml.etree.ElementTree",
"IPython.core.display.HTML",
"matplotlib.p... | [((350, 361), 'numpy.cov', 'np.cov', (['arg'], {}), '(arg)\n', (356, 361), True, 'import numpy as np\n'), ((647, 674), 'numpy.array', 'np.array', (['data'], {'dtype': 'float'}), '(data, dtype=float)\n', (655, 674), True, 'import numpy as np\n'), ((1968, 1996), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['data.... |
import requests
from bs4 import BeautifulSoup
from time import sleep
headers = {
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
}
def parse(url):
print('Parsing..' + url)
return 'Parsed..' + url
def pull(category_... | [
"bs4.BeautifulSoup",
"time.sleep",
"requests.get"
] | [((434, 488), 'requests.get', 'requests.get', (['category_url'], {'headers': 'headers', 'timeout': '(5)'}), '(category_url, headers=headers, timeout=5)\n', (446, 488), False, 'import requests\n'), ((575, 602), 'bs4.BeautifulSoup', 'BeautifulSoup', (['html', '"""lxml"""'], {}), "(html, 'lxml')\n", (588, 602), False, 'fr... |
# -*- coding: utf-8 -*-
import os
import sys
import re
import settings
from auth.connector import TrelloConnector
from stats import summary
from stats.trelloboardconfiguration import TrelloBoardConfiguration
def extract_stats(configuration_file_path):
"""
Extract stats for a given configuration file that de... | [
"os.listdir",
"auth.connector.TrelloConnector",
"stats.trelloboardconfiguration.TrelloBoardConfiguration.load_from_file",
"re.match",
"os.path.isfile",
"os.path.isdir",
"stats.summary.make"
] | [((468, 532), 'stats.trelloboardconfiguration.TrelloBoardConfiguration.load_from_file', 'TrelloBoardConfiguration.load_from_file', (['configuration_file_path'], {}), '(configuration_file_path)\n', (507, 532), False, 'from stats.trelloboardconfiguration import TrelloBoardConfiguration\n'), ((537, 582), 'stats.summary.ma... |
"""Convenience file to help start the game when the repo is cloned from git rather than installed via pip
This was required as we needed to run the script from the same level as the housie/ package in order for the imports
to work correctly.
"""
from housie.game import display_main_menu
display_main_menu()
| [
"housie.game.display_main_menu"
] | [((290, 309), 'housie.game.display_main_menu', 'display_main_menu', ([], {}), '()\n', (307, 309), False, 'from housie.game import display_main_menu\n')] |
import json
import sys
import urllib.parse
import urllib.request
import os
import zipfile
import io
import csv
import re
from html.parser import HTMLParser
code_list = {}
with open('data/codepoints.csv') as f:
reader = csv.reader(f)
for row in reader:
d1,d2,d3 = row[0].split('-')
d1 = int(d1)
... | [
"re.sub",
"io.TextIOWrapper",
"csv.reader",
"re.search"
] | [((224, 237), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (234, 237), False, 'import csv\n'), ((2722, 2779), 're.sub', 're.sub', (['"""<ruby><rb>(.*?)</rb>.*?</ruby>"""', '"""\\\\1"""', 'maintext'], {}), "('<ruby><rb>(.*?)</rb>.*?</ruby>', '\\\\1', maintext)\n", (2728, 2779), False, 'import re\n'), ((2994, 3048),... |
#!/usr/bin/env python
"""
setup.py file for SWIG Interface of Ext
"""
import os
import platform
import re
import subprocess
import sys
from distutils.version import LooseVersion
from os import walk
import numpy
import wget
from setuptools import Extension
from setuptools import setup, find_packages
from setuptools.co... | [
"numpy.get_numpy_include",
"wget.download",
"os.path.exists",
"re.compile",
"setuptools.setup",
"setuptools.Extension",
"platform.system",
"numpy.get_include",
"os.path.abspath"
] | [((2713, 2939), 'setuptools.Extension', 'Extension', (['"""EggNetExtension._EggNetExtension"""'], {'sources': 'source_files', 'include_dirs': 'include_dirs', 'swig_opts': "['-py3']", 'extra_compile_args': 'extra_args', 'extra_link_args': 'extra_link_args', 'depends': "['numpy']", 'optional': '(False)'}), "('EggNetExten... |
import discord
import subprocess
import os, random, re, requests, json
import asyncio
from datetime import datetime
from discord.ext import commands
class Economy(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print('[+] Trashmoney Code AC... | [
"discord.ext.commands.Cog.listener",
"asyncio.sleep",
"json.load",
"discord.ext.commands.cooldown",
"discord.ext.commands.command",
"json.dump"
] | [((236, 259), 'discord.ext.commands.Cog.listener', 'commands.Cog.listener', ([], {}), '()\n', (257, 259), False, 'from discord.ext import commands\n'), ((333, 383), 'discord.ext.commands.cooldown', 'commands.cooldown', (['(1)', '(60)', 'commands.BucketType.user'], {}), '(1, 60, commands.BucketType.user)\n', (350, 383),... |
from __future__ import absolute_import, unicode_literals
from celery import shared_task
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
import requests
import csv
@shared_task
def getStockQuote(room_group_name, stock_code):
url = 'https://stooq.com/q/l/?s=%s&f=sd2t2ohlcv&h&e=cs... | [
"requests.Session",
"asgiref.sync.async_to_sync",
"channels.layers.get_channel_layer"
] | [((333, 351), 'requests.Session', 'requests.Session', ([], {}), '()\n', (349, 351), False, 'import requests\n'), ((1047, 1066), 'channels.layers.get_channel_layer', 'get_channel_layer', ([], {}), '()\n', (1064, 1066), False, 'from channels.layers import get_channel_layer\n'), ((535, 574), 'asgiref.sync.async_to_sync', ... |
from jobbergate import appform
def mainflow(data):
return [appform.Const("val", default=10)]
| [
"jobbergate.appform.Const"
] | [((65, 97), 'jobbergate.appform.Const', 'appform.Const', (['"""val"""'], {'default': '(10)'}), "('val', default=10)\n", (78, 97), False, 'from jobbergate import appform\n')] |
# -*- coding: utf-8 -*-
import re
__author__ = 'luckydonald'
__all__ = [
'USERNAME_REGEX', '_USERNAME_REGEX', 'USER_AT_REGEX', '_USER_AT_REGEX',
'FULL_USERNAME_REGEX', '_FULL_USERNAME_REGEX'
]
_USERNAME_REGEX = '[a-zA-Z](?:[a-zA-Z0-9]|_(?!_)){3,30}[a-zA-Z0-9]' # https://regex101.com/r/nZdOHS/2
USERNAME_REGEX... | [
"re.compile"
] | [((323, 350), 're.compile', 're.compile', (['_USERNAME_REGEX'], {}), '(_USERNAME_REGEX)\n', (333, 350), False, 'import re\n'), ((426, 452), 're.compile', 're.compile', (['_USER_AT_REGEX'], {}), '(_USER_AT_REGEX)\n', (436, 452), False, 'import re\n'), ((645, 677), 're.compile', 're.compile', (['_FULL_USERNAME_REGEX'], {... |
from datetime import datetime, timedelta
import pytest
from django.test import TestCase
from tests.models import Org, Sub, Widget
data_org = {"name": "Acme Widgets"}
class FieldTestCase(TestCase):
def setUp(self):
self.org = Org.objects.create(**data_org)
self.created = datetime.now()
s... | [
"datetime.datetime.now",
"datetime.timedelta",
"tests.models.Org.objects.create"
] | [((242, 272), 'tests.models.Org.objects.create', 'Org.objects.create', ([], {}), '(**data_org)\n', (260, 272), False, 'from tests.models import Org, Sub, Widget\n'), ((296, 310), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (308, 310), False, 'from datetime import datetime, timedelta\n'), ((334, 354), 'da... |
from flask import Flask, render_template, request, redirect, url_for, Markup, \
flash # Imports Flask and all required modules
import databasemanager # Provides the functionality to load stuff from the database
app = Flask(__name__)
import errormanager # Enum for types of errors
# DECLARE datamanager as... | [
"flask.render_template",
"flask.url_for",
"flask.Flask"
] | [((228, 243), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (233, 243), False, 'from flask import Flask, render_template, request, redirect, url_for, Markup, flash\n'), ((718, 812), 'flask.render_template', 'render_template', (['"""base.html"""'], {'entries': 'datamanager.entries', 'bFailure': '(False)', ... |
import scipy.sparse as ssp
import scipy.sparse.csgraph as csgraph
import networkx as nx
import pylab as pl
import pygraphviz as pgv
from itertools import product, chain
class DiGraph(ssp.lil_matrix):
"""
An implementation of a directed graph with a Sparse Matrix representation using Scipy's sparse module.
... | [
"networkx.NetworkXUnfeasible",
"scipy.sparse.csgraph.breadth_first_order",
"pylab.show",
"itertools.product",
"networkx.DiGraph",
"scipy.sparse.lil_matrix.copy",
"pygraphviz.AGraph"
] | [((6726, 6735), 'pylab.show', 'pl.show', ([], {}), '()\n', (6733, 6735), True, 'import pylab as pl\n'), ((6776, 6801), 'pygraphviz.AGraph', 'pgv.AGraph', ([], {'filename': 'path'}), '(filename=path)\n', (6786, 6801), True, 'import pygraphviz as pgv\n'), ((4114, 4139), 'scipy.sparse.lil_matrix.copy', 'ssp.lil_matrix.cop... |
##
## Software PI-Net: Pose Interacting Network for Multi-Person Monocular 3D Pose Estimation
## Copyright Inria and UPC
## Year 2021
## Contact : <EMAIL>
##
## The software PI-Net is provided under MIT License.
##
#used in train for skeleton input
import os
import os.path as osp
import numpy as np
import math
from ut... | [
"numpy.ones",
"utils.pose_utils.warp_coord_to_original",
"json.dump",
"os.path.join",
"pycocotools.coco.COCO",
"math.sqrt",
"numpy.max",
"numpy.array",
"numpy.concatenate",
"utils.pose_utils.pixel2cam"
] | [((1105, 1143), 'os.path.join', 'osp.join', (['cfg.data_dir', '"""MuCo"""', '"""data"""'], {}), "(cfg.data_dir, 'MuCo', 'data')\n", (1113, 1143), True, 'import os.path as osp\n'), ((2129, 2156), 'pycocotools.coco.COCO', 'COCO', (['self.train_annot_path'], {}), '(self.train_annot_path)\n', (2133, 2156), False, 'from pyc... |
import discord
import slash_util
class SampleCog(slash_util.Cog):
@slash_util.slash_command(guild_id=123)
async def pog(self, ctx: slash_util.Context):
await ctx.send("pog", ephemeral=True)
@slash_util.message_command(guild_id=123)
async def quote(self, ctx: slash_util.Context, message: discor... | [
"slash_util.slash_command",
"slash_util.user_command",
"slash_util.message_command"
] | [((72, 110), 'slash_util.slash_command', 'slash_util.slash_command', ([], {'guild_id': '(123)'}), '(guild_id=123)\n', (96, 110), False, 'import slash_util\n'), ((213, 253), 'slash_util.message_command', 'slash_util.message_command', ([], {'guild_id': '(123)'}), '(guild_id=123)\n', (239, 253), False, 'import slash_util\... |
# encoding=utf-8
# Elkatip
import os
import imp
# main class
class Elkatip():
api = None
gui = None
def __init__(self):
self.modulePath = os.path.dirname(__file__)
pass
def toExt(self, text):
if not self.api:
api = imp.load_source("api", self.modulePath + "/api.p... | [
"os.path.dirname",
"imp.load_source"
] | [((162, 187), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (177, 187), False, 'import os\n'), ((272, 323), 'imp.load_source', 'imp.load_source', (['"""api"""', "(self.modulePath + '/api.py')"], {}), "('api', self.modulePath + '/api.py')\n", (287, 323), False, 'import imp\n'), ((485, 536), '... |
from __future__ import absolute_import
from sklearn.exceptions import NotFittedError
from sklearn.neighbors import KernelDensity
from sklearn.linear_model import LinearRegression, LogisticRegression
import pickle
import os
import matplotlib.pylab as plt
from sklearn.externals import joblib
import numpy as np
from sklea... | [
"logging.getLogger",
"sklearn.exceptions.NotFittedError",
"numpy.log",
"matplotlib.pylab.show",
"os.path.exists",
"numpy.multiply",
"seaborn.distplot",
"sklearn.neighbors.KernelDensity",
"numpy.max",
"numpy.linspace",
"matplotlib.pylab.plot",
"matplotlib.pylab.xlabel",
"sklearn.linear_model.... | [((486, 591), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': '"""logfile.log"""', 'level': 'logging.DEBUG', 'format': 'logger_format', 'filemode': '"""w"""'}), "(filename='logfile.log', level=logging.DEBUG, format=\n logger_format, filemode='w')\n", (505, 591), False, 'import logging\n'), ((667, 694... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
# --1.2.1
class one_conv(nn.Module):
def __init__(self, in_ch, out_ch, normaliz=False):
super(one_conv, self).__init__()
ops = []
ops += [nn.Conv2d(in_ch, out_ch, 3, padding=1)]
# ops += [nn.... | [
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"math.ceil",
"torch.nn.Sequential",
"torch.nn.Conv2d",
"torch.nn.Upsample",
"torch.nn.functional.relu",
"torch.nn.ConvTranspose2d",
"torch.cat"
] | [((466, 485), 'torch.nn.Sequential', 'nn.Sequential', (['*ops'], {}), '(*ops)\n', (479, 485), True, 'import torch.nn as nn\n'), ((1156, 1175), 'torch.nn.Sequential', 'nn.Sequential', (['*ops'], {}), '(*ops)\n', (1169, 1175), True, 'import torch.nn as nn\n'), ((2063, 2082), 'torch.nn.Sequential', 'nn.Sequential', (['*op... |
"""
=========================================
Robust line model estimation using RANSAC
=========================================
In this example we see how to robustly fit a line model to faulty data using
the RANSAC (random sample consensus) algorithm.
Firstly the data are generated by adding a gaussian noise to a ... | [
"numpy.random.normal",
"numpy.sqrt",
"numpy.column_stack",
"skimage.measure.LineModelND",
"numpy.array",
"skimage.measure.ransac",
"matplotlib.pyplot.figure",
"numpy.random.seed",
"matplotlib.pyplot.subplots",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((1667, 1689), 'numpy.random.seed', 'np.random.seed', ([], {'seed': '(1)'}), '(seed=1)\n', (1681, 1689), True, 'import numpy as np\n'), ((1726, 1746), 'numpy.arange', 'np.arange', (['(-200)', '(200)'], {}), '(-200, 200)\n', (1735, 1746), True, 'import numpy as np\n'), ((1771, 1794), 'numpy.column_stack', 'np.column_st... |
from flask import Flask, request, jsonify
import os, sys
import helpers, escape_helpers
import logging
import config
from rdflib.namespace import Namespace
##############
# INIT CONFIG
##############
CONFIG = config.load_config(os.environ.get('ENVIRONMENT', "DEBUG"))
app = Flask(__name__)
handler = logging.StreamHan... | [
"helpers.session_id_header",
"logging.StreamHandler",
"helpers.query",
"flask.Flask",
"os.environ.get",
"rdflib.namespace.Namespace",
"escape_helpers.sparql_escape",
"flask.request.get_json",
"helpers.validate_json_api_content_type",
"helpers.validate_resource_type",
"helpers.error",
"helpers.... | [((276, 291), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (281, 291), False, 'from flask import Flask, request, jsonify\n'), ((303, 343), 'logging.StreamHandler', 'logging.StreamHandler', ([], {'stream': 'sys.stderr'}), '(stream=sys.stderr)\n', (324, 343), False, 'import logging\n'), ((434, 479), 'rdfli... |
"""
This file illustrates a few examples of using pgmock with pytest.
A postgres testing database from pytest-pgsql (https://github.com/CloverHealth/pytest-pgsql)
is used and a fixture is created for using the mock context manager. This is the
preferred way of using pgmock, but it's also possible to render SQL yoursel... | [
"pgmock.table",
"pgmock.subquery",
"pgmock.mock"
] | [((498, 546), 'pgmock.mock', 'pgmock.mock', (['transacted_postgresql_db.connection'], {}), '(transacted_postgresql_db.connection)\n', (509, 546), False, 'import pgmock\n'), ((754, 780), 'pgmock.table', 'pgmock.table', (['"""test_table"""'], {}), "('test_table')\n", (766, 780), False, 'import pgmock\n'), ((1384, 1406), ... |
# -*- coding: utf-8 -*-
__author__ = '<NAME> <<EMAIL>>'
import json
import BaseHTTPServer
import threading
from urlparse import parse_qs, urlparse
import status
callbacks = dict()
class JsonHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
print("path:", self.path)
if self.path ... | [
"urlparse.parse_qs",
"status.update",
"json.dumps",
"BaseHTTPServer.HTTPServer",
"urlparse.urlparse"
] | [((2795, 2847), 'BaseHTTPServer.HTTPServer', 'BaseHTTPServer.HTTPServer', (['self.address', 'JsonHandler'], {}), '(self.address, JsonHandler)\n', (2820, 2847), False, 'import BaseHTTPServer\n'), ((1823, 1839), 'json.dumps', 'json.dumps', (['data'], {}), '(data)\n', (1833, 1839), False, 'import json\n'), ((2119, 2138), ... |
from django.contrib.auth.models import Permission, Group
from rest_framework import viewsets, mixins, response, status
from rest_framework.generics import get_object_or_404
from .serializer import PermissionSerializer
from .common import get_permission_obj
from .filter import PermissionFilter
class PermissionsViews... | [
"django.contrib.auth.models.Permission.objects.all",
"rest_framework.response.Response",
"rest_framework.generics.get_object_or_404",
"django.contrib.auth.models.Group.objects.all"
] | [((428, 452), 'django.contrib.auth.models.Permission.objects.all', 'Permission.objects.all', ([], {}), '()\n', (450, 452), False, 'from django.contrib.auth.models import Permission, Group\n'), ((1081, 1105), 'django.contrib.auth.models.Permission.objects.all', 'Permission.objects.all', ([], {}), '()\n', (1103, 1105), F... |
'''
Module with helper classes to create new persistables
'''
from abc import ABCMeta, abstractmethod
from simpleml.persistables.meta_registry import SIMPLEML_REGISTRY
from simpleml.datasets.base_dataset import Dataset
from simpleml.pipelines.base_pipeline import Pipeline
from simpleml.models.base_model import Model
fr... | [
"logging.getLogger",
"simpleml.utils.errors.TrainingError",
"future.utils.with_metaclass",
"simpleml.persistables.meta_registry.SIMPLEML_REGISTRY.get"
] | [((479, 506), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (496, 506), False, 'import logging\n'), ((557, 588), 'future.utils.with_metaclass', 'with_metaclass', (['ABCMeta', 'object'], {}), '(ABCMeta, object)\n', (571, 588), False, 'from future.utils import with_metaclass\n'), ((3503, 3... |
#!/usr/bin/env python
"""Generates a poller file that will be used as input to runsinglehap.py, hapsequencer.py, runmultihap.py or
hapmultisequencer.py based on the files or rootnames listed user-specified list file.
USAGE
>>> python drizzlepac/haputils/make_poller_files.py <input filename> -[ost]
- input fil... | [
"os.path.exists",
"os.getenv",
"argparse.ArgumentParser",
"re.compile",
"os.getcwd",
"drizzlepac.haputils.poller_utils.determine_filter_name",
"sys.exit",
"astropy.io.fits.open"
] | [((10193, 10267), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Create a HAP SVM or MVM poller file"""'}), "(description='Create a HAP SVM or MVM poller file')\n", (10216, 10267), False, 'import argparse\n'), ((4926, 4949), 'astropy.io.fits.open', 'fits.open', (['fullfilepath'], {}), '(... |
import unittest
from ...scenes import Scene
class TestSceneMethods(unittest.TestCase):
def test_scene(self):
scene = Scene()
if __name__ == "__main__":
unittest.main()
| [
"unittest.main"
] | [((173, 188), 'unittest.main', 'unittest.main', ([], {}), '()\n', (186, 188), False, 'import unittest\n')] |
#!/usr/bin/evn python3
# coding=utf-8
import logging
import redis
from typing import Any
from conf import dev_conf as conf
from util import singleton
@singleton
class Config:
"""
根据指定的配置文件,把conf文件转换成字典
默认情况下使用 conf 中的配置
"""
def __init__(self):
self.config = conf
self.redis_db = N... | [
"redis.ConnectionPool",
"logging.error",
"redis.Redis"
] | [((1837, 1924), 'redis.ConnectionPool', 'redis.ConnectionPool', ([], {'host': "db_conf['host']", 'port': "db_conf['port']", 'db': "db_conf['db']"}), "(host=db_conf['host'], port=db_conf['port'], db=db_conf\n ['db'])\n", (1857, 1924), False, 'import redis\n'), ((2010, 2043), 'redis.Redis', 'redis.Redis', ([], {'conne... |
import json
import os
script_path = os.path.abspath(__file__)
script_dir = os.path.split(script_path)[0]
def get_config():
rel_path = 'resources/config.json'
path = os.path.join(script_dir, rel_path)
with open(path, 'r') as f:
config = json.loads(f.read())
return config
def get_submissions... | [
"os.path.abspath",
"json.dumps",
"os.path.join",
"os.path.split"
] | [((38, 63), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (53, 63), False, 'import os\n'), ((77, 103), 'os.path.split', 'os.path.split', (['script_path'], {}), '(script_path)\n', (90, 103), False, 'import os\n'), ((177, 211), 'os.path.join', 'os.path.join', (['script_dir', 'rel_path'], {}), ... |
from flask import g
from flask_socketio import SocketIO, emit
from logic.game_manager import GameManager
from logic.player_manager import PlayerManager
from logic.player_logic import PlayerLogic
from globals import socketio, db
from session import SessionHelper, SessionKeys
from utils.response import Response
from uti... | [
"globals.db.session.commit",
"utils.socketio_helper.commit_and_notify_if_dirty",
"globals.socketio.on",
"logic.player_manager.PlayerManager",
"globals.db.session.rollback",
"globals.db.session.remove",
"flask.g.game.set_dirty",
"logic.game_manager.GameManager",
"session.SessionHelper.has"
] | [((376, 401), 'globals.socketio.on', 'socketio.on', (['"""disconnect"""'], {}), "('disconnect')\n", (387, 401), False, 'from globals import socketio, db\n'), ((450, 472), 'globals.socketio.on', 'socketio.on', (['"""connect"""'], {}), "('connect')\n", (461, 472), False, 'from globals import socketio, db\n'), ((558, 598)... |
from django.contrib import admin
from .models import Rating
# Register your models here.
@admin.register(Rating)
class RatingAdmin(admin.ModelAdmin):
date_hierarchy = 'created_on'
search_fields = ['user_id__username', 'value']
list_display = ('user_id', 'value',)
list_filter = ('user_id', 'value', 'is... | [
"django.contrib.admin.register"
] | [((92, 114), 'django.contrib.admin.register', 'admin.register', (['Rating'], {}), '(Rating)\n', (106, 114), False, 'from django.contrib import admin\n')] |
import discpy
from discpy import commands
bot = commands.Bot(command_prefix='!')
# you can set "arg" keyword argument to the name of argument that represents the option in the command function
# and then change the option name as desired.
@bot.slash_command()
@discpy.application.option('sentence', arg='text', descrip... | [
"discpy.application.option",
"discpy.commands.Bot"
] | [((49, 81), 'discpy.commands.Bot', 'commands.Bot', ([], {'command_prefix': '"""!"""'}), "(command_prefix='!')\n", (61, 81), False, 'from discpy import commands\n'), ((263, 349), 'discpy.application.option', 'discpy.application.option', (['"""sentence"""'], {'arg': '"""text"""', 'description': '"""The text to say!"""'})... |
from huaweisms.api.common import get_from_url, ApiCtx
from .config import API_URL
def status(ctx: ApiCtx):
url = "{}/monitoring/status".format(API_URL)
return get_from_url(url, ctx)
| [
"huaweisms.api.common.get_from_url"
] | [((169, 191), 'huaweisms.api.common.get_from_url', 'get_from_url', (['url', 'ctx'], {}), '(url, ctx)\n', (181, 191), False, 'from huaweisms.api.common import get_from_url, ApiCtx\n')] |
"""add role
Revision ID: 221ccee39de7
Revises: <KEY>
Create Date: 2021-05-13 23:51:53.241485
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = "221ccee39de7"
down_revision = "<KEY>"
branch_labels = None
depends_on = None
... | [
"sqlalchemy.ForeignKeyConstraint",
"sqlalchemy.DateTime",
"alembic.op.drop_table",
"alembic.op.f",
"sqlalchemy.PrimaryKeyConstraint",
"sqlalchemy.dialects.postgresql.UUID",
"sqlalchemy.String"
] | [((1637, 1658), 'alembic.op.drop_table', 'op.drop_table', (['"""role"""'], {}), "('role')\n", (1650, 1658), False, 'from alembic import op\n'), ((926, 997), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['grade_id']", "['grade.id']"], {'ondelete': '"""CASCADE"""'}), "(['grade_id'], ['grade.id'], onde... |
#!/usr/bin/env python3
# coding: utf-8
# Copyright 2016 <NAME>, https://github.com/tywtyw2002, and https://github.com/treedust
#
# 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:/... | [
"urllib.parse.quote",
"socket.socket",
"sys.exit"
] | [((1257, 1306), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (1270, 1306), False, 'import socket\n'), ((4432, 4443), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (4440, 4443), False, 'import sys\n'), ((3413, 3425), 'urllib.parse.quote', '... |
"""Wrappers for the ophyd devices."""
from ophyd import Device, Signal
from ophyd import Kind
from ophyd.device import Component as Cpt
class CalibrationData(Device):
"""A device to hold pyFAI calibration data."""
dist = Cpt(Signal, value=1., kind=Kind.config)
poni1 = Cpt(Signal, value=0., kind=Kind.confi... | [
"ophyd.device.Component"
] | [((231, 271), 'ophyd.device.Component', 'Cpt', (['Signal'], {'value': '(1.0)', 'kind': 'Kind.config'}), '(Signal, value=1.0, kind=Kind.config)\n', (234, 271), True, 'from ophyd.device import Component as Cpt\n'), ((283, 323), 'ophyd.device.Component', 'Cpt', (['Signal'], {'value': '(0.0)', 'kind': 'Kind.config'}), '(Si... |
import numpy as np
import pytest
from sklearn.dummy import DummyRegressor
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from hcrystalball.metrics import get_scorer
from hcrystalball.model_selection import FinerTimeSplit
from hcrystalball.model_selection import get_best_not_fail... | [
"hcrystalball.model_selection.get_best_not_failing_model",
"pytest.mark.parametrize",
"hcrystalball.metrics.get_scorer",
"hcrystalball.wrappers.get_sklearn_wrapper",
"pytest.raises",
"sklearn.pipeline.Pipeline",
"hcrystalball.model_selection.FinerTimeSplit",
"hcrystalball.model_selection.select_model"... | [((503, 696), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""train_data, grid_search, parallel_over_dict"""', "[('two_regions', '', {'Region': 'region_0'}), ('two_regions', '', None)]"], {'indirect': "['train_data', 'grid_search']"}), "('train_data, grid_search, parallel_over_dict', [(\n 'two_regions', ... |
from squidpy.instrument import Instrument
import visa
class SR830(Instrument):
'''
Instrument driver for SR830
'''
def __init__(self, gpib_address='', name='SR830'):
self._units = {'amplitude': 'V', 'frequency': 'Hz'}
self._visa_handle = visa.ResourceManager().open_resource(gpib_address... | [
"visa.ResourceManager"
] | [((271, 293), 'visa.ResourceManager', 'visa.ResourceManager', ([], {}), '()\n', (291, 293), False, 'import visa\n')] |
import os
from logging.config import dictConfig
from typing import Optional
from flask import render_template, request, send_from_directory
from flask_babel import get_locale, lazy_gettext as _
from werkzeug.utils import ImportStringError
from .auth import auth_bp
from .comp import comp_bp
from .ext import babel, csr... | [
"flask.render_template",
"logging.config.dictConfig",
"flask.request.accept_languages.best_match",
"os.environ.get",
"os.path.join",
"flask_babel.lazy_gettext"
] | [((2384, 2422), 'flask_babel.lazy_gettext', '_', (['"""Please log in to access this page"""'], {}), "('Please log in to access this page')\n", (2385, 2422), True, 'from flask_babel import get_locale, lazy_gettext as _\n'), ((2689, 3011), 'logging.config.dictConfig', 'dictConfig', (["{'version': 1, 'formatters': {'defau... |
# -*- coding: utf-8 -*-
##############################################################################
##
## This file is part of Taurus
##
## http://taurus-scada.org
##
## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
## Taurus is free software: you can redistribute it and/or modify
## it under the te... | [
"unittest.main",
"taurus.setLogLevel",
"sys.modules.keys"
] | [((3628, 3654), 'unittest.main', 'unittest.main', ([], {'verbosity': '(2)'}), '(verbosity=2)\n', (3641, 3654), False, 'import unittest\n'), ((1172, 1207), 'taurus.setLogLevel', 'taurus.setLogLevel', (['taurus.Critical'], {}), '(taurus.Critical)\n', (1190, 1207), False, 'import taurus\n'), ((1433, 1451), 'sys.modules.ke... |
import os, pickle
import os.path as osp
import numpy as np
import cv2
import scipy.ndimage as nd
import init_path
from lib.dataset.get_dataset import get_dataset
from lib.network.sgan import SGAN
import torch
from torch.utils.data import DataLoader
import argparse
from ipdb import set_trace
import matplotlib.pyplot as... | [
"torch.from_numpy",
"numpy.argsort",
"numpy.array",
"scipy.ndimage.zoom",
"os.path.exists",
"argparse.ArgumentParser",
"numpy.where",
"numpy.max",
"os.mkdir",
"lib.network.sgan.SGAN",
"numpy.ones",
"numpy.argmax",
"torch.device",
"os.makedirs",
"os.path.join",
"numpy.sum",
"numpy.zer... | [((922, 959), 'numpy.array', 'np.array', (['[104.008, 116.669, 122.675]'], {}), '([104.008, 116.669, 122.675])\n', (930, 959), True, 'import numpy as np\n'), ((686, 711), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (709, 711), False, 'import argparse\n'), ((816, 852), 'lib.utils.pyutils.read... |
import os
import shutil
from shapely.geometry import Polygon
from .. import osm_create_maps
from .. import util
TEST_FP = os.path.dirname(os.path.abspath(__file__))
def test_get_width():
assert osm_create_maps.get_width('15.2') == 15
assert osm_create_maps.get_width('') == 0
assert osm_create_maps.get_wi... | [
"os.path.abspath",
"shapely.geometry.Polygon",
"os.path.join",
"shutil.copy"
] | [((139, 164), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (154, 164), False, 'import os\n'), ((709, 784), 'shutil.copy', 'shutil.copy', (["(TEST_FP + '/data/processed/maps/osm_elements.geojson')", 'tmppath'], {}), "(TEST_FP + '/data/processed/maps/osm_elements.geojson', tmppath)\n", (720, ... |
import unittest
import numpy as np
import tensorflow as tf
from megnet.losses import mean_squared_error_with_scale
class TestLosses(unittest.TestCase):
def test_mse(self):
x = np.array([0.1, 0.2, 0.3])
y = np.array([0.05, 0.15, 0.25])
loss = mean_squared_error_with_scale(x, y, scale=100)... | [
"unittest.main",
"numpy.array",
"numpy.mean",
"megnet.losses.mean_squared_error_with_scale"
] | [((428, 443), 'unittest.main', 'unittest.main', ([], {}), '()\n', (441, 443), False, 'import unittest\n'), ((192, 217), 'numpy.array', 'np.array', (['[0.1, 0.2, 0.3]'], {}), '([0.1, 0.2, 0.3])\n', (200, 217), True, 'import numpy as np\n'), ((230, 258), 'numpy.array', 'np.array', (['[0.05, 0.15, 0.25]'], {}), '([0.05, 0... |
import datetime
import requests
import socket
import random
import sys
import time
def now():
a=datetime.fromtimestamp(time.time())
return a.strftime("%H:%M:%S %Y-%m-%d")
def getmyip():
a=requests.get('http://checkip.dyndns.org')
a=a.content
b=a[76:89]
return b
class node:
def __init__... | [
"random.random",
"time.time",
"requests.get"
] | [((202, 243), 'requests.get', 'requests.get', (['"""http://checkip.dyndns.org"""'], {}), "('http://checkip.dyndns.org')\n", (214, 243), False, 'import requests\n'), ((124, 135), 'time.time', 'time.time', ([], {}), '()\n', (133, 135), False, 'import time\n'), ((361, 372), 'time.time', 'time.time', ([], {}), '()\n', (370... |
#!/usr/bin/python
import RPi.GPIO as GPIO
from picamera import PiCamera
import time
import datetime
PIN = 12
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN, GPIO.IN)
camera = PiCamera()
camera.rotation = 180
camera.resolution = (1024, 576)
#camera.start_preview()
#sleep(20)
#camera.stop_preview()
while True:
time.s... | [
"datetime.datetime.fromtimestamp",
"RPi.GPIO.setup",
"picamera.PiCamera",
"time.sleep",
"RPi.GPIO.input",
"time.time",
"RPi.GPIO.setmode"
] | [((113, 135), 'RPi.GPIO.setmode', 'GPIO.setmode', (['GPIO.BCM'], {}), '(GPIO.BCM)\n', (125, 135), True, 'import RPi.GPIO as GPIO\n'), ((136, 160), 'RPi.GPIO.setup', 'GPIO.setup', (['PIN', 'GPIO.IN'], {}), '(PIN, GPIO.IN)\n', (146, 160), True, 'import RPi.GPIO as GPIO\n'), ((171, 181), 'picamera.PiCamera', 'PiCamera', (... |
from django.conf import settings
from django.contrib.auth.models import User
from django.urls import reverse
from rest_framework.test import APITestCase
class BaseAPITest(APITestCase):
def setUp(self, password=None) -> None:
self.user = User(username="John Smith", email="<EMAIL>")
self.user.set_pa... | [
"django.contrib.auth.models.User",
"django.urls.reverse"
] | [((251, 295), 'django.contrib.auth.models.User', 'User', ([], {'username': '"""John Smith"""', 'email': '"""<EMAIL>"""'}), "(username='John Smith', email='<EMAIL>')\n", (255, 295), False, 'from django.contrib.auth.models import User\n'), ((523, 578), 'django.contrib.auth.models.User', 'User', ([], {'username': 'usernam... |
"""Core pytorch operations regarding optimization (optimize, schedule) are placed in general tests."""
import pytest
import torch
import torchtraining.pytorch as P
def test_backward():
backward = P.Backward()
x = torch.randn(10, requires_grad=True)
y = x ** 2
backward(y.sum())
assert x.grad is not... | [
"torch.randn",
"torchtraining.pytorch.Backward"
] | [((202, 214), 'torchtraining.pytorch.Backward', 'P.Backward', ([], {}), '()\n', (212, 214), True, 'import torchtraining.pytorch as P\n'), ((223, 258), 'torch.randn', 'torch.randn', (['(10)'], {'requires_grad': '(True)'}), '(10, requires_grad=True)\n', (234, 258), False, 'import torch\n')] |
"""
Emoji extras for Material.
Override the indexes with an extended version that includes short names for Material icons, FontAwesome, etc.
"""
import os
import glob
import copy
import codecs
import inspect
import material
import pymdownx
from pymdownx.emoji import TWEMOJI_SVG_CDN, add_attriubtes
import xml.etree.Ele... | [
"pymdownx.emoji.add_attriubtes",
"os.path.join",
"inspect.getfile",
"xml.etree.ElementTree.Element",
"copy.deepcopy",
"codecs.open"
] | [((437, 462), 'inspect.getfile', 'inspect.getfile', (['material'], {}), '(material)\n', (452, 462), False, 'import inspect\n'), ((922, 955), 'os.path.join', 'os.path.join', (['RESOURCES', '""".icons"""'], {}), "(RESOURCES, '.icons')\n", (934, 955), False, 'import os\n'), ((2434, 2469), 'pymdownx.emoji.add_attriubtes', ... |
import pigpio
import time
class OdomDist(object):
"""
Take a tick input from odometry and compute the distance travelled
"""
def __init__(self, mm_per_tick, debug=False):
self.mm_per_tick = mm_per_tick
self.m_per_tick = mm_per_tick / 1000.0
self.meters = 0
self.last_time... | [
"pigpio.pi",
"time.sleep",
"time.time"
] | [((2735, 2746), 'pigpio.pi', 'pigpio.pi', ([], {}), '()\n', (2744, 2746), False, 'import pigpio\n'), ((323, 334), 'time.time', 'time.time', ([], {}), '()\n', (332, 334), False, 'import time\n'), ((941, 952), 'time.time', 'time.time', ([], {}), '()\n', (950, 952), False, 'import time\n'), ((2800, 2815), 'time.sleep', 't... |
# coding: utf-8
import pprint
import re
import six
class ActionSmnForwarding:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the valu... | [
"six.iteritems"
] | [((4995, 5028), 'six.iteritems', 'six.iteritems', (['self.openapi_types'], {}), '(self.openapi_types)\n', (5008, 5028), False, 'import six\n')] |
"""Contains code that stitches together different parts of the library. By containing most side effects here the rest
of the code can be more deterministic and testable.
This code should not be unit tested.
"""
import os
from pathlib import Path
from typing import Union, List, Tuple, Dict, Optional
import yaml
from py... | [
"typhoon.introspection.introspect_extensions.get_typhoon_extensions_info",
"pathlib.Path",
"typhoon.core.dags.add_yaml_constructors",
"typhoon.core.settings.Settings.dags_directory.rglob",
"typhoon.core.dags.DAGDefinitionV2.parse_obj",
"typhoon.core.transpiler.task_transpiler.TasksFile",
"typhoon.core.t... | [((885, 909), 'pathlib.Path', 'Path', (['output_folder_path'], {}), '(output_folder_path)\n', (889, 909), False, 'from pathlib import Path\n'), ((978, 1008), 'typhoon.core.dags.DAGDefinitionV2.parse_obj', 'DAGDefinitionV2.parse_obj', (['dag'], {}), '(dag)\n', (1003, 1008), False, 'from typhoon.core.dags import DAGDefin... |
import os
import csv
import glob
import numpy as np
import pandas as pd
import nltk
import string
import re
from numpy import genfromtxt
from nltk import *
from nltk.corpus.reader.plaintext import PlaintextCorpusReader
from nltk import word_tokenize
from nltk.util import ngrams
from collections import Counter
def sta... | [
"pandas.DataFrame",
"glob.glob",
"pandas.read_csv"
] | [((433, 447), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (445, 447), True, 'import pandas as pd\n'), ((469, 483), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (481, 483), True, 'import pandas as pd\n'), ((499, 535), 'pandas.read_csv', 'pd.read_csv', (['pathToCSV'], {'dtype': 'object'}), '(pathToCSV,... |
import matplotlib.pyplot as plt
import numpy as np
def count_harmonic_numbers(n: int):
count = 0
for i in range(1, n+1): # 1 ~ N まで
for _ in range(i, n+1, i): # N以下の i の倍数
count += 1
return count
x = np.linspace(1, 10**5, 100, dtype='int')
y = list(map(lambda x: count_harmonic_numb... | [
"numpy.log",
"matplotlib.pyplot.plot",
"numpy.linspace",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show"
] | [((238, 279), 'numpy.linspace', 'np.linspace', (['(1)', '(10 ** 5)', '(100)'], {'dtype': '"""int"""'}), "(1, 10 ** 5, 100, dtype='int')\n", (249, 279), True, 'import numpy as np\n'), ((370, 399), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {'label': '"""count"""'}), "(x, y, label='count')\n", (378, 399), True, '... |
import pathlib
import numpy as np
def create_submission(path: pathlib.Path, predictions):
pred_with_id = np.stack([np.arange(len(predictions)), predictions], axis=1)
np.savetxt(
fname=path,
X=pred_with_id,
fmt="%d",
delimiter=",",
header="id,label",
comments=""... | [
"numpy.savetxt"
] | [((177, 277), 'numpy.savetxt', 'np.savetxt', ([], {'fname': 'path', 'X': 'pred_with_id', 'fmt': '"""%d"""', 'delimiter': '""","""', 'header': '"""id,label"""', 'comments': '""""""'}), "(fname=path, X=pred_with_id, fmt='%d', delimiter=',', header=\n 'id,label', comments='')\n", (187, 277), True, 'import numpy as np\n... |
import json
import urllib
import utils as ut
from distutils.util import strtobool
class Call(object):
"""docstring for Call"""
def __init__(self, currentStrike, currentPrice, currentProbOTM, currentIV, currentITM):
self.currentStrike = currentStrike
self.currentPrice = currentPrice
self.currentProbOTM = curr... | [
"json.loads",
"utils.formatExpiryURL",
"utils.calculateDelta",
"utils.truncateStrikes",
"urllib.urlopen"
] | [((961, 980), 'json.loads', 'json.loads', (['rawData'], {}), '(rawData)\n', (971, 980), False, 'import json\n'), ((1196, 1242), 'utils.truncateStrikes', 'ut.truncateStrikes', (['strikes', 'currentStockPrice'], {}), '(strikes, currentStockPrice)\n', (1214, 1242), True, 'import utils as ut\n'), ((846, 873), 'utils.format... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 20 17:12:53 2014
author: <NAME>
"""
import numpy as np
from statsmodels.regression.linear_model import OLS, WLS
from statsmodels.sandbox.regression.predstd import wls_prediction_std
def test_predict_se():
# this test doesn't use reference values
# checks conis... | [
"numpy.random.normal",
"statsmodels.sandbox.regression.predstd.wls_prediction_std",
"numpy.sqrt",
"numpy.ones",
"numpy.testing.assert_equal",
"statsmodels.regression.linear_model.WLS",
"numpy.testing.assert_allclose",
"numpy.testing.assert_raises",
"numpy.testing.assert_almost_equal",
"numpy.dot",... | [((427, 454), 'numpy.linspace', 'np.linspace', (['(0)', '(20)', 'nsample'], {}), '(0, 20, nsample)\n', (438, 454), True, 'import numpy as np\n'), ((508, 525), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (522, 525), True, 'import numpy as np\n'), ((587, 602), 'numpy.dot', 'np.dot', (['x', 'beta'], {})... |
import logging
import jsonpointer
import yadage.handlers.utils as utils
from yadage.handlers.expression_handlers import handlers as exprhandlers
log = logging.getLogger(__name__)
handlers, predicate = utils.handler_decorator()
def checkmeta(flowview, metainfo):
log.debug('checking meta %s on view with offset ... | [
"logging.getLogger",
"yadage.handlers.utils.handler_decorator",
"jsonpointer.JsonPointer"
] | [((154, 181), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (171, 181), False, 'import logging\n'), ((205, 230), 'yadage.handlers.utils.handler_decorator', 'utils.handler_decorator', ([], {}), '()\n', (228, 230), True, 'import yadage.handlers.utils as utils\n'), ((1163, 1193), 'jsonpoint... |
from pyspark.sql import SparkSession
spark = SparkSession.builder.master("local").appName('ReadParquet').config("spark.driver.host", "localhost").config(
"spark.ui.port", "4040").getOrCreate()
peopleDF = spark.read.json("people.json")
# DataFrames can be saved as Parquet files, maintaining the schema information... | [
"pyspark.sql.SparkSession.builder.master"
] | [((46, 82), 'pyspark.sql.SparkSession.builder.master', 'SparkSession.builder.master', (['"""local"""'], {}), "('local')\n", (73, 82), False, 'from pyspark.sql import SparkSession\n')] |
import os
from enum import Enum
import requests
from docker import ContextAPI
from docker.transport import UnixHTTPAdapter
from compose.const import IS_WINDOWS_PLATFORM
if IS_WINDOWS_PLATFORM:
from docker.transport import NpipeHTTPAdapter
class Status(Enum):
SUCCESS = "success"
FAILURE = "failure"
... | [
"docker.ContextAPI.get_current_context",
"os.environ.get",
"docker.transport.UnixHTTPAdapter",
"docker.transport.NpipeHTTPAdapter"
] | [((1100, 1158), 'os.environ.get', 'os.environ.get', (['"""METRICS_SOCKET_FILE"""', 'METRICS_SOCKET_FILE'], {}), "('METRICS_SOCKET_FILE', METRICS_SOCKET_FILE)\n", (1114, 1158), False, 'import os\n'), ((954, 986), 'docker.ContextAPI.get_current_context', 'ContextAPI.get_current_context', ([], {}), '()\n', (984, 986), Fal... |
# -*- coding: UTF-8 -*-
import time
import simplejson as json
from MySQLdb.connections import numeric_part
from django.contrib.auth.decorators import permission_required
from django.http import HttpResponse
from common.utils.extend_json_encoder import ExtendJSONEncoder
from common.utils.const import SQLTuning
from s... | [
"simplejson.dumps",
"django.contrib.auth.decorators.permission_required",
"MySQLdb.connections.numeric_part",
"time.time",
"sql.utils.dao.Dao",
"sqlparse.parse"
] | [((456, 523), 'django.contrib.auth.decorators.permission_required', 'permission_required', (['"""sql.optimize_sqltuning"""'], {'raise_exception': '(True)'}), "('sql.optimize_sqltuning', raise_exception=True)\n", (475, 523), False, 'from django.contrib.auth.decorators import permission_required\n'), ((2125, 2189), 'simp... |
from django.contrib import admin
from .models import Item
@admin.register(Item)
class ItemAdmin(admin.ModelAdmin):
fieldsets = [
('Item', {
'fields': [
'name',
'stock',
'description',
'thumbnail'
]
}),
(... | [
"django.contrib.admin.register"
] | [((60, 80), 'django.contrib.admin.register', 'admin.register', (['Item'], {}), '(Item)\n', (74, 80), False, 'from django.contrib import admin\n')] |
#!/usr/bin/python3
import sys
import os, os.path
import platform
import shutil
import time
import re
import difflib
import pickle
from subprocess import run, PIPE
from colorama import init, Fore, Back, Style
from statistics import median
# Globals
if platform.system() in ['Linux', 'Darwin']:
SYNQUID_CMD = ['stack'... | [
"pickle.dump",
"argparse.ArgumentParser",
"subprocess.run",
"re.match",
"difflib.unified_diff",
"os.path.isfile",
"statistics.median",
"platform.system",
"shutil.copy",
"time.time",
"sys.stdout.writelines",
"colorama.init",
"os.remove"
] | [((252, 269), 'platform.system', 'platform.system', ([], {}), '()\n', (267, 269), False, 'import platform\n'), ((21296, 21307), 'time.time', 'time.time', ([], {}), '()\n', (21305, 21307), False, 'import time\n'), ((21410, 21552), 'subprocess.run', 'run', (["(TIMEOUT_CMD + TIMEOUT + SYNQUID_CMD + COMMON_OPTS + variant_o... |
import sys
import signal
from clint.textui import colored, puts
from downloader import Downloader
from extractor import Extractor
signal.signal(signal.SIGINT, lambda x, y: sys.exit(0))
def main():
downloader = Downloader()
extractor = Extractor()
url = "https://pornhub.com"
puts(colored.green("getti... | [
"extractor.Extractor",
"sys.exit",
"clint.textui.colored.green",
"downloader.Downloader"
] | [((217, 229), 'downloader.Downloader', 'Downloader', ([], {}), '()\n', (227, 229), False, 'from downloader import Downloader\n'), ((246, 257), 'extractor.Extractor', 'Extractor', ([], {}), '()\n', (255, 257), False, 'from extractor import Extractor\n'), ((173, 184), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (181,... |
from cryptography.fernet import Fernet
import os
import discord
import aiohttp
import secrets
from urllib.parse import quote
from dotenv import load_dotenv
load_dotenv()
class OAuth:
def __init__(self):
# User Provided Data
self.client_id = os.getenv("CID")
self.client_secret = os.getenv("C... | [
"aiohttp.ClientSession",
"os.getenv",
"secrets.token_urlsafe",
"urllib.parse.quote",
"dotenv.load_dotenv",
"cryptography.fernet.Fernet",
"cryptography.fernet.Fernet.generate_key"
] | [((156, 169), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (167, 169), False, 'from dotenv import load_dotenv\n'), ((262, 278), 'os.getenv', 'os.getenv', (['"""CID"""'], {}), "('CID')\n", (271, 278), False, 'import os\n'), ((308, 324), 'os.getenv', 'os.getenv', (['"""CIS"""'], {}), "('CIS')\n", (317, 324), Fa... |
from __future__ import division
import numpy as np
def SoftmaxLoss2(w, X, y, k):
# w(feature*class,1) - weights for last class assumed to be 0
# X(instance,feature)
# y(instance,1)
#
# version of SoftmaxLoss where weights for last class are fixed at 0
# to avoid overparameterization
n, ... | [
"numpy.ravel",
"numpy.zeros",
"numpy.log"
] | [((509, 529), 'numpy.zeros', 'np.zeros', (['(p, k - 1)'], {}), '((p, k - 1))\n', (517, 529), True, 'import numpy as np\n'), ((684, 695), 'numpy.ravel', 'np.ravel', (['g'], {}), '(g)\n', (692, 695), True, 'import numpy as np\n'), ((384, 400), 'numpy.zeros', 'np.zeros', (['(p, 1)'], {}), '((p, 1))\n', (392, 400), True, '... |
# Copyright (c) <NAME> <<EMAIL>>
# See LICENSE file.
from os import path
def test_config(testing_config):
with testing_config() as config:
assert config.filename().endswith('rosshm.ini')
assert config.getbool('debug')
with testing_config(init = False):
config.init(fn = None)
assert config.getbool('debug')
... | [
"os.path.join"
] | [((551, 591), 'os.path.join', 'path.join', (['path.sep', '"""testing"""', '"""db.cfg"""'], {}), "(path.sep, 'testing', 'db.cfg')\n", (560, 591), False, 'from os import path\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 09 february, 2021
Testing suite for BNetwork class
@author: <NAME>
@email: <EMAIL>
@date: 09 february, 2021
"""
import unittest
import os
import numpy as np
from topopy import Flow, Basin, Network, BNetwork, DEM
from topopy.network import NetworkError
infol... | [
"topopy.BNetwork",
"os.remove",
"numpy.array",
"numpy.random.randint",
"numpy.array_equal",
"unittest.main",
"topopy.Basin"
] | [((6743, 6758), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6756, 6758), False, 'import unittest\n'), ((3650, 3684), 'topopy.BNetwork', 'BNetwork', (['net', 'cuencas', 'heads', 'bid'], {}), '(net, cuencas, heads, bid)\n', (3658, 3684), False, 'from topopy import Flow, Basin, Network, BNetwork, DEM\n'), ((4599,... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
def remove_useless_aliases(apps, schema_editor):
"""Remove aliases linked to disabled messages."""
ARmessage = apps.get_model("modoboa_postfix_autoreply", "ARmessage")
AliasRecipient = apps.get_model(... | [
"django.db.migrations.RunPython"
] | [((1001, 1045), 'django.db.migrations.RunPython', 'migrations.RunPython', (['remove_useless_aliases'], {}), '(remove_useless_aliases)\n', (1021, 1045), False, 'from django.db import migrations, models\n')] |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import xrange
from util import log
from pprint import pprint
from input_ops import create_input_ops
from model import Model
import os
import time
import tensorflow as tf
import tensorflow.contr... | [
"model.Model",
"datasets.synthia.create_default_splits",
"tensorflow.contrib.framework.get_or_create_global_step",
"six.moves.xrange",
"input_ops.create_input_ops",
"tensorflow.GPUOptions",
"pprint.pprint",
"util.log.warning",
"os.path.exists",
"argparse.ArgumentParser",
"numpy.asarray",
"tens... | [((10788, 10813), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (10811, 10813), False, 'import argparse\n'), ((16457, 16504), 'datasets.synthia.create_default_splits', 'dataset.create_default_splits', (['config.num_input'], {}), '(config.num_input)\n', (16486, 16504), True, 'import datasets.sy... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2020, NVIDIA CORPORATION. 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/li... | [
"apex.normalization.FusedLayerNorm",
"pyprof.init",
"pyprof.wrap",
"torch.randn"
] | [((761, 774), 'pyprof.init', 'pyprof.init', ([], {}), '()\n', (772, 774), False, 'import pyprof\n'), ((775, 820), 'pyprof.wrap', 'pyprof.wrap', (['fused_layer_norm_cuda', '"""forward"""'], {}), "(fused_layer_norm_cuda, 'forward')\n", (786, 820), False, 'import pyprof\n'), ((821, 867), 'pyprof.wrap', 'pyprof.wrap', (['f... |
import unittest
def merge_sort(arr):
def _merge(left, right):
merged_list = []
i, j = 0, 0
while len(left) > i and len(right) > j:
if left[i] < right[j]:
merged_list.append(left[i])
i += 1
else:
merged_list.append(righ... | [
"unittest.TestCase"
] | [((1541, 1560), 'unittest.TestCase', 'unittest.TestCase', ([], {}), '()\n', (1558, 1560), False, 'import unittest\n')] |
# coding: utf-8
from __future__ import print_function, unicode_literals, absolute_import
import cv2
from .base import BaseTestCase, root
try:
cv2.setNumThreads(1)
except AttributeError:
print('!!! You are using OpenCV which does not allow you to set '
'the number of threads')
class Cv2TestCase(... | [
"cv2.setNumThreads",
"cv2.cvtColor"
] | [((151, 171), 'cv2.setNumThreads', 'cv2.setNumThreads', (['(1)'], {}), '(1)\n', (168, 171), False, 'import cv2\n'), ((834, 870), 'cv2.cvtColor', 'cv2.cvtColor', (['im', 'cv2.COLOR_BGR2GRAY'], {}), '(im, cv2.COLOR_BGR2GRAY)\n', (846, 870), False, 'import cv2\n')] |
"""Librerias Importadas"""
from flask import Flask
from flask import render_template
from flask import request
App=Flask(__name__)
@App.route('/')
def index():
"""Pagina Principal en donde se introduce el nombre, apellido, comision"""
return render_template('index.html')
@App.route('/porcentaje',methods=... | [
"flask.render_template",
"flask.request.form.get",
"flask.Flask"
] | [((118, 133), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (123, 133), False, 'from flask import Flask\n'), ((255, 284), 'flask.render_template', 'render_template', (['"""index.html"""'], {}), "('index.html')\n", (270, 284), False, 'from flask import render_template\n'), ((1623, 1700), 'flask.render_temp... |
# Copyright 2018 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 a... | [
"absl.flags.DEFINE_integer",
"random.SystemRandom",
"absl.logging.debug"
] | [((871, 1195), 'absl.flags.DEFINE_integer', 'flags.DEFINE_integer', (['"""password_length"""', '_MAX', '"""The length of the password to be generated for the Grab n Go Role Account.\nNOTE: The length must be between 8 and 100 and must be compliant with the G Suite Admin password settings.\nThe Security Settings can be ... |
# -*- coding: utf-8 -*-
# Copyright 2015-2016 Telefónica Investigación y Desarrollo, S.A.U
#
# This file is part of FIWARE project.
#
# 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:
#
# htt... | [
"commons.utils.get_real_value_of_image_property",
"os.getcwd",
"qautils.dataset.dataset_utils.DatasetUtils",
"qautils.logger.logger_utils.get_logger",
"hamcrest.equal_to"
] | [((1148, 1169), 'qautils.logger.logger_utils.get_logger', 'get_logger', (['"""qautils"""'], {}), "('qautils')\n", (1158, 1169), False, 'from qautils.logger.logger_utils import get_logger\n'), ((1762, 1776), 'qautils.dataset.dataset_utils.DatasetUtils', 'DatasetUtils', ([], {}), '()\n', (1774, 1776), False, 'from qautil... |
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
import store_api.urls
import store_ui.urls
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include(store_api.urls.urlpatterns)),
url(r'^.*$', include(store_ui.... | [
"django.conf.urls.include"
] | [((203, 227), 'django.conf.urls.include', 'include', (['admin.site.urls'], {}), '(admin.site.urls)\n', (210, 227), False, 'from django.conf.urls import include, url\n'), ((248, 283), 'django.conf.urls.include', 'include', (['store_api.urls.urlpatterns'], {}), '(store_api.urls.urlpatterns)\n', (255, 283), False, 'from d... |
import pp
def test_mzi():
netlist = """
instances:
CP1:
component: mmi1x2
settings:
width_mmi: 4.5
length_mmi: 10
CP2:
component: mmi1x2
settings:
width_mmi: 4.5
length_mmi: 5
arm_t... | [
"pp.component_from_yaml",
"pp.plotgds",
"pp.show"
] | [((663, 694), 'pp.component_from_yaml', 'pp.component_from_yaml', (['netlist'], {}), '(netlist)\n', (685, 694), False, 'import pp\n'), ((747, 757), 'pp.show', 'pp.show', (['c'], {}), '(c)\n', (754, 757), False, 'import pp\n'), ((762, 775), 'pp.plotgds', 'pp.plotgds', (['c'], {}), '(c)\n', (772, 775), False, 'import pp\... |
import numpy as np
import scipy.linalg as la
from scipy.stats import multinomial
def random_multivar_normal(n, d, k, sigma=.1):
'''
Generate random samples from a random multivariate normal distribution
with covariance A A^T + sigma^2 I.
Input:
n: int, number of samples
d: int, dimensio... | [
"scipy.linalg.eigh",
"numpy.eye",
"numpy.random.rand",
"numpy.diag_indices",
"scipy.stats.multinomial.cov",
"numpy.random.multinomial",
"numpy.random.dirichlet",
"numpy.zeros",
"numpy.outer"
] | [((2998, 3015), 'numpy.random.rand', 'np.random.rand', (['d'], {}), '(d)\n', (3012, 3015), True, 'import numpy as np\n'), ((3408, 3420), 'scipy.linalg.eigh', 'la.eigh', (['cov'], {}), '(cov)\n', (3415, 3420), True, 'import scipy.linalg as la\n'), ((4563, 4580), 'numpy.random.rand', 'np.random.rand', (['d'], {}), '(d)\n... |
"""livestream API tests"""
from livestream.api import get_upcoming_events
def test_get_upcoming_events(settings, mocker):
"""test get upcoming events"""
settings.LIVESTREAM_ACCOUNT_ID = 392_239
settings.LIVESTREAM_SECRET_KEY = "secret key"
requests_patch = mocker.patch("requests.get", autospec=True)
... | [
"livestream.api.get_upcoming_events"
] | [((330, 351), 'livestream.api.get_upcoming_events', 'get_upcoming_events', ([], {}), '()\n', (349, 351), False, 'from livestream.api import get_upcoming_events\n')] |
'''
Created on 15.2.2017
@author: sapejura
'''
import io
import threading
import struct
class FrameQueue(io.IOBase):
def __init__(self, frame_size):
super().__init__()
self.queue_lock = threading.Lock()
self._queue = bytearray()
self._store_mode = 0
self.frame_size = fram... | [
"threading.Lock",
"struct.unpack"
] | [((210, 226), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (224, 226), False, 'import threading\n'), ((1744, 1768), 'struct.unpack', 'struct.unpack', (['"""B"""', 'byte'], {}), "('B', byte)\n", (1757, 1768), False, 'import struct\n')] |
#!/usr/bin/python
import numpy as np
import os
import pymaster as nmt
import pytest
import tjpcov.main as cv
from tjpcov.parser import parse
import yaml
import sacc
root = "./tests/benchmarks/32_DES_tjpcov_bm/"
input_yml = os.path.join(root, "tjpcov_conf_minimal.yaml")
input_yml_no_nmtc = os.path.join(root, "tjpcov_c... | [
"pymaster.NmtWorkspace",
"numpy.abs",
"pymaster.NmtCovarianceWorkspace",
"numpy.delete",
"os.path.join",
"tjpcov.parser.parse",
"numpy.diag",
"pytest.mark.parametrize",
"numpy.array",
"yaml.safe_load",
"numpy.zeros",
"pytest.raises",
"numpy.linalg.inv",
"os.system",
"numpy.all",
"numpy... | [((225, 271), 'os.path.join', 'os.path.join', (['root', '"""tjpcov_conf_minimal.yaml"""'], {}), "(root, 'tjpcov_conf_minimal.yaml')\n", (237, 271), False, 'import os\n'), ((292, 349), 'os.path.join', 'os.path.join', (['root', '"""tjpcov_conf_minimal_no_nmtconf.yaml"""'], {}), "(root, 'tjpcov_conf_minimal_no_nmtconf.yam... |
# -*- coding: utf-8 -*-
from os.path import join
import requests
from bs4 import BeautifulSoup
SCIKIT_LEARN_BASE_URL = 'http://scikit-learn.org/stable/auto_examples/'
SCIKIT_INDEX_URL = 'http://scikit-learn.org/stable/auto_examples/index.html'
def download_file(fetch_me):
"""
Fetches a file in given url int... | [
"bs4.BeautifulSoup",
"requests.get"
] | [((550, 585), 'requests.get', 'requests.get', (['fetch_me'], {'stream': '(True)'}), '(fetch_me, stream=True)\n', (562, 585), False, 'import requests\n'), ((895, 930), 'bs4.BeautifulSoup', 'BeautifulSoup', (['index', '"""html.parser"""'], {}), "(index, 'html.parser')\n", (908, 930), False, 'from bs4 import BeautifulSoup... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import cstr, cint, getdate
from frappe import msgprint, _
def execute(filters=None):
if not filters: filters = {}
if... | [
"frappe.defaults.get_defaults",
"frappe.db.sql",
"frappe._"
] | [((2020, 2262), 'frappe.db.sql', 'frappe.db.sql', (['"""select count(*) as count, status from `tabStudent Attendance` where \t\t\t\tstudent_group= %s and date= %s and\t\t\t\t(course_schedule is Null or course_schedule=\'\') group by status"""', '(student_group, date)'], {'as_dict': '(1)'}), '(\n "select count(*) as ... |
import logging
from bottle import Bottle, request, response, abort, static_file
import os
import time
import threading
from threading import Thread
from pathlib import Path
import json
import subprocess
import io
import sys
import signal
from internal.notifier import getNotifier, NotificationLevel
from internal.interpr... | [
"logging.getLogger",
"bottle.static_file",
"json.loads",
"internal.notifier.getNotifier",
"traceback.format_exc",
"paho.mqtt.client.Client",
"subprocess.Popen",
"json.dumps",
"os.path.join",
"time.sleep",
"paho.mqtt.subscribe.simple",
"os.getpid",
"machine_app.MachineAppEngine",
"threading... | [((728, 756), 'os.path.join', 'os.path.join', (['""".."""', '"""client"""'], {}), "('..', 'client')\n", (740, 756), False, 'import os\n'), ((790, 807), 'os.path.join', 'os.path.join', (['"""."""'], {}), "('.')\n", (802, 807), False, 'import os\n'), ((832, 859), 'logging.getLogger', 'logging.getLogger', (['__name__'], {... |
from __future__ import absolute_import
from __future__ import unicode_literals
from corehq.apps.locations.models import SQLLocation
from corehq.form_processor.models import CommCareCaseIndexSQL
from custom.icds.case_relationships import (
mother_person_case_from_ccs_record_case,
mother_person_case_from_child_he... | [
"datetime.datetime",
"datetime.datetime.utcnow",
"custom.icds.case_relationships.mother_person_case_from_child_health_case",
"dimagi.utils.logging.notify_exception",
"custom.icds.case_relationships.mother_person_case_from_child_person_case",
"corehq.apps.locations.models.SQLLocation.objects.filter",
"cu... | [((1668, 1736), 'custom.icds.case_relationships.mother_person_case_from_ccs_record_case', 'mother_person_case_from_ccs_record_case', (['case_schedule_instance.case'], {}), '(case_schedule_instance.case)\n', (1707, 1736), False, 'from custom.icds.case_relationships import mother_person_case_from_ccs_record_case, mother_... |
"""
Driver program for training and evaluation.
"""
import argparse
import logging
import numpy as np
import random
import torch
import torch.optim as O
from datasets import get_dataset, get_dataset_configurations
from models import get_model
from runners import Runner
if __name__ == '__main__':
parser = argpar... | [
"logging.getLogger",
"torch.manual_seed",
"numpy.prod",
"logging.StreamHandler",
"argparse.ArgumentParser",
"runners.Runner",
"logging.Formatter",
"models.get_model",
"random.seed",
"torch.cuda.manual_seed",
"numpy.random.seed",
"datasets.get_dataset_configurations",
"datasets.get_dataset"
] | [((314, 379), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Sentence similarity models"""'}), "(description='Sentence similarity models')\n", (337, 379), False, 'import argparse\n'), ((1789, 1811), 'random.seed', 'random.seed', (['args.seed'], {}), '(args.seed)\n', (1800, 1811), False, ... |
"""
USFM References Tools
"""
import re
__version__ = '1.1.0'
ANY_REF = re.compile(r'^[1-9A-Z]{3}\.([0-9]{1,3}(_[0-9]+)?(\.[0-9]{1,3})?|INTRO\d+)$')
CHAPTER = re.compile(r'^[1-6A-Z]{3}\.[0-9]{1,3}(_[0-9]+)?$')
CHAPTER_OR_INTRO = re.compile(r'^[1-9A-Z]{3}\.([0-9]{1,3}(_[0-9]+)?|INTRO\d+)$')
SINGLE_CHAPTER_OR_VERSE = r... | [
"re.match",
"re.compile"
] | [((74, 152), 're.compile', 're.compile', (['"""^[1-9A-Z]{3}\\\\.([0-9]{1,3}(_[0-9]+)?(\\\\.[0-9]{1,3})?|INTRO\\\\d+)$"""'], {}), "('^[1-9A-Z]{3}\\\\.([0-9]{1,3}(_[0-9]+)?(\\\\.[0-9]{1,3})?|INTRO\\\\d+)$')\n", (84, 152), False, 'import re\n'), ((161, 211), 're.compile', 're.compile', (['"""^[1-6A-Z]{3}\\\\.[0-9]{1,3}(_[... |
from wallarm_api.core.api.base_api import BaseApi
from wallarm_api.core.models.trigger import Triggers
class TriggersApi(BaseApi):
def get_triggers(self, clientid):
url = f'/v2/clients/{clientid}/triggers?denormalize=true'
response = self.client.get(url)
triggers = Triggers(trig... | [
"wallarm_api.core.models.trigger.Triggers"
] | [((307, 346), 'wallarm_api.core.models.trigger.Triggers', 'Triggers', ([], {'triggers': "response['triggers']"}), "(triggers=response['triggers'])\n", (315, 346), False, 'from wallarm_api.core.models.trigger import Triggers\n')] |
from PIL import Image
from matplotlib import pyplot as plt
import numpy as np
names = locals()
img0 = Image.open("./assets/pyCharm.png")
# print image info:
print(img0.size, img0.format, img0.mode, np.array(img0))
# save other format
# img0.save('./assets/pyCharm.tiff')
# img0.convert('RGB').save('./assets/pyCharm.jp... | [
"PIL.Image.fromarray",
"PIL.Image.open",
"numpy.array",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.subplot",
"PIL.Image.merge",
"matplotlib.pyplot.show"
] | [((104, 138), 'PIL.Image.open', 'Image.open', (['"""./assets/pyCharm.png"""'], {}), "('./assets/pyCharm.png')\n", (114, 138), False, 'from PIL import Image\n'), ((389, 424), 'PIL.Image.open', 'Image.open', (['"""./assets/pyCharm.tiff"""'], {}), "('./assets/pyCharm.tiff')\n", (399, 424), False, 'from PIL import Image\n'... |
from rpython.rtyper.lltypesystem import lltype, rffi
from rpython.rlib.rarithmetic import intmask
from rpython.rlib.debug import debug_start, debug_print, debug_stop
from rpython.rlib.debug import have_debug_prints
from rpython.jit.backend.llsupport.asmmemmgr import BlockBuilderMixin
from rpython.jit.backend.x86.rx86 i... | [
"rpython.rlib.rarithmetic.intmask",
"rpython.rtyper.lltypesystem.rffi.cast"
] | [((1918, 1949), 'rpython.rtyper.lltypesystem.rffi.cast', 'rffi.cast', (['rffi.LONGP', '(p - WORD)'], {}), '(rffi.LONGP, p - WORD)\n', (1927, 1949), False, 'from rpython.rtyper.lltypesystem import lltype, rffi\n'), ((1975, 1994), 'rpython.rlib.rarithmetic.intmask', 'intmask', (['(adr[0] - p)'], {}), '(adr[0] - p)\n', (1... |
from typing import List, Literal, Optional, Sequence
from pydantic import Field, root_validator, validator
from pydantic.main import BaseModel
from weaverbird.pipeline.steps.utils.base import BaseStep
from weaverbird.pipeline.steps.utils.render_variables import StepWithVariablesMixin
from weaverbird.pipeline.steps.ut... | [
"pydantic.Field",
"weaverbird.pipeline.steps.utils.validation.validate_unique_columns",
"pydantic.root_validator",
"pydantic.validator"
] | [((751, 776), 'pydantic.Field', 'Field', ([], {'alias': '"""newcolumns"""'}), "(alias='newcolumns')\n", (756, 776), False, 'from pydantic import Field, root_validator, validator\n'), ((809, 835), 'pydantic.Field', 'Field', ([], {'alias': '"""aggfunction"""'}), "(alias='aggfunction')\n", (814, 835), False, 'from pydanti... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import flt, cstr, cint
from frappe import _
from frappe.model.meta import get_field_precision
from erpnext.accounts.util... | [
"frappe._dict",
"frappe.db.get_value",
"frappe.db.get_single_value",
"frappe._",
"erpnext.accounts.doctype.gl_entry.gl_entry.validate_balance_type",
"erpnext.accounts.utils.validate_expense_against_budget",
"frappe.db.sql",
"frappe.get_doc",
"erpnext.accounts.doctype.gl_entry.gl_entry.validate_froze... | [((3387, 3407), 'frappe.get_doc', 'frappe.get_doc', (['args'], {}), '(args)\n', (3401, 3407), False, 'import frappe\n'), ((4529, 4562), 'frappe.utils.flt', 'flt', (['debit_credit_diff', 'precision'], {}), '(debit_credit_diff, precision)\n', (4532, 4562), False, 'from frappe.utils import flt, cstr, cint\n'), ((5305, 531... |
import pygame
import inspect
from .bullet import Bullet
from .player import Player
PRESSED = {
pygame.K_UP: 'up',
pygame.K_DOWN: 'down',
pygame.K_LEFT: 'left',
pygame.K_RIGHT: 'right',
}
DOWN = {
pygame.K_LSHIFT: 'shift',
}
UP = {
pygame.K_LSHIFT: 'unshift',
}
class Game:
def __init__... | [
"pygame.event.get",
"pygame.sprite.Group",
"pygame.display.set_mode",
"inspect.isgenerator",
"pygame.key.get_pressed",
"pygame.time.Clock",
"pygame.display.update"
] | [((350, 385), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(640, 480)'], {}), '((640, 480))\n', (373, 385), False, 'import pygame\n'), ((459, 480), 'pygame.sprite.Group', 'pygame.sprite.Group', ([], {}), '()\n', (478, 480), False, 'import pygame\n'), ((504, 525), 'pygame.sprite.Group', 'pygame.sprite.Group'... |
import numpy as np
import pandas as pd
import pytest
from sklearn.feature_selection import SelectKBest, chi2 as sk_chi2
from inz.utils import chi2, select_k_best, split, train_test_split
def test_split_list_int():
ints = list(range(7))
want = [[0, 1, 2], [3, 4, 5], [6]]
get = list(split(ints, 3))
ass... | [
"inz.utils.train_test_split",
"inz.utils.split",
"numpy.testing.assert_equal",
"pandas.read_csv",
"inz.utils.select_k_best",
"pytest.main",
"sklearn.feature_selection.SelectKBest",
"numpy.array",
"inz.utils.chi2",
"numpy.array_equal",
"sklearn.feature_selection.chi2",
"numpy.arange"
] | [((2899, 2933), 'pandas.read_csv', 'pd.read_csv', (['"""../../data/data.csv"""'], {}), "('../../data/data.csv')\n", (2910, 2933), True, 'import pandas as pd\n'), ((3044, 3057), 'sklearn.feature_selection.chi2', 'sk_chi2', (['X', 'y'], {}), '(X, y)\n', (3051, 3057), True, 'from sklearn.feature_selection import SelectKBe... |
from unittest import TestCase
from tests import get_data
from pytezos.michelson.micheline import michelson_to_micheline
from pytezos.michelson.formatter import micheline_to_michelson
class MichelsonCodingTestKT1BDM(TestCase):
def setUp(self):
self.maxDiff = None
def test_michelson_parse_code_KT... | [
"pytezos.michelson.formatter.micheline_to_michelson",
"tests.get_data"
] | [((351, 436), 'tests.get_data', 'get_data', ([], {'path': '"""contracts/KT1BDMQEhMATgVAcwtgqNgZNBM6LEM1PANuM/code_KT1BDM.json"""'}), "(path='contracts/KT1BDMQEhMATgVAcwtgqNgZNBM6LEM1PANuM/code_KT1BDM.json'\n )\n", (359, 436), False, 'from tests import get_data\n'), ((690, 768), 'tests.get_data', 'get_data', ([], {'p... |
import timeit
setup = """
import phash
import imageio
import numpy as np
mod = phash.phash()
"""
read_image = """
img0 = np.array(imageio.imread('data/frog.jpeg', pilmode='F'))
mod.img_hash_f32(img0)
"""
print('data/frog.jpeg', timeit.timeit(read_image, setup=setup, number=100) * 10, "ms")
setup_imagehash = """
fr... | [
"timeit.timeit"
] | [((232, 282), 'timeit.timeit', 'timeit.timeit', (['read_image'], {'setup': 'setup', 'number': '(100)'}), '(read_image, setup=setup, number=100)\n', (245, 282), False, 'import timeit\n'), ((454, 514), 'timeit.timeit', 'timeit.timeit', (['hash_bench'], {'setup': 'setup_imagehash', 'number': '(100)'}), '(hash_bench, setup... |
import torch
import sys
import coremltools as ct
from hidt.style_transformer import StyleTransformer
from ops import inference_size
sys.path.append('./HiDT')
class HiDT(torch.nn.Module):
def __init__(self):
super().__init__()
config_path = './configs/daytime.yaml'
gen_weights_path = './t... | [
"torch.jit.trace",
"hidt.style_transformer.StyleTransformer",
"torch.no_grad",
"sys.path.append",
"torch.zeros",
"coremltools.Shape"
] | [((134, 159), 'sys.path.append', 'sys.path.append', (['"""./HiDT"""'], {}), "('./HiDT')\n", (149, 159), False, 'import sys\n'), ((1304, 1331), 'torch.zeros', 'torch.zeros', (['(1)', '(3)', '(256)', '(452)'], {}), '(1, 3, 256, 452)\n', (1315, 1331), False, 'import torch\n'), ((1356, 1370), 'torch.zeros', 'torch.zeros', ... |
import json
from .helpers import send_notification_to_user
def send_user_notification(user, payload, ttl=0):
payload = json.dumps(payload)
send_notification_to_user(user, payload, ttl) | [
"json.dumps"
] | [((123, 142), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (133, 142), False, 'import json\n')] |