code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from abc import ABC, abstractmethod
import copy
import logging
import numpy as np
from scipy.stats import rankdata
from typing import Dict, NamedTuple, NoReturn, Tuple
from ..lux.game import Game
from ..lux.game_constants import GAME_CONSTANTS
from ..lux.game_objects import Player
def count_city_tiles(game_state: Ga... | [
"numpy.zeros_like",
"numpy.ones_like",
"numpy.maximum",
"logging.warning",
"numpy.empty",
"numpy.empty_like",
"numpy.ones",
"copy.copy",
"scipy.stats.rankdata",
"numpy.where",
"numpy.array",
"numpy.logical_or"
] | [((350, 417), 'numpy.array', 'np.array', (['[player.city_tile_count for player in game_state.players]'], {}), '([player.city_tile_count for player in game_state.players])\n', (358, 417), True, 'import numpy as np\n'), ((801, 868), 'numpy.array', 'np.array', (['[player.research_points for player in game_state.players]']... |
import numpy as np
import matplotlib.pyplot as plt
# To use LaTeX in the plots
plt.rcParams.update({
"text.usetex": True,
"font.family": "sans-serif",
"font.sans-serif": ["Helvetica"]})
# for Palatino and other serif fonts use:
plt.rcParams.update({
"text.usetex": True,
"font.family": "serif",
... | [
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.add",
"numpy.zeros",
"matplotlib.pyplot.rcParams.update",
"numpy.array",
"numpy.exp",
"numpy.linspace",
"numpy.linalg.norm",
"numpy.linalg.inv",
"matplotlib.pyplot.ylabel",
"numpy.log10",
"matplotlib.pyplot.xlabel"
] | [((80, 189), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'text.usetex': True, 'font.family': 'sans-serif', 'font.sans-serif': [\n 'Helvetica']}"], {}), "({'text.usetex': True, 'font.family': 'sans-serif',\n 'font.sans-serif': ['Helvetica']})\n", (99, 189), True, 'import matplotlib.pyplot as pl... |
import bpy
import asyncio
from asyncio import Task, coroutine, sleep
import blender_async
class TestDialog(blender_async.dialogs.AsyncDialog):
my_float = bpy.props.FloatProperty(name="Some Floating Point")
my_bool = bpy.props.BoolProperty(name="Toggle Option")
my_string = bpy.props.StringProperty(name="S... | [
"bpy.props.BoolProperty",
"blender_async.get_event_loop",
"asyncio.sleep",
"blender_async.open_file_dialog",
"bpy.props.FloatProperty",
"bpy.props.StringProperty",
"blender_async.open_dialog"
] | [((578, 608), 'blender_async.get_event_loop', 'blender_async.get_event_loop', ([], {}), '()\n', (606, 608), False, 'import blender_async\n'), ((161, 212), 'bpy.props.FloatProperty', 'bpy.props.FloatProperty', ([], {'name': '"""Some Floating Point"""'}), "(name='Some Floating Point')\n", (184, 212), False, 'import bpy\n... |
# --------------
# Import packages
import numpy as np
import pandas as pd
from scipy.stats import mode
bank = pd.read_csv(path)
categorical_var = bank.select_dtypes(include='object')
print(categorical_var)
numerical_var = bank.select_dtypes(include='number')
print(numerical_var)
# code starts here
# code end... | [
"pandas.read_csv",
"pandas.pivot_table"
] | [((113, 130), 'pandas.read_csv', 'pd.read_csv', (['path'], {}), '(path)\n', (124, 130), True, 'import pandas as pd\n'), ((934, 1043), 'pandas.pivot_table', 'pd.pivot_table', (['banks'], {'values': '"""LoanAmount"""', 'index': "['Gender', 'Married', 'Self_Employed']", 'aggfunc': 'np.mean'}), "(banks, values='LoanAmount'... |
#03_01_dice
import random # import random module
for x in range(1,11): # for loop to go from 1 -10
random_number = random.randint(1, 6) # ranint pick between 1 and 6
print(random_number) # print the # that was saved to variable random_number
| [
"random.randint"
] | [((119, 139), 'random.randint', 'random.randint', (['(1)', '(6)'], {}), '(1, 6)\n', (133, 139), False, 'import random\n')] |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 17 23:03:32 2020
@author: quipo
"""
import pandas as pd
import numpy as np
import re
from unidecode import unidecode
def diccionario_quitar_tildes(col):
return {col: {'á': 'a', 'Á': 'A','é': 'e', 'É': 'E','í': 'i', 'Í': 'I','ó': 'o', 'Ó': 'O','ú': 'u', 'Ú': 'U'}}
dat... | [
"pandas.read_csv",
"pandas.merge",
"pandas.DataFrame",
"pandas.read_excel"
] | [((331, 399), 'pandas.read_csv', 'pd.read_csv', (['"""../../datos_proscesados.csv"""'], {'sep': '""","""', 'encoding': '"""utf8"""'}), "('../../datos_proscesados.csv', sep=',', encoding='utf8')\n", (342, 399), True, 'import pandas as pd\n'), ((594, 647), 'pandas.read_excel', 'pd.read_excel', (['"""../../Andres/cluster/... |
#!/usr/local/bin/python3
#encoding:utf8
'''
作用:爬取京东商城手机分类下的的所有手机商品的展示图片。
url:为需要爬取的网址
page:页数
'''
import re
import urllib.request
def getimage(url, page):
html = urllib.request.urlopen(url).read();
html = str(html);
pattern1 = '<div id="plist".+? <div class="page clearfix">';
... | [
"re.compile"
] | [((331, 351), 're.compile', 're.compile', (['pattern1'], {}), '(pattern1)\n', (341, 351), False, 'import re\n'), ((471, 491), 're.compile', 're.compile', (['pattern2'], {}), '(pattern2)\n', (481, 491), False, 'import re\n'), ((677, 697), 're.compile', 're.compile', (['pattern3'], {}), '(pattern3)\n', (687, 697), False,... |
import os
import json
from flask import Flask, render_template
from flask.ext.assets import Environment
app = Flask(__name__)
app.debug = True
# govuk_template asset path
@app.context_processor
def asset_path_context_processor():
return {
'asset_path': '/static/govuk-template/',
'prototypes_asset_path': '/... | [
"os.environ.get",
"flask.Flask",
"flask.render_template",
"json.load"
] | [((112, 127), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (117, 127), False, 'from flask import Flask, render_template\n'), ((371, 400), 'flask.render_template', 'render_template', (['"""index.html"""'], {}), "('index.html')\n", (386, 400), False, 'from flask import Flask, render_template\n'), ((558, 59... |
# need better design
import pyglet
import resources
import random
import math
from pyglet.window import key
score = 0
game_window = pyglet.window.Window()
pyglet.resource.path = ['./resources']
pyglet.resource.reindex()
ast_img = pyglet.resource.image("player.png")
def distance(point_1=(0, 0), point_2=(0, 0)):
""... | [
"pyglet.resource.image",
"pyglet.app.run",
"random.randint",
"pyglet.text.Label",
"math.sqrt",
"pyglet.resource.reindex",
"pyglet.sprite.Sprite",
"random.random",
"pyglet.window.Window",
"pyglet.clock.schedule_interval"
] | [((133, 155), 'pyglet.window.Window', 'pyglet.window.Window', ([], {}), '()\n', (153, 155), False, 'import pyglet\n'), ((195, 220), 'pyglet.resource.reindex', 'pyglet.resource.reindex', ([], {}), '()\n', (218, 220), False, 'import pyglet\n'), ((231, 266), 'pyglet.resource.image', 'pyglet.resource.image', (['"""player.p... |
import hashlib
import random
import string
from llvmlite.ir import Context
def generate_random_name(count: int):
return ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase + string.digits, k=count))
def rreplace(s, old, new, occurrence=-1):
li = s.rsplit(old, occurrence)
return new.j... | [
"random.choices"
] | [((135, 228), 'random.choices', 'random.choices', (['(string.ascii_uppercase + string.ascii_lowercase + string.digits)'], {'k': 'count'}), '(string.ascii_uppercase + string.ascii_lowercase + string.\n digits, k=count)\n', (149, 228), False, 'import random\n')] |
from typing import Optional
from tlh.const import RomVariant
from tlh import settings
class Rom:
def __init__(self, filename: str):
with open(filename, 'rb') as rom:
self.bytes = bytearray(rom.read())
def get_bytes(self, from_index: int, to_index: int) -> bytearray:
# TODO apply c... | [
"tlh.settings.get_rom"
] | [((1025, 1050), 'tlh.settings.get_rom', 'settings.get_rom', (['variant'], {}), '(variant)\n', (1041, 1050), False, 'from tlh import settings\n')] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import copy
# import os
import json
# import ConfigParser
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.core.urlresolvers import reverse
from django.contrib import messages
fro... | [
"app.core.models.Domain.objects.filter",
"csv.reader",
"django.core.urlresolvers.reverse",
"app.utils.domain_session.get_domainid_bysession",
"app.core.models.DomainAttr.objects.filter",
"xlrd.open_workbook",
"django.db.models.Q",
"json.dumps",
"lib.tools.clear_redis_cache",
"django.template.respo... | [((1164, 1186), 'django_redis.get_redis_connection', 'get_redis_connection', ([], {}), '()\n', (1184, 1186), False, 'from django_redis import get_redis_connection\n'), ((1272, 1291), 'lib.tools.clear_redis_cache', 'clear_redis_cache', ([], {}), '()\n', (1289, 1291), False, 'from lib.tools import clear_redis_cache\n'), ... |
#
# Copyright (C) 2020 IBM. All Rights Reserved.
#
# See LICENSE.txt file in the root directory
# of this source tree for licensing information.
#
import os
from pathlib import Path
from clai.tools.colorize_console import Colorize
from clai.server.searchlib.data import Datastore
from clai.server.agent import Agent
f... | [
"clai.server.searchlib.data.Datastore",
"clai.tools.colorize_console.Colorize",
"clai.server.logger.current_logger.info",
"clai.server.command_message.Action",
"pathlib.Path"
] | [((650, 673), 'clai.server.searchlib.data.Datastore', 'Datastore', (['inifile_path'], {}), '(inifile_path)\n', (659, 673), False, 'from clai.server.searchlib.data import Datastore\n'), ((2081, 2120), 'clai.server.command_message.Action', 'Action', ([], {'suggested_command': 'state.command'}), '(suggested_command=state.... |
from .app import data_path
from .optionswin import OptionsWin
from .camera import Camera, CameraControl, getCameraDevices
from .camlabel import CamLabel
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtGui import QImage, QIcon
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QAction, QVBoxLayout, QHBoxLay... | [
"os.mkdir",
"PyQt5.QtWidgets.QVBoxLayout",
"glob.glob",
"PyQt5.QtWidgets.QMessageBox.critical",
"os.path.join",
"PyQt5.QtWidgets.QMessageBox.aboutQt",
"PyQt5.QtWidgets.QLabel",
"os.path.abspath",
"PyQt5.QtWidgets.QWidget",
"os.path.exists",
"PyQt5.QtWidgets.QComboBox",
"functools.partial",
"... | [((6212, 6225), 'PyQt5.QtCore.pyqtSlot', 'pyqtSlot', (['int'], {}), '(int)\n', (6220, 6225), False, 'from PyQt5.QtCore import pyqtSlot\n'), ((6323, 6333), 'PyQt5.QtCore.pyqtSlot', 'pyqtSlot', ([], {}), '()\n', (6331, 6333), False, 'from PyQt5.QtCore import pyqtSlot\n'), ((514, 539), 'os.path.abspath', 'os.path.abspath'... |
import sys
from os.path import join
from threading import Timer
import numpy as np
from openal.audio import SoundSource
assets_root = getattr(sys, '_MEIPASS', '.')
def get_sfx(name):
return join(assets_root, 'assets', name)
def new_pt(*values):
return np.array(values or (0, 0, 0), dtype=float)
def vec_m... | [
"numpy.array",
"os.path.join"
] | [((198, 231), 'os.path.join', 'join', (['assets_root', '"""assets"""', 'name'], {}), "(assets_root, 'assets', name)\n", (202, 231), False, 'from os.path import join\n'), ((266, 308), 'numpy.array', 'np.array', (['(values or (0, 0, 0))'], {'dtype': 'float'}), '(values or (0, 0, 0), dtype=float)\n', (274, 308), True, 'im... |
import cirq
import numpy as np
from cirq import Circuit
from cirq.devices import GridQubit
# creating circuit with 5 qubit
length = 5
qubits = [cirq.GridQubit(i, j) for i in range(length) for j in range(length)]
print(qubits)
circuit = cirq.Circuit()
H1 = cirq.H(qubits[0])
H2 = cirq.H(qubits[1])
H3 = cirq.H(qubits[... | [
"cirq.GridQubit",
"cirq.H",
"cirq.SWAP",
"cirq.CNOT",
"cirq.Circuit",
"cirq.Moment",
"cirq.X"
] | [((240, 254), 'cirq.Circuit', 'cirq.Circuit', ([], {}), '()\n', (252, 254), False, 'import cirq\n'), ((260, 277), 'cirq.H', 'cirq.H', (['qubits[0]'], {}), '(qubits[0])\n', (266, 277), False, 'import cirq\n'), ((283, 300), 'cirq.H', 'cirq.H', (['qubits[1]'], {}), '(qubits[1])\n', (289, 300), False, 'import cirq\n'), ((3... |
import networkx as nx
from parse import read_input_file, write_output_file
from Utility import is_valid_network, average_pairwise_distance, average_pairwise_distance_fast
import sys
import time
import multiprocessing
def solve(G, depth):
"""
Args:
G: networkx.Graph
Returns:
T: networkx.Gra... | [
"networkx.dfs_edges",
"Utility.is_valid_network",
"Utility.average_pairwise_distance_fast",
"networkx.Graph",
"parse.read_input_file",
"multiprocessing.Pool",
"multiprocessing.cpu_count"
] | [((866, 899), 'Utility.average_pairwise_distance_fast', 'average_pairwise_distance_fast', (['T'], {}), '(T)\n', (896, 899), False, 'from Utility import is_valid_network, average_pairwise_distance, average_pairwise_distance_fast\n'), ((1464, 1497), 'Utility.average_pairwise_distance_fast', 'average_pairwise_distance_fas... |
"""
Contains functions related to Discord-specific features, such as embeds.
"""
import discord
import datetime
import time
from botforces.utils.constants import (
NUMBER_OF_ACS,
USER_WEBSITE_URL,
PROBLEM_WEBSITE_URL,
)
from botforces.utils.services import enclose_tags_in_spoilers
"""
User embeds.
"""
... | [
"botforces.utils.services.enclose_tags_in_spoilers",
"discord.Embed",
"datetime.datetime.strptime",
"datetime.timedelta",
"datetime.datetime.fromtimestamp"
] | [((445, 541), 'discord.Embed', 'discord.Embed', ([], {'title': "user['handle']", 'url': 'f"""{USER_WEBSITE_URL}{user[\'handle\']}"""', 'color': 'color'}), '(title=user[\'handle\'], url=\n f"{USER_WEBSITE_URL}{user[\'handle\']}", color=color)\n', (458, 541), False, 'import discord\n'), ((1616, 1818), 'discord.Embed',... |
"""
Test the ability to ignore undriven inputs (useful for formal verification
tools that use undriven inputs to mark wires that can take on any value)
"""
import pytest
import magma as m
from magma.testing import check_files_equal
def test_ignore_unused_undriven_basic():
class Main(m.Circuit):
_ignore_... | [
"magma.ClockIO",
"magma.In",
"magma.testing.check_files_equal",
"pytest.warns",
"magma.Out",
"magma.compile"
] | [((413, 532), 'magma.compile', 'm.compile', (['"""build/test_ignore_unused_undriven_basic"""', 'Main'], {'inline': '(True)', 'drive_undriven': '(True)', 'terminate_unused': '(True)'}), "('build/test_ignore_unused_undriven_basic', Main, inline=True,\n drive_undriven=True, terminate_unused=True)\n", (422, 532), True, ... |
import re
from typing import Optional, List, NamedTuple, Dict, Any
import requests
import bs4
GENO_REGEX = re.compile(r"\(.;.\)")
DESC_STYLE = (
"border: 1px; background-color: #FFFFC0;"
+ "border-style: solid; margin:1em; width:90%;"
)
class SNP:
def __init__(
self, rsid: str, table: Optional[... | [
"re.match",
"typing.NamedTuple",
"requests.get",
"bs4.BeautifulSoup",
"re.compile"
] | [((109, 132), 're.compile', 're.compile', (['"""\\\\(.;.\\\\)"""'], {}), "('\\\\(.;.\\\\)')\n", (119, 132), False, 'import re\n'), ((813, 869), 'typing.NamedTuple', 'NamedTuple', (['"""Row"""', '((header, str) for header in headers)'], {}), "('Row', ((header, str) for header in headers))\n", (823, 869), False, 'from ty... |
import time
import math as m
import redis
import struct
import numpy as np
from adafruit_servokit import ServoKit
r = redis.Redis(host='localhost', port=6379, db=0)
kit = ServoKit(channels=16)
#controllable variables
def rget_and_float(name, default = None):
output = r.get(name)
if output == None:
ret... | [
"redis.Redis",
"struct.unpack",
"adafruit_servokit.ServoKit",
"time.sleep",
"time.time"
] | [((119, 165), 'redis.Redis', 'redis.Redis', ([], {'host': '"""localhost"""', 'port': '(6379)', 'db': '(0)'}), "(host='localhost', port=6379, db=0)\n", (130, 165), False, 'import redis\n'), ((172, 193), 'adafruit_servokit.ServoKit', 'ServoKit', ([], {'channels': '(16)'}), '(channels=16)\n', (180, 193), False, 'from adaf... |
#!/usr/bin/env python3
#pylint: disable = C, R
#pylint: disable = E1101 # no-member (generated-members)
#pylint: disable = C0302 # too-many-lines
"""
This code features the article
"Pareto-based evaluation of national responses to COVID-19 pandemic shows
that saving lives and protecting economy are non-trade-o... | [
"colorsys.rgb_to_hls",
"numpy.isnan",
"numpy.sin",
"pandas.Grouper",
"locale.setlocale",
"matplotlib.patheffects.Normal",
"matplotlib.pyplot.cm.tab10",
"numpy.savetxt",
"dill.load",
"numpy.place",
"matplotlib.dates.DateFormatter",
"matplotlib.patheffects.Stroke",
"matplotlib.pyplot.rc",
"m... | [((1038, 1070), 'pandas.plotting.register_matplotlib_converters', 'register_matplotlib_converters', ([], {}), '()\n', (1068, 1070), False, 'from pandas.plotting import register_matplotlib_converters\n'), ((1971, 2014), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'size': '(8)', 'family': '"""sans-serif"""'}), "(... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from utilities.models import BaseDateTime
class Contact(BaseDateTime):
title = models.CharField(
_('TITLE_LABEL'),
max_length=255
)
name = models.CharField(
_('NAME_L... | [
"django.utils.translation.ugettext_lazy"
] | [((211, 227), 'django.utils.translation.ugettext_lazy', '_', (['"""TITLE_LABEL"""'], {}), "('TITLE_LABEL')\n", (212, 227), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((311, 326), 'django.utils.translation.ugettext_lazy', '_', (['"""NAME_LABEL"""'], {}), "('NAME_LABEL')\n", (312, 326), True, 'fr... |
import numpy as np
from absl.testing import parameterized
from keras.preprocessing import image
from keras.utils import data_utils
from tensorflow.python.platform import test
from ..bit import BiT_S_R50x1, BiT_S_R50x3, BiT_S_R101x1, BiT_S_R101x3, BiT_S_R152x4
from ..bit import BiT_M_R50x1, BiT_M_R50x3, BiT_M_R101x1, Bi... | [
"tensorflow.python.platform.test.main",
"numpy.argmax",
"numpy.expand_dims",
"absl.testing.parameterized.parameters",
"keras.utils.data_utils.get_file",
"keras.preprocessing.image.img_to_array"
] | [((814, 853), 'absl.testing.parameterized.parameters', 'parameterized.parameters', (['*MODEL_LIST_S'], {}), '(*MODEL_LIST_S)\n', (838, 853), False, 'from absl.testing import parameterized\n'), ((1197, 1236), 'absl.testing.parameterized.parameters', 'parameterized.parameters', (['*MODEL_LIST_S'], {}), '(*MODEL_LIST_S)\n... |
#!/usr/bin/env python3
from Adafruit_PCA9685 import PCA9685
import time
pwm = PCA9685()
servo_min = 250
servo_max = 450
pulse = servo_min
increasing = True
step_size = 1
while True:
pwm.set_pwm(0, 0, pulse)
if pulse < servo_max and increasing:
pulse += step_size
increasing = True
elif pul... | [
"Adafruit_PCA9685.PCA9685",
"time.sleep"
] | [((79, 88), 'Adafruit_PCA9685.PCA9685', 'PCA9685', ([], {}), '()\n', (86, 88), False, 'from Adafruit_PCA9685 import PCA9685\n'), ((457, 473), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (467, 473), False, 'import time\n'), ((542, 557), 'time.sleep', 'time.sleep', (['(0.5)'], {}), '(0.5)\n', (552, 557), Fa... |
from setuptools import setup, find_packages
NAME = "passari_web_ui"
DESCRIPTION = (
"Web interface for Passari workflow"
)
LONG_DESCRIPTION = DESCRIPTION
AUTHOR = "<NAME>"
AUTHOR_EMAIL = "<EMAIL>"
setup(
name=NAME,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
author=AUTHOR,
au... | [
"setuptools.find_packages"
] | [((358, 378), 'setuptools.find_packages', 'find_packages', (['"""src"""'], {}), "('src')\n", (371, 378), False, 'from setuptools import setup, find_packages\n')] |
from django.urls import path
from . import views
app_name="blog" #Works as namespace
urlpatterns = [
path('', views.blogs, name="blog"),
path('<int:blog_id>', views.detail, name="detail")
] | [
"django.urls.path"
] | [((107, 141), 'django.urls.path', 'path', (['""""""', 'views.blogs'], {'name': '"""blog"""'}), "('', views.blogs, name='blog')\n", (111, 141), False, 'from django.urls import path\n'), ((147, 197), 'django.urls.path', 'path', (['"""<int:blog_id>"""', 'views.detail'], {'name': '"""detail"""'}), "('<int:blog_id>', views.... |
from pyreact import setTitle, useEffect, useState, render, createElement as el
def App():
newTask, setNewTask = useState("")
editTask, setEditTask = useState(None)
taskList, setTaskList = useState([])
taskCount, setTaskCount = useState(0)
taskFilter, setTaskFilter = useState("all")
def handleS... | [
"pyreact.useState",
"pyreact.setTitle",
"pyreact.render",
"pyreact.createElement",
"pyreact.useEffect"
] | [((5328, 5353), 'pyreact.render', 'render', (['App', 'None', '"""root"""'], {}), "(App, None, 'root')\n", (5334, 5353), False, 'from pyreact import setTitle, useEffect, useState, render, createElement as el\n'), ((117, 129), 'pyreact.useState', 'useState', (['""""""'], {}), "('')\n", (125, 129), False, 'from pyreact im... |
from io import open
from setuptools import setup
from setuptools.command.test import test as TestCommand
import appstore
class Tox(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
impor... | [
"tox.cmdline",
"setuptools.command.test.test.finalize_options",
"setuptools.setup",
"io.open"
] | [((473, 1387), 'setuptools.setup', 'setup', ([], {'name': '"""appstore"""', 'version': 'appstore.__version__', 'description': '"""App Store -- user-oriented front-end for pip."""', 'long_description': 'readme', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'url': '"""http://www.grantjenks.com/docs/appstore... |
# %%
from trainer import Trainer
from network import ResUnet3D, ResAttrUnet3D, ResAttrUnet3D2, ResAttrBNUnet3D
from loss import Dice, HybirdLoss, DiceLoss, FocalLoss
from data import CaseDataset
from torchvision.transforms import Compose
from transform import Crop, RandomCrop, ToTensor, CombineLabels, \
RandomBrig... | [
"transform.RandomMirror",
"data.CaseDataset",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"datetime.datetime.now",
"loss.FocalLoss",
"transform.ToTensor",
"transform.RandomRescaleCrop",
"loss.Dice",
"transform.RandomGamma",
"network.ResUnet3D",
"transform.RandomContrast",
"trainer.Trainer",
... | [((621, 676), 'loss.HybirdLoss', 'HybirdLoss', ([], {'weight_v': '[1, 148, 191]', 'alpha': '(0.9)', 'beta': '(0.1)'}), '(weight_v=[1, 148, 191], alpha=0.9, beta=0.1)\n', (631, 676), False, 'from loss import Dice, HybirdLoss, DiceLoss, FocalLoss\n'), ((909, 962), 'torch.optim.lr_scheduler.ReduceLROnPlateau', 'ReduceLROn... |
from serial import Serial
import time
import platform
import socket
serialPort = Serial('COM3' if platform.system() == 'Windows' else '/dev/ttyUSB0', 9600)
time.sleep(2)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('', 2222))
server.listen(1)
while True:
(client, address) = server.accept(... | [
"platform.system",
"socket.socket",
"time.sleep"
] | [((157, 170), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (167, 170), False, 'import time\n'), ((181, 230), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (194, 230), False, 'import socket\n'), ((99, 116), 'platform.system', 'platform.... |
from django.forms import ModelForm, Textarea, TextInput
from .models import Review
from django import forms
from django.contrib.auth.models import User
# Form to take display to take user's review
class ReviewForm(ModelForm):
class Meta:
model = Review
fields = ['rating', 'comment']
#user_... | [
"django.forms.TextInput",
"django.forms.CharField",
"django.forms.Textarea"
] | [((697, 740), 'django.forms.CharField', 'forms.CharField', ([], {'widget': 'forms.PasswordInput'}), '(widget=forms.PasswordInput)\n', (712, 740), False, 'from django import forms\n'), ((442, 482), 'django.forms.Textarea', 'Textarea', ([], {'attrs': "{'cols': 35, 'rows': 10}"}), "(attrs={'cols': 35, 'rows': 10})\n", (45... |
from flax import nn
import jax
from haiku._src.typing import PRNGKey
from jax import random
import jax.numpy as jnp
import numpy as onp
from typing import List, Tuple
from utils import gaussian_likelihood
class TD3Actor(nn.Module):
def apply(self, x, action_dim, max_action):
x = nn.Dense(x, features=256)... | [
"jax.random.normal",
"flax.nn.softplus",
"jax.numpy.concatenate",
"jax.numpy.exp",
"utils.gaussian_likelihood",
"jax.numpy.asarray",
"flax.nn.elu",
"flax.nn.LayerNorm",
"jax.numpy.split",
"flax.nn.tanh",
"jax.numpy.clip",
"flax.nn.Model",
"flax.nn.Dense",
"flax.nn.relu"
] | [((3025, 3056), 'flax.nn.Model', 'nn.Model', (['constant', 'init_params'], {}), '(constant, init_params)\n', (3033, 3056), False, 'from flax import nn\n'), ((3286, 3314), 'flax.nn.Model', 'nn.Model', (['actor', 'init_params'], {}), '(actor, init_params)\n', (3294, 3314), False, 'from flax import nn\n'), ((3480, 3509), ... |
# Anagram Utility
# License: MIT
""" Tests for anagram"""
import unittest
import errno
import shutil
from os.path import join
import anagram.anagram as anagram
class TestAnagram(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.parser = anagram.args_options()
cls.mock_path = '/path/to/folder'
@clas... | [
"shutil.rmtree",
"anagram.anagram.args_options"
] | [((254, 276), 'anagram.anagram.args_options', 'anagram.args_options', ([], {}), '()\n', (274, 276), True, 'import anagram.anagram as anagram\n'), ((363, 384), 'shutil.rmtree', 'shutil.rmtree', (['"""path"""'], {}), "('path')\n", (376, 384), False, 'import shutil\n')] |
from fractions import Fraction
from dice_stats import Dice
def test_totalchance():
d6 = Dice.from_dice(6)
for c in [
Fraction(1),
Fraction(1, 2),
Fraction(1, 6),
]:
assert d6 @ c * 2 == 2 * d6 @ c
def test_nested_d6():
d6 = Dice.from_dice(6)
d6_a = Dice.sum(v * ... | [
"fractions.Fraction",
"dice_stats.Dice.sum",
"dice_stats.Dice.from_dice"
] | [((95, 112), 'dice_stats.Dice.from_dice', 'Dice.from_dice', (['(6)'], {}), '(6)\n', (109, 112), False, 'from dice_stats import Dice\n'), ((278, 295), 'dice_stats.Dice.from_dice', 'Dice.from_dice', (['(6)'], {}), '(6)\n', (292, 295), False, 'from dice_stats import Dice\n'), ((358, 416), 'dice_stats.Dice.sum', 'Dice.sum'... |
# Copyright 2019 The SQLFlow Authors. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | [
"pickle.load",
"tensorflow.python.platform.gfile.GFile"
] | [((1287, 1318), 'tensorflow.python.platform.gfile.GFile', 'gfile.GFile', (['oss_path'], {'mode': '"""w"""'}), "(oss_path, mode='w')\n", (1298, 1318), False, 'from tensorflow.python.platform import gfile\n'), ((1897, 1928), 'tensorflow.python.platform.gfile.GFile', 'gfile.GFile', (['oss_path'], {'mode': '"""r"""'}), "(o... |
# Copyright (C) 2017 <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,... | [
"os.path.abspath",
"json.load",
"os.path.join",
"os.makedirs",
"os.path.basename",
"os.path.isdir",
"os.path.dirname",
"datetime.datetime.now",
"os.path.isfile",
"subprocess.call",
"os.path.normpath",
"winreg.QueryValue",
"os.path.splitext",
"operator.itemgetter",
"os.path.expanduser",
... | [((1446, 1467), 'os.path.normpath', 'os.path.normpath', (['hou'], {}), '(hou)\n', (1462, 1467), False, 'import os\n'), ((1526, 1559), 'os.path.expanduser', 'os.path.expanduser', (['"""~/Documents"""'], {}), "('~/Documents')\n", (1544, 1559), False, 'import os\n'), ((1637, 1658), 'os.listdir', 'os.listdir', (['directory... |
from __future__ import print_function, absolute_import, unicode_literals, division
import six
from six.moves import (zip, filter, map, reduce, input, range)
# standard library
import functools
# third party
# project specific
from waldo.conf import settings
from waldo import wio
from . import secondary
from . import... | [
"waldo.wio.Experiment",
"six.iteritems"
] | [((1286, 1339), 'waldo.wio.Experiment', 'wio.Experiment', ([], {'experiment_id': 'ex_id', 'callback': 'cb_load'}), '(experiment_id=ex_id, callback=cb_load)\n', (1300, 1339), False, 'from waldo import wio\n'), ((1540, 1559), 'six.iteritems', 'six.iteritems', (['data'], {}), '(data)\n', (1553, 1559), False, 'import six\n... |
"""
Useful functions for creating encryption schemes.
"""
from math import gcd
from typing import Tuple
import sympy
from ._check_gmpy2 import USE_GMPY2
if USE_GMPY2:
import gmpy2
def randprime(low: int, high: int) -> int:
"""
Generate a random prime number in the range [low, high). Returns GMPY2 MPZ ... | [
"gmpy2.invert",
"math.gcd",
"sympy.ntheory.generate.randprime",
"gmpy2.lcm",
"gmpy2.mpz",
"gmpy2.powmod",
"sympy.isprime"
] | [((821, 864), 'sympy.ntheory.generate.randprime', 'sympy.ntheory.generate.randprime', (['low', 'high'], {}), '(low, high)\n', (853, 864), False, 'import sympy\n'), ((3270, 3291), 'sympy.isprime', 'sympy.isprime', (['number'], {}), '(number)\n', (3283, 3291), False, 'import sympy\n'), ((1158, 1195), 'gmpy2.powmod', 'gmp... |
import torch
import torch.nn as nn
from torchvision.models.utils import load_state_dict_from_url
model_urls = {
'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth',
}
class VGG(nn.Module):
def __init__(self, features, num_classes=1000, init_weights=True):
super(VGG, self).__i... | [
"torch.flatten",
"torch.nn.AdaptiveAvgPool2d",
"torch.nn.Dropout",
"torch.nn.ReLU",
"torch.nn.init.kaiming_normal_",
"torch.nn.Sequential",
"torch.nn.Conv2d",
"torch.nn.BatchNorm2d",
"torch.nn.init.constant_",
"torch.nn.init.normal_",
"torchvision.models.utils.load_state_dict_from_url",
"torch... | [((2270, 2292), 'torch.nn.Sequential', 'nn.Sequential', (['*layers'], {}), '(*layers)\n', (2283, 2292), True, 'import torch.nn as nn\n'), ((386, 414), 'torch.nn.AdaptiveAvgPool2d', 'nn.AdaptiveAvgPool2d', (['(7, 7)'], {}), '((7, 7))\n', (406, 414), True, 'import torch.nn as nn\n'), ((867, 886), 'torch.flatten', 'torch.... |
import gym
import gym_sokoban
from stable_baselines.common.vec_env import DummyVecEnv
from stable_baselines.deepq.policies import MlpPolicy
from stable_baselines import DQN
def run():
# hyperparameters
gamma = 0.99 #discount factor
learning_rate = 0.00025 #learning rate for adam optimizer
buffer_size ... | [
"stable_baselines.DQN",
"gym.make"
] | [((1000, 1028), 'gym.make', 'gym.make', (['"""Boxoban-Train-v1"""'], {}), "('Boxoban-Train-v1')\n", (1008, 1028), False, 'import gym\n'), ((1042, 1392), 'stable_baselines.DQN', 'DQN', (['MlpPolicy', 'env'], {'gamma': 'gamma', 'learning_rate': 'learning_rate', 'buffer_size': 'buffer_size', 'exploration_fraction': 'explo... |
#!/usr/bin/env python
# Roobert V2 - second version of home robot project
# ________ ______ _____
# ___ __ \______________ /_______________ /_
# __ /_/ / __ \ __ \_ __ \ _ \_ ___/ __/
# _ _, _// /_/ / /_/ / /_/ / __/ / / /_
# /_/ |_| \____/\____//... | [
"atexit.register",
"os.path.abspath",
"SmartServoManager.SmartServoManager",
"os.system",
"sys.path.insert",
"time.sleep",
"LX16AServos.LX16AServos"
] | [((1717, 1742), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (1732, 1742), False, 'import time, sys, os\n'), ((1788, 1859), 'sys.path.insert', 'sys.path.insert', (['(0)', "(my_path + '/../DanielsRasPiPythonLibs/multitasking')"], {}), "(0, my_path + '/../DanielsRasPiPythonLibs/multitasking')... |
"""
The Colloid_output module contains classes to read LB Colloids simulation
outputs and perform post processing. Many classes are available to
provide plotting functionality. ModelPlot and CCModelPlot are useful for
visualizing colloid-surface forces and colloid-colloid forces respectively.
example import of the Col... | [
"matplotlib.pyplot.bar",
"matplotlib.pyplot.quiver",
"numpy.isnan",
"numpy.arange",
"numpy.exp",
"matplotlib.pyplot.gca",
"pandas.DataFrame",
"numpy.meshgrid",
"numpy.std",
"scipy.special.erfc",
"scipy.optimize.least_squares",
"numpy.linspace",
"numpy.var",
"h5py.File",
"numpy.ma.masked_... | [((5546, 5562), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0, 1]'], {}), '([0, 1])\n', (5554, 5562), True, 'import matplotlib.pyplot as plt\n'), ((6361, 6377), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0, 1]'], {}), '([0, 1])\n', (6369, 6377), True, 'import matplotlib.pyplot as plt\n'), ((10592, 10608), 'matplotlib.pypl... |
# -*- coding: UTF-8 -*-
# !/usr/bin/python
# @time :2019/6/5 21:04
# @author :Mo
# @function :file of path
import os
# 项目的根目录
path_root = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
path_root = path_root.replace('\\', '/')
# train out
path_out = path_root + "/out/"
# path of embedding
... | [
"os.path.dirname"
] | [((175, 200), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (190, 200), False, 'import os\n')] |
from rest_framework.authtoken.models import Token
from rest_framework.test import APITestCase
from users.models import User, GitHubProfile
class BaseTestCase(APITestCase):
USER = 'admin'
PASSWORD = '<PASSWORD>'
EMAIL = '<EMAIL>'
def setUp(self):
super(BaseTestCase, self).setUp()
user... | [
"rest_framework.authtoken.models.Token.objects.create",
"users.models.User.objects.create_user",
"users.models.GitHubProfile.objects.create"
] | [((344, 380), 'rest_framework.authtoken.models.Token.objects.create', 'Token.objects.create', ([], {'user': 'self.user'}), '(user=self.user)\n', (364, 380), False, 'from rest_framework.authtoken.models import Token\n'), ((539, 627), 'users.models.User.objects.create_user', 'User.objects.create_user', ([], {'username': ... |
"""
This is an example of importing data from a CKAN instance and converting it
into the JSON output suitable for the Open SDG reporting platform.
"""
import os
import sdg
import pandas as pd
# Input data from CKAN
endpoint = 'https://inventory.data.gov/api/action/datastore_search'
indicator_id_map = {
# The reso... | [
"sdg.outputs.OutputOpenSdg",
"sdg.translations.TranslationInputSdgTranslations",
"sdg.inputs.InputCkan",
"sdg.schemas.SchemaInputOpenSdg",
"pandas.melt",
"os.path.join"
] | [((416, 490), 'sdg.inputs.InputCkan', 'sdg.inputs.InputCkan', ([], {'endpoint': 'endpoint', 'indicator_id_map': 'indicator_id_map'}), '(endpoint=endpoint, indicator_id_map=indicator_id_map)\n', (436, 490), False, 'import sdg\n'), ((1177, 1212), 'os.path.join', 'os.path.join', (['"""tests"""', '"""_prose.yml"""'], {}), ... |
import geopandas as gpd
# required for MAUP: https://github.com/geopandas/geopandas/issues/2199
gpd.options.use_pygeos = False
import pandas as pd
import numpy as np
import shapely
import shapely.geometry
from shapely.geometry import Polygon, Point
from tqdm import tqdm
import maup
import os
#INTRO - need to edit valu... | [
"pandas.DataFrame",
"maup.normalize",
"shapely.geometry.Point",
"numpy.ceil",
"shapely.geometry.Polygon",
"pandas.read_csv",
"maup.assign",
"maup.prorate",
"numpy.isnan",
"geopandas.GeoDataFrame",
"maup.intersections",
"geopandas.clip",
"shapely.geometry.box",
"geopandas.read_file"
] | [((934, 962), 'shapely.geometry.Point', 'Point', (['(-71.411479)', '(41.823544)'], {}), '(-71.411479, 41.823544)\n', (939, 962), False, 'from shapely.geometry import Polygon, Point\n'), ((977, 1021), 'geopandas.GeoDataFrame', 'gpd.GeoDataFrame', ([], {'geometry': '[point]', 'crs': '(4326)'}), '(geometry=[point], crs=43... |
import time
import pickle
import redis
class ModelAgent:
def __init__(
self,
redis_broker='localhost:6379',
redis_queue='broker',
model_class=None,
model_config={},
batch_size=64,
model_sleep=0.1,
collection=False,
collection_limit=6000,
... | [
"pickle.loads",
"pickle.dumps",
"time.sleep"
] | [((2073, 2101), 'time.sleep', 'time.sleep', (['self.model_sleep'], {}), '(self.model_sleep)\n', (2083, 2101), False, 'import time\n'), ((1419, 1434), 'pickle.loads', 'pickle.loads', (['x'], {}), '(x)\n', (1431, 1434), False, 'import pickle\n'), ((1732, 1752), 'pickle.dumps', 'pickle.dumps', (['result'], {}), '(result)\... |
#!/usr/bin/env python
# coding: utf-8
# ## SIMPLE CONVOLUTIONAL NEURAL NETWORK
# In[1]:
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
get_ipython().run_line_magic('matplotlib', 'inline')
print ("PACKAGES LOADED")
# # LOAD MNIS... | [
"numpy.argmax",
"tensorflow.reshape",
"tensorflow.ConfigProto",
"tensorflow.matmul",
"tensorflow.nn.conv2d",
"tensorflow.nn.relu",
"tensorflow.nn.softmax_cross_entropy_with_logits",
"matplotlib.pyplot.colorbar",
"tensorflow.placeholder",
"tensorflow.cast",
"tensorflow.initialize_all_variables",
... | [((342, 390), 'tensorflow.examples.tutorials.mnist.input_data.read_data_sets', 'input_data.read_data_sets', (['"""data/"""'], {'one_hot': '(True)'}), "('data/', one_hot=True)\n", (367, 390), False, 'from tensorflow.examples.tutorials.mnist import input_data\n'), ((2026, 2069), 'tensorflow.placeholder', 'tf.placeholder'... |
import kivy
kivy.require('1.10.0')
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.checkbox import CheckBox
from kivy.uix.dropdown import DropDown
from kivy.uix.gridlayout import GridLayout
from kivy.uix.screenmanager import Screen, ScreenManager
from sudokub... | [
"kivy.require",
"kivy.uix.button.Button",
"kivy.uix.screenmanager.ScreenManager",
"kivy.uix.checkbox.CheckBox"
] | [((12, 34), 'kivy.require', 'kivy.require', (['"""1.10.0"""'], {}), "('1.10.0')\n", (24, 34), False, 'import kivy\n'), ((1323, 1338), 'kivy.uix.screenmanager.ScreenManager', 'ScreenManager', ([], {}), '()\n', (1336, 1338), False, 'from kivy.uix.screenmanager import Screen, ScreenManager\n'), ((1108, 1174), 'kivy.uix.ch... |
import argparse
import inspect
import re
def bindSignatureArgs(func, src:dict) -> dict:
'''
Args:
func: Function/method from which the signature will be sourced.
src: Source dictionary that will provide values for dest.
Returns:
A new dictionary with argument values from src set
... | [
"inspect.signature"
] | [((451, 474), 'inspect.signature', 'inspect.signature', (['func'], {}), '(func)\n', (468, 474), False, 'import inspect\n'), ((3388, 3419), 'inspect.signature', 'inspect.signature', (['cls.__call__'], {}), '(cls.__call__)\n', (3405, 3419), False, 'import inspect\n')] |
import os, sys
from subprocess import Popen, PIPE
from backupcommon import BackupLogger, info, debug, error, exception
from datetime import datetime, timedelta
from tempfile import mkstemp, TemporaryFile
class OracleExec(object):
oraclehome = None
tnspath = None
oraclesid = None
def __init__(self, ora... | [
"subprocess.Popen",
"os.unlink",
"tempfile.mkstemp",
"os.path.join",
"backupcommon.debug",
"os.environ.get",
"tempfile.TemporaryFile",
"backupcommon.BackupLogger.init",
"os.close",
"backupcommon.error",
"os.fdopen",
"backupcommon.BackupLogger.close",
"datetime.datetime.now"
] | [((486, 528), 'backupcommon.debug', 'debug', (["('Oracle home: %s' % self.oraclehome)"], {}), "('Oracle home: %s' % self.oraclehome)\n", (491, 528), False, 'from backupcommon import BackupLogger, info, debug, error, exception\n'), ((983, 1013), 'backupcommon.debug', 'debug', (['"""RMAN execution starts"""'], {}), "('RM... |
import mxnet as mx
import numpy as np
from rcnn.config import config
class LogLossMetric(mx.metric.EvalMetric):
def __init__(self):
super(LogLossMetric, self).__init__('LogLoss')
def update(self, labels, preds):
pred_cls = preds[0].asnumpy()
label = labels[0].asnumpy().astype('int32'... | [
"numpy.arange",
"numpy.sum",
"numpy.log"
] | [((460, 476), 'numpy.sum', 'np.sum', (['cls_loss'], {}), '(cls_loss)\n', (466, 476), True, 'import numpy as np\n'), ((825, 842), 'numpy.sum', 'np.sum', (['bbox_loss'], {}), '(bbox_loss)\n', (831, 842), True, 'import numpy as np\n'), ((429, 440), 'numpy.log', 'np.log', (['cls'], {}), '(cls)\n', (435, 440), True, 'import... |
import pandas as pd
import os
class DataFile:
# 1日分のデータが格納された辞書
data_files = {}
def __init__(self,df,filepath,outpath,kind):
# 1ファイルの内容
self.df = df
# 入力ファイルパス
self.filename = filepath
# 出力先パス
self.output_dir = outpath
# データの種類
self.data_kind... | [
"pandas.to_datetime",
"os.makedirs"
] | [((829, 853), 'pandas.to_datetime', 'pd.to_datetime', (["df['時間']"], {}), "(df['時間'])\n", (843, 853), True, 'import pandas as pd\n'), ((6645, 6664), 'os.makedirs', 'os.makedirs', (['output'], {}), '(output)\n', (6656, 6664), False, 'import os\n')] |
import os
import gensim
import pytest
import compress_fasttext
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from compress_fasttext.feature_extraction import FastTextTransformer
BIG_MODEL_FILE = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data/test_data/f... | [
"compress_fasttext.feature_extraction.FastTextTransformer",
"gensim.models.fasttext.FastTextKeyedVectors.load",
"os.path.dirname",
"sklearn.linear_model.LogisticRegression",
"pytest.mark.parametrize",
"pytest.approx",
"compress_fasttext.models.CompressedFastTextKeyedVectors.load"
] | [((1665, 1953), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""word1, word2, model_name"""', "[('белый', 'черный',\n 'gensim-4-draft/geowac_tokens_sg_300_5_2020-100K-20K-100.bin'), (\n 'white', 'black',\n 'gensim-4-draft/ft_cc.en.300_freqprune_50K_5K_pq_100.bin'), ('white',\n 'black', 'v0.0.4/c... |
import unittest, yaml
from pyreqgen.ReqParser import *
class TestParser(unittest.TestCase):
def test_files(self):
with open("../config.yaml", 'r+') as config_f:
configs = yaml.load(config_f, Loader=yaml.FullLoader)
print(configs)
py_files = ReqParser.__get_py_files(configs)
reqs = ReqParser.__get_reqs(... | [
"unittest.main",
"yaml.load"
] | [((1211, 1226), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1224, 1226), False, 'import unittest, yaml\n'), ((180, 223), 'yaml.load', 'yaml.load', (['config_f'], {'Loader': 'yaml.FullLoader'}), '(config_f, Loader=yaml.FullLoader)\n', (189, 223), False, 'import unittest, yaml\n')] |
import os
import sys
import xml.etree.ElementTree as xml
from ..Helpers import path_helper
from ..Helpers import xcrun_helper
from ..Helpers import logging_helper
from .XCSchemeActions.BuildAction import BuildAction
from .XCSchemeActions.TestAction import TestAction
from .XCSchemeActions.LaunchAction import LaunchAct... | [
"xml.etree.ElementTree.parse",
"os.getlogin",
"os.path.basename",
"os.path.exists",
"os.path.isfile",
"os.path.join",
"os.listdir"
] | [((737, 781), 'os.path.join', 'os.path.join', (['path', '"""xcshareddata/xcschemes"""'], {}), "(path, 'xcshareddata/xcschemes')\n", (749, 781), False, 'import os\n'), ((559, 593), 'os.path.join', 'os.path.join', (['path', '"""xcshareddata"""'], {}), "(path, 'xcshareddata')\n", (571, 593), False, 'import os\n'), ((657, ... |
# -*- coding: utf8 -*-
"""
Special action to recompress all data
"""
__author__ = 'sergey'
import sys
from multiprocessing import cpu_count
def do_recompress(options, _fuse):
"""
@param options: Commandline options
@type options: object
@param _fuse: FUSE wrapper
@type _fuse: dedupsqlfs.fuse.... | [
"sys.stdout.write",
"sys.stdout.flush",
"dedupsqlfs.fuse.subvolume.Subvolume",
"multiprocessing.cpu_count"
] | [((4917, 4944), 'dedupsqlfs.fuse.subvolume.Subvolume', 'Subvolume', (['_fuse.operations'], {}), '(_fuse.operations)\n', (4926, 4944), False, 'from dedupsqlfs.fuse.subvolume import Subvolume\n'), ((1163, 1174), 'multiprocessing.cpu_count', 'cpu_count', ([], {}), '()\n', (1172, 1174), False, 'from multiprocessing import ... |
# get_positions.py
import pandas as pd
from math import ceil
from sys import argv
'''
Current known problems:
- do schools at different times (ew)
- Bias towards double delegate committees
'''
class Team:
def __init__(self, name, num_delegates, preferences):
'''
num_delegats is an int of the ... | [
"pandas.read_csv",
"pandas.DataFrame",
"math.ceil"
] | [((2044, 2077), 'pandas.read_csv', 'pd.read_csv', (['school_info_filename'], {}), '(school_info_filename)\n', (2055, 2077), True, 'import pandas as pd\n'), ((2090, 2126), 'pandas.read_csv', 'pd.read_csv', (['committee_info_filename'], {}), '(committee_info_filename)\n', (2101, 2126), True, 'import pandas as pd\n'), ((6... |
import re
class BaseClass:
def _get_keys(self):
attrs = self.get_attributes()
return attrs.keys()
def get_attributes(self):
attrs = self.__dict__
attrs_filtered = {k: v for k, v in attrs.items() if not k.startswith("_")}
return attrs_filtered
@staticmethod
def... | [
"re.split",
"re.search"
] | [((444, 468), 're.split', 're.split', (['""", |,"""', 'string'], {}), "(', |,', string)\n", (452, 468), False, 'import re\n'), ((1613, 1645), 're.search', 're.search', (['"""[^a-zA-Z_0-9]"""', 'name'], {}), "('[^a-zA-Z_0-9]', name)\n", (1622, 1645), False, 'import re\n')] |
from ccxt_microservice.bucket import Bucket
import pytest
@pytest.fixture
def the_bucket():
return Bucket(10, 1, 5)
def test_state(the_bucket):
assert 4.99 < the_bucket.state() < 5
def test_push(the_bucket):
the_bucket.push(5)
assert 9.99 < the_bucket.state() < 10
def test_timeToWait(the_bucket):... | [
"ccxt_microservice.bucket.Bucket"
] | [((105, 121), 'ccxt_microservice.bucket.Bucket', 'Bucket', (['(10)', '(1)', '(5)'], {}), '(10, 1, 5)\n', (111, 121), False, 'from ccxt_microservice.bucket import Bucket\n')] |
#!/usr/bin/env python3
# NOTE: If you are using an alpine docker image
# such as pyaction-lite, the -S option above won't
# work. The above line works fine on other linux distributions
# such as debian, etc, so the above line will work fine
# if you use pyaction:4.0.0 or higher as your base docker image.
# Steps in t... | [
"os.path.exists",
"logging.getLogger",
"os.path.splitext",
"os.symlink",
"os.path.join",
"subprocess.check_call"
] | [((567, 598), 'logging.getLogger', 'logging.getLogger', (['"""entrypoint"""'], {}), "('entrypoint')\n", (584, 598), False, 'import logging\n'), ((3401, 3462), 'subprocess.check_call', 'subprocess.check_call', (['f"""rochtml {metadata_file}"""'], {'shell': '(True)'}), "(f'rochtml {metadata_file}', shell=True)\n", (3422,... |
"""
Because Gooey communicates with the host program
over stdin/out, we have to be able to differentiate what's
coming from gooey and structured, versus what is arbitrary
junk coming from the host's own logging.
To do this, we just prefix all written by gooey with the
literal string 'gooey::'. This lets us dig through... | [
"base64.b64decode",
"gooey.python_bindings.schema.validate_public_state",
"json.dumps"
] | [((1205, 1232), 'gooey.python_bindings.schema.validate_public_state', 'validate_public_state', (['data'], {}), '(data)\n', (1226, 1232), False, 'from gooey.python_bindings.schema import validate_public_state\n'), ((836, 851), 'json.dumps', 'json.dumps', (['out'], {}), '(out)\n', (846, 851), False, 'import json\n'), ((1... |
import numpy as np
from pytest_cases import parametrize_with_cases, case
from snake_learner.direction import Direction
from snake_learner.linalg_util import block_distance, closest_direction, \
project_to_direction
CLOSEST_DIRECTION = "closest_direction"
PROJECT_TO_DIRECTION = "project_to_direction"
@case(tags=... | [
"snake_learner.direction.Direction.RIGHT.to_array",
"snake_learner.linalg_util.block_distance",
"snake_learner.linalg_util.closest_direction",
"snake_learner.direction.Direction.UP.to_array",
"snake_learner.linalg_util.project_to_direction",
"numpy.array",
"pytest_cases.case",
"pytest_cases.parametriz... | [((310, 340), 'pytest_cases.case', 'case', ([], {'tags': '[CLOSEST_DIRECTION]'}), '(tags=[CLOSEST_DIRECTION])\n', (314, 340), False, 'from pytest_cases import parametrize_with_cases, case\n'), ((503, 533), 'pytest_cases.case', 'case', ([], {'tags': '[CLOSEST_DIRECTION]'}), '(tags=[CLOSEST_DIRECTION])\n', (507, 533), Fa... |
# -*- coding: utf-8 -*-
import logging
import json
import random
import string
import time
import requests
from requests import RequestException
logger = logging.getLogger(__name__)
class PyttributionIo:
"""
A Python wrapper around the Attribution.io API (by <NAME> – www.jakob.codes)
"""
GET_REQUE... | [
"requests.RequestException",
"random.choice",
"time.time",
"time.sleep",
"requests.post",
"logging.getLogger"
] | [((157, 184), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (174, 184), False, 'import logging\n'), ((3747, 3765), 'requests.RequestException', 'RequestException', ([], {}), '()\n', (3763, 3765), False, 'from requests import RequestException\n'), ((4113, 4131), 'requests.RequestException... |
from setuptools import setup
setup(
name="google-doc",
version="0.1",
description="Manipulating files pragmatically",
url="https://github.com/ribeirogab/google-doc",
author="<NAME>",
author_email="<EMAIL>",
license="MIT",
packages=["app"],
zip_safe=False,
)
| [
"setuptools.setup"
] | [((30, 269), 'setuptools.setup', 'setup', ([], {'name': '"""google-doc"""', 'version': '"""0.1"""', 'description': '"""Manipulating files pragmatically"""', 'url': '"""https://github.com/ribeirogab/google-doc"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'license': '"""MIT"""', 'packages': "['app']", ... |
# Generated by Django 2.1.4 on 2019-10-03 13:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0032_auto_20190729_1249'),
]
operations = [
migrations.AddField(
model_name='ocrmodel',
name='job',
... | [
"django.db.models.PositiveSmallIntegerField"
] | [((330, 421), 'django.db.models.PositiveSmallIntegerField', 'models.PositiveSmallIntegerField', ([], {'choices': "[(1, 'Segment'), (2, 'Recognize')]", 'default': '(2)'}), "(choices=[(1, 'Segment'), (2, 'Recognize')],\n default=2)\n", (362, 421), False, 'from django.db import migrations, models\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2017, <NAME>
# All rights reserved.
#
# The file is part of the xpcc library and is released under the 3-clause BSD
# license. See the file `LICENSE` for the full license governing this code.
# ---------------------------------------------------------------... | [
"collections.defaultdict",
"subprocess.Popen",
"locale.getpreferredencoding",
"argparse.ArgumentParser"
] | [((1640, 1656), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (1651, 1656), False, 'from collections import defaultdict\n'), ((2484, 2549), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Author statistics of xpcc."""'}), "(description='Author statistics of xpcc.')\n... |
import pytest
from pyisic import KSIC10_to_ISIC4
from pyisic.types import Standards
@pytest.mark.parametrize(
"code,expected",
[
("DOESNT EXIST", set()),
("A", set()),
("14112", {(Standards.ISIC4, "1410")}),
],
)
def test_ksic10_to_isic4_concordance(code: str, expected: str):
... | [
"pyisic.KSIC10_to_ISIC4.concordant"
] | [((379, 411), 'pyisic.KSIC10_to_ISIC4.concordant', 'KSIC10_to_ISIC4.concordant', (['code'], {}), '(code)\n', (405, 411), False, 'from pyisic import KSIC10_to_ISIC4\n')] |
from unittest import TestCase, main
from ko_pron import romanise
def mr_romanize(word):
return romanise(word, "mr")
class TestKoPron(TestCase):
def test_kosinga(self):
self.assertEqual("kŏsin'ga", mr_romanize("것인가"))
def test_kosida(self):
self.assertEqual("kŏsida", mr_romanize("것이다"))... | [
"unittest.main",
"ko_pron.romanise"
] | [((102, 122), 'ko_pron.romanise', 'romanise', (['word', '"""mr"""'], {}), "(word, 'mr')\n", (110, 122), False, 'from ko_pron import romanise\n'), ((354, 360), 'unittest.main', 'main', ([], {}), '()\n', (358, 360), False, 'from unittest import TestCase, main\n')] |
import sys
try: from Queue import PriorityQueue
except: from queue import PriorityQueue
try: from memory import page
except: import page
from collections import OrderedDict
# Disable bytecode generation
sys.dont_write_bytecode = True
class PageTable(object):
'''
Simulates the operations of the Memory Mana... | [
"collections.OrderedDict"
] | [((449, 462), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (460, 462), False, 'from collections import OrderedDict\n'), ((485, 498), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (496, 498), False, 'from collections import OrderedDict\n')] |
# Code to reboot an EC2 instance (configured with 'aws configure')
import boto3
from botocore.exceptions import ClientError
def getFirstInstanceID(ec2):
# Get all EC2 instances
all_instances = ec2.describe_instances()
# Select the first
first = all_instances['Reservations'][0]['Instances'][0]
# Re... | [
"boto3.client"
] | [((414, 433), 'boto3.client', 'boto3.client', (['"""ec2"""'], {}), "('ec2')\n", (426, 433), False, 'import boto3\n')] |
from typing import List, Dict, Tuple, Callable, Any, Optional, Union
from drepr.models import Variable, Location
from drepr.services.ra_iterator import RAIterator
from drepr.services.ra_reader.ra_reader import RAReader
class MultiRAReader(RAReader):
def __init__(self, ra_readers: Dict[str, RAReader]):
se... | [
"drepr.services.ra_iterator.RAIterator"
] | [((1968, 2041), 'drepr.services.ra_iterator.RAIterator', 'RAIterator', (['self', 'upperbound', 'lowerbound', 'step_sizes', 'reverse', 'is_dynamic'], {}), '(self, upperbound, lowerbound, step_sizes, reverse, is_dynamic)\n', (1978, 2041), False, 'from drepr.services.ra_iterator import RAIterator\n')] |
'''
Created on Nov 14, 2018
@author: nilson.nieto
'''
import time, datetime
# Using Epoch
print(time.ctime(time.time()))
print('Current day')
print(datetime.datetime.today())
| [
"datetime.datetime.today",
"time.time"
] | [((155, 180), 'datetime.datetime.today', 'datetime.datetime.today', ([], {}), '()\n', (178, 180), False, 'import time, datetime\n'), ((110, 121), 'time.time', 'time.time', ([], {}), '()\n', (119, 121), False, 'import time, datetime\n')] |
###############################################################################
# Copyright 2011,2012 The University of Texas at Austin #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #... | [
"copy.deepcopy",
"ipf.engine.WorkflowEngine",
"time.sleep",
"time.time",
"ipf.error.StepError",
"multiprocessing.Queue",
"ipf.error.NoMoreInputsError",
"multiprocessing.Process.__init__"
] | [((1573, 1611), 'multiprocessing.Process.__init__', 'multiprocessing.Process.__init__', (['self'], {}), '(self)\n', (1605, 1611), False, 'import multiprocessing\n'), ((2301, 2324), 'multiprocessing.Queue', 'multiprocessing.Queue', ([], {}), '()\n', (2322, 2324), False, 'import multiprocessing\n'), ((6762, 6798), 'ipf.e... |
import itchat
import datetime, os, platform, time
import cv2
import face_recognition as face
from sklearn.externals import joblib
def send_move(friends_name, text):
users = itchat.search_friends(name = friends_name)
print(users)
userName = users[0]['UserName']
itchat.send(text, toUserName = userName)
... | [
"itchat.send",
"cv2.waitKey",
"face_recognition.face_encodings",
"itchat.msg_register",
"itchat.search_friends",
"os.path.isfile",
"sklearn.externals.joblib.load",
"itchat.send_image",
"itchat.auto_login",
"face_recognition.load_image_file",
"itchat.run"
] | [((796, 836), 'itchat.msg_register', 'itchat.msg_register', (['itchat.content.TEXT'], {}), '(itchat.content.TEXT)\n', (815, 836), False, 'import itchat\n'), ((1169, 1213), 'sklearn.externals.joblib.load', 'joblib.load', (['"""./face_regonition/my_face.pkl"""'], {}), "('./face_regonition/my_face.pkl')\n", (1180, 1213), ... |
import pandas as pd
from src.config import Config
config = Config()
dfs = []
for cloth in ['blouse', 'skirt', 'outwear', 'dress', 'trousers']:
df = pd.read_csv(config.proj_path + 'kp_predictions/' + cloth + '.csv')
dfs.append(df)
res_df = pd.concat(dfs)
res_df.to_csv(config.proj_path +'kp_prediction... | [
"pandas.read_csv",
"pandas.concat",
"src.config.Config"
] | [((63, 71), 'src.config.Config', 'Config', ([], {}), '()\n', (69, 71), False, 'from src.config import Config\n'), ((258, 272), 'pandas.concat', 'pd.concat', (['dfs'], {}), '(dfs)\n', (267, 272), True, 'import pandas as pd\n'), ((161, 227), 'pandas.read_csv', 'pd.read_csv', (["(config.proj_path + 'kp_predictions/' + clo... |
### Author : <NAME>
# --> Implementation of **K-MEANS** algorithim.
"""
#Importing the Libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random
#Reading the dataset
iris = pd.read_csv('https://raw.githubusercontent.com/Piyush9323/NaiveBayes_in_Python/main/iris.csv')
#iris.head(... | [
"sklearn.cluster.KMeans"
] | [((3181, 3232), 'sklearn.cluster.KMeans', 'KMeans', ([], {'n_clusters': '(3)', 'max_iter': '(100)', 'random_state': '(15)'}), '(n_clusters=3, max_iter=100, random_state=15)\n', (3187, 3232), False, 'from sklearn.cluster import KMeans\n')] |
# -*- coding: utf-8 -*-
"""Tests for :mod:`~utilipy.utils`."""
__all__ = [
"test_init_data_utils",
"test_init_decorators",
"test_init_imports",
"test_init_ipython",
"test_init_math",
"test_init_plot",
"test_init_scripts",
"test_init_utils",
"test_utils_top_level_imports",
]
####... | [
"os.path.isdir",
"os.path.split",
"os.listdir"
] | [((6466, 6482), 'os.listdir', 'os.listdir', (['drct'], {}), '(drct)\n', (6476, 6482), False, 'import os\n'), ((6341, 6370), 'os.path.split', 'os.path.split', (['utils.__file__'], {}), '(utils.__file__)\n', (6354, 6370), False, 'import os\n'), ((6540, 6572), 'os.path.isdir', 'os.path.isdir', (["(drct + '/' + file)"], {}... |
import os
import re
import itertools
import cv2
import time
import numpy as np
import torch
from torch.autograd import Variable
from utils.craft_utils import getDetBoxes, adjustResultCoordinates
from data import imgproc
from data.dataset import SynthTextDataSet
import math
import xml.etree.ElementTree as elemTree
#... | [
"data.imgproc.resize_aspect_ratio",
"xml.etree.ElementTree.parse",
"data.imgproc.cvt2HeatmapImg",
"ipdb.set_trace",
"data.imgproc.normalizeMeanVariance",
"os.walk",
"numpy.expand_dims",
"math.sin",
"utils.craft_utils.adjustResultCoordinates",
"cv2.imread",
"numpy.array",
"math.cos",
"itertoo... | [((531, 546), 'math.cos', 'math.cos', (['theta'], {}), '(theta)\n', (539, 546), False, 'import math\n'), ((562, 577), 'math.sin', 'math.sin', (['theta'], {}), '(theta)\n', (570, 577), False, 'import math\n'), ((1181, 1200), 'xml.etree.ElementTree.parse', 'elemTree.parse', (['xml'], {}), '(xml)\n', (1195, 1200), True, '... |
from time import time
from telemetry_datastore import Datastore
def data_push_to_cloud(data_points):
last_id = 0
for data_point in data_points:
last_id = data_point["id"]
return last_id
if __name__ == '__main__':
start_time = time()
total = 0
index = 0
batch_size = 1000
with... | [
"telemetry_datastore.Datastore",
"time.time"
] | [((255, 261), 'time.time', 'time', ([], {}), '()\n', (259, 261), False, 'from time import time\n'), ((321, 352), 'telemetry_datastore.Datastore', 'Datastore', (['"""/tmp/telemetry.db3"""'], {}), "('/tmp/telemetry.db3')\n", (330, 352), False, 'from telemetry_datastore import Datastore\n'), ((672, 678), 'time.time', 'tim... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import *
admin.site.register(VotingEvent)
admin.site.register(Question)
admin.site.register(Choice)
| [
"django.contrib.admin.site.register"
] | [((121, 153), 'django.contrib.admin.site.register', 'admin.site.register', (['VotingEvent'], {}), '(VotingEvent)\n', (140, 153), False, 'from django.contrib import admin\n'), ((154, 183), 'django.contrib.admin.site.register', 'admin.site.register', (['Question'], {}), '(Question)\n', (173, 183), False, 'from django.con... |
import os
import errno
ERRNO_STRINGS = [
os.strerror(x).lower() for x in errno.errorcode.keys()
]
MANPAGE_MAPPING = {
'.ldaprc': ['http://man7.org/linux/man-pages/man5/.ldaprc.5.html'],
'30-systemd-environment-d-generator': ['http://man7.org/linux/man-pages/man7/30-systemd-environment-d-generator.7.html',
... | [
"errno.errorcode.keys",
"os.strerror"
] | [((78, 100), 'errno.errorcode.keys', 'errno.errorcode.keys', ([], {}), '()\n', (98, 100), False, 'import errno\n'), ((46, 60), 'os.strerror', 'os.strerror', (['x'], {}), '(x)\n', (57, 60), False, 'import os\n')] |
from PIL import Image
import pytesseract
import os
import openpyxl as xl
from pytesseract import Output
from pytesseract import pytesseract as pt
import numpy as np
from matplotlib import pyplot as plt
import cv2
from imutils.object_detection import non_max_suppression
class Scan():
def __init__(self,fol... | [
"numpy.load",
"numpy.abs",
"openpyxl.load_workbook",
"numpy.hsplit",
"numpy.sin",
"numpy.arange",
"cv2.imshow",
"os.chdir",
"numpy.unique",
"cv2.line",
"cv2.selectROI",
"cv2.cvtColor",
"cv2.imwrite",
"cv2.boundingRect",
"cv2.Laplacian",
"numpy.repeat",
"pytesseract.image_to_boxes",
... | [((484, 505), 'os.chdir', 'os.chdir', (['self.folder'], {}), '(self.folder)\n', (492, 505), False, 'import os\n'), ((520, 545), 'PIL.Image.open', 'Image.open', (['self.readfile'], {}), '(self.readfile)\n', (530, 545), False, 'from PIL import Image\n'), ((579, 622), 'pytesseract.image_to_string', 'pytesseract.image_to_s... |
##############################################################################
# Copyright (c) 2016 Huawei Technologies Co.,Ltd and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, ... | [
"tornado.options.define"
] | [((608, 676), 'tornado.options.define', 'define', (['"""port"""'], {'default': '(8000)', 'help': '"""run on the given port"""', 'type': 'int'}), "('port', default=8000, help='run on the given port', type=int)\n", (614, 676), False, 'from tornado.options import define\n')] |
from flask import has_request_context, request
from flask_login import current_user as user
import logging
class MyFormatter(logging.Formatter): # test: no cover
def __init__(self, fmt, style) -> None:
super().__init__(fmt=fmt, style=style)
def format(self, record):
if user:
if u... | [
"flask.has_request_context"
] | [((497, 518), 'flask.has_request_context', 'has_request_context', ([], {}), '()\n', (516, 518), False, 'from flask import has_request_context, request\n')] |
"""Access to all categorizations is provided directly at the module level, using the
names of categorizations. To access the example categorization `Excat`, simply use
`climate_categories.Excat` .
"""
__author__ = """<NAME>"""
__email__ = "<EMAIL>"
__version__ = "0.7.1"
import importlib
import importlib.resources
imp... | [
"importlib.import_module"
] | [((945, 1015), 'importlib.import_module', 'importlib.import_module', (['f""".data.{name}"""'], {'package': '"""climate_categories"""'}), "(f'.data.{name}', package='climate_categories')\n", (968, 1015), False, 'import importlib\n')] |
import numpy as np
import json
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
class YarrHisto1d:
def __init__(self, data: np.array, metadata: json = {}) -> None:
# need to check shape
self._histogram = data
self._name = ""
self._overflow = 0.0
... | [
"logging.getLogger",
"logging.basicConfig"
] | [((48, 69), 'logging.basicConfig', 'logging.basicConfig', ([], {}), '()\n', (67, 69), False, 'import logging\n'), ((79, 106), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (96, 106), False, 'import logging\n')] |
"""
A :class:`~Dataset` represents a collection of data suitable for feeding into a model.
For example, when you train a model, you will likely have a *training* dataset and a *validation* dataset.
"""
import logging
from collections import defaultdict
from typing import Dict, List, Union
import numpy
import tqdm
fr... | [
"collections.defaultdict",
"tqdm.tqdm",
"allennlp.common.checks.ConfigurationError",
"logging.getLogger"
] | [((474, 501), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (491, 501), False, 'import logging\n'), ((2566, 2591), 'tqdm.tqdm', 'tqdm.tqdm', (['self.instances'], {}), '(self.instances)\n', (2575, 2591), False, 'import tqdm\n'), ((3257, 3274), 'collections.defaultdict', 'defaultdict', (['... |
#!/usr/bin/env python3
import os
from time import sleep
from glob import glob
from shutil import copytree, rmtree, ignore_patterns
from jinja2 import Environment, FileSystemLoader, select_autoescape
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
env = Environment(
loade... | [
"shutil.ignore_patterns",
"os.path.basename",
"jinja2.select_autoescape",
"time.sleep",
"jinja2.FileSystemLoader",
"glob.glob",
"shutil.rmtree",
"os.path.join",
"watchdog.observers.Observer"
] | [((1315, 1325), 'watchdog.observers.Observer', 'Observer', ([], {}), '()\n', (1323, 1325), False, 'from watchdog.observers import Observer\n'), ((322, 365), 'jinja2.FileSystemLoader', 'FileSystemLoader', (["['examples', 'templates']"], {}), "(['examples', 'templates'])\n", (338, 365), False, 'from jinja2 import Environ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import logging
from flask import Blueprint
from flask import request
from api.utils.responses import response_with
from api.utils import responses as resp
from api.models.person import Person, PersonSchema
from api.models.group import Group, GroupSchema
from api.models.email i... | [
"logging.error",
"flask.Blueprint",
"api.utils.responses.response_with",
"api.models.person.PersonSchema",
"api.models.group.GroupSchema",
"api.models.person.Person.query.filter_by",
"api.models.group.Group.query.filter_by",
"flask.request.get_json",
"api.models.person.Person.query.join"
] | [((349, 385), 'flask.Blueprint', 'Blueprint', (['"""route_general"""', '__name__'], {}), "('route_general', __name__)\n", (358, 385), False, 'from flask import Blueprint\n'), ((9325, 9382), 'api.utils.responses.response_with', 'response_with', (['resp.SUCCESS_200'], {'value': "{'person': dumped}"}), "(resp.SUCCESS_200,... |
import unittest
from programy.config.file.yaml_file import YamlConfigurationFile
from programy.clients.polling.twitter.config import TwitterConfiguration
from programy.clients.events.console.config import ConsoleConfiguration
class TwitterConfigurationTests(unittest.TestCase):
def test_init(self):
yaml ... | [
"programy.clients.polling.twitter.config.TwitterConfiguration",
"programy.config.file.yaml_file.YamlConfigurationFile",
"programy.clients.events.console.config.ConsoleConfiguration"
] | [((322, 345), 'programy.config.file.yaml_file.YamlConfigurationFile', 'YamlConfigurationFile', ([], {}), '()\n', (343, 345), False, 'from programy.config.file.yaml_file import YamlConfigurationFile\n'), ((813, 835), 'programy.clients.polling.twitter.config.TwitterConfiguration', 'TwitterConfiguration', ([], {}), '()\n'... |
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression, RANSACRegressor
from sklearn.preprocessing import PolynomialFeatures
import matplotlib.pyplot as plt
# housing_data = pd.read_fwf("https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data", header=None)
hous... | [
"pandas.read_fwf",
"sklearn.preprocessing.PolynomialFeatures",
"sklearn.linear_model.LinearRegression"
] | [((331, 379), 'pandas.read_fwf', 'pd.read_fwf', (['"""../Data/housing.data"""'], {'header': 'None'}), "('../Data/housing.data', header=None)\n", (342, 379), True, 'import pandas as pd\n'), ((911, 929), 'sklearn.linear_model.LinearRegression', 'LinearRegression', ([], {}), '()\n', (927, 929), False, 'from sklearn.linear... |
import copy
import numpy as np
from sklearn.base import RegressorMixin
from spinesTS.base import EstimatorMixin
class Pipeline(RegressorMixin, EstimatorMixin):
"""estimators pipeline """
def __init__(self, steps:[tuple]):
"""
Demo:
'''python
from spinesTS.... | [
"copy.deepcopy"
] | [((1445, 1467), 'copy.deepcopy', 'copy.deepcopy', (['train_x'], {}), '(train_x)\n', (1458, 1467), False, 'import copy\n'), ((1481, 1503), 'copy.deepcopy', 'copy.deepcopy', (['train_y'], {}), '(train_y)\n', (1494, 1503), False, 'import copy\n'), ((2359, 2380), 'copy.deepcopy', 'copy.deepcopy', (['x_pred'], {}), '(x_pred... |
# generated from rosidl_generator_py/resource/_idl.py.em
# with input from control_msgs:msg/PidState.idl
# generated code does not contain a copyright notice
# Import statements for member types
import rosidl_parser.definition # noqa: E402, I100
class Metaclass_PidState(type):
"""Metaclass of message 'PidStat... | [
"std_msgs.msg.Header.__class__.__import_type_support__",
"std_msgs.msg.Header",
"copy.copy",
"builtin_interfaces.msg.Duration.__class__.__import_type_support__",
"rosidl_generator_py.import_type_support",
"traceback.format_exc",
"logging.getLogger",
"builtin_interfaces.msg.Duration"
] | [((7199, 7232), 'copy.copy', 'copy', (['cls._fields_and_field_types'], {}), '(cls._fields_and_field_types)\n', (7203, 7232), False, 'from copy import copy\n'), ((651, 686), 'rosidl_generator_py.import_type_support', 'import_type_support', (['"""control_msgs"""'], {}), "('control_msgs')\n", (670, 686), False, 'from rosi... |
from plaso.lib.eventdata import EventTimestamp
from case_plaso.event_exporter import EventExporter
@EventExporter.register('fs:stat:ntfs')
class NTFSExporter(EventExporter):
TIMESTAMP_MAP = {
EventTimestamp.CREATION_TIME: 'mftFileNameCreatedTime',
EventTimestamp.MODIFICATION_TIME: 'mftFileNameM... | [
"case_plaso.event_exporter.EventExporter.register"
] | [((104, 142), 'case_plaso.event_exporter.EventExporter.register', 'EventExporter.register', (['"""fs:stat:ntfs"""'], {}), "('fs:stat:ntfs')\n", (126, 142), False, 'from case_plaso.event_exporter import EventExporter\n')] |
from typing import Any, List, Literal, TypedDict
from .FHIR_Address import FHIR_Address
from .FHIR_CodeableConcept import FHIR_CodeableConcept
from .FHIR_ContactPoint import FHIR_ContactPoint
from .FHIR_Element import FHIR_Element
from .FHIR_HumanName import FHIR_HumanName
from .FHIR_Period import FHIR_Period
from .FH... | [
"typing.TypedDict"
] | [((547, 959), 'typing.TypedDict', 'TypedDict', (['"""FHIR_Patient_Contact"""', "{'id': FHIR_string, 'extension': List[Any], 'modifierExtension': List[Any],\n 'relationship': List[FHIR_CodeableConcept], 'name': FHIR_HumanName,\n 'telecom': List[FHIR_ContactPoint], 'address': FHIR_Address, 'gender':\n Literal['m... |
#!/usr/bin/env python3
from ev3dev.ev3 import *
from ev3dev2.motor import OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D, MoveTank, MediumMotor, LargeMotor
from ev3dev2.sensor import INPUT_1, INPUT_2, INPUT_3
from ev3dev2.sensor.lego import GyroSensor
import time
tank = MoveTank(OUTPUT_C, OUTPUT_D)
Sensor_Cor[0].mode = 'COL-... | [
"ev3dev2.motor.MoveTank"
] | [((264, 292), 'ev3dev2.motor.MoveTank', 'MoveTank', (['OUTPUT_C', 'OUTPUT_D'], {}), '(OUTPUT_C, OUTPUT_D)\n', (272, 292), False, 'from ev3dev2.motor import OUTPUT_A, OUTPUT_B, OUTPUT_C, OUTPUT_D, MoveTank, MediumMotor, LargeMotor\n')] |
''' Naively optimize a trajectory of inputs.
'''
import tensorflow as tf
def run_naive_trajopt(env, x_0, u_init):
'''
Runs a naive trajectory optimization using built-in TensorFlow optimizers.
'''
# Validate u_init shape.
N = u_init.shape[0]
assert u_init.shape == (N, env.get_num_actuators)
... | [
"tensorflow.global_variables_initializer",
"tensorflow.Session",
"tensorflow.constant",
"tensorflow.Variable",
"tensorflow.train.GradientDescentOptimizer"
] | [((368, 387), 'tensorflow.Variable', 'tf.Variable', (['u_init'], {}), '(u_init)\n', (379, 387), True, 'import tensorflow as tf\n'), ((459, 475), 'tensorflow.constant', 'tf.constant', (['(0.0)'], {}), '(0.0)\n', (470, 475), True, 'import tensorflow as tf\n'), ((590, 642), 'tensorflow.train.GradientDescentOptimizer', 'tf... |
from rest_framework import serializers
from recycle.models import Location, CommercialRequest, Transaction
from recycle.validators import IsGarbageCollectorValidator, IsCommercialValidator, DateIsNotPast
class LocationSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField()
open_time = serializers... | [
"rest_framework.serializers.SerializerMethodField",
"rest_framework.serializers.ListField",
"rest_framework.serializers.ReadOnlyField",
"recycle.validators.DateIsNotPast",
"recycle.validators.IsCommercialValidator",
"recycle.validators.IsGarbageCollectorValidator"
] | [((268, 295), 'rest_framework.serializers.ReadOnlyField', 'serializers.ReadOnlyField', ([], {}), '()\n', (293, 295), False, 'from rest_framework import serializers\n'), ((309, 344), 'rest_framework.serializers.SerializerMethodField', 'serializers.SerializerMethodField', ([], {}), '()\n', (342, 344), False, 'from rest_f... |