code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import socket
from time import sleep
from zeroconf import IPVersion, ServiceInfo, Zeroconf
class BonjourService:
ip_version = IPVersion.V4Only
def __init__(self, host, type, domain, port, ips):
self.info = ServiceInfo(
type + domain,
host + '.' + type + domain,
add... | [
"socket.inet_aton",
"zeroconf.Zeroconf"
] | [((516, 552), 'zeroconf.Zeroconf', 'Zeroconf', ([], {'ip_version': 'self.ip_version'}), '(ip_version=self.ip_version)\n', (524, 552), False, 'from zeroconf import IPVersion, ServiceInfo, Zeroconf\n'), ((330, 350), 'socket.inet_aton', 'socket.inet_aton', (['ip'], {}), '(ip)\n', (346, 350), False, 'import socket\n')] |
from flask import Flask
from flask import make_response
from flask_restful import Resource
from flask_restful import Api
import os
import os.path
def stat(path):
st = os.stat(path)
s = {}
s['atime'] = st.st_atime
s['blksize'] = st.st_blksize
s['blocks'] = st.st_blocks
s['ctime'] = st.st_ctime
... | [
"flask_restful.Api",
"os.stat",
"os.path.isdir",
"flask.Flask",
"os.path.join",
"os.listdir"
] | [((1029, 1044), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (1034, 1044), False, 'from flask import Flask\n'), ((1051, 1059), 'flask_restful.Api', 'Api', (['app'], {}), '(app)\n', (1054, 1059), False, 'from flask_restful import Api\n'), ((173, 186), 'os.stat', 'os.stat', (['path'], {}), '(path)\n', (180... |
# -*- coding: utf-8 -*-
from copy import deepcopy
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError
from django_filters.fields import BaseCSVField
from django_filters.widgets import CSVWidget
class ListCSVWidget(CSVWidget):
def... | [
"copy.deepcopy",
"django.utils.translation.ugettext_lazy",
"django.core.exceptions.ValidationError"
] | [((818, 875), 'django.utils.translation.ugettext_lazy', '_', (['"""List query expects minimum {} and maximum {} values."""'], {}), "('List query expects minimum {} and maximum {} values.')\n", (819, 875), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((899, 927), 'django.utils.translation.ugettext... |
from flask import render_template
from flask_login import login_required
from application.auth.models import VIEW_DASHBOARDS
from application.dashboard import dashboard_blueprint
from application.dashboard.data_helpers import (
get_published_dashboard_data,
get_ethnic_groups_dashboard_data,
get_ethnic_gro... | [
"application.dashboard.data_helpers.get_ethnicity_classifications_dashboard_data",
"application.dashboard.data_helpers.get_published_dashboard_data",
"application.dashboard.data_helpers.get_geographic_breakdown_dashboard_data",
"application.factory.page_service.get_topics",
"application.dashboard.data_helpe... | [((726, 755), 'application.dashboard.dashboard_blueprint.route', 'dashboard_blueprint.route', (['""""""'], {}), "('')\n", (751, 755), False, 'from application.dashboard import dashboard_blueprint\n'), ((773, 798), 'application.utils.user_can', 'user_can', (['VIEW_DASHBOARDS'], {}), '(VIEW_DASHBOARDS)\n', (781, 798), Fa... |
import copy
from saleor.extensions import ConfigurationTypeField
from saleor.extensions.models import PluginConfiguration
from saleor.extensions.plugins.anonymize.plugin import AnonymizePlugin
from tests.extensions.sample_plugins import PluginSample
from tests.extensions.utils import get_config_value
def test_update... | [
"copy.deepcopy",
"saleor.extensions.models.PluginConfiguration.objects.all",
"tests.extensions.sample_plugins.PluginSample",
"saleor.extensions.plugins.anonymize.plugin.AnonymizePlugin",
"tests.extensions.sample_plugins.PluginSample.get_plugin_configuration",
"tests.extensions.utils.get_config_value"
] | [((522, 536), 'tests.extensions.sample_plugins.PluginSample', 'PluginSample', ([], {}), '()\n', (534, 536), False, 'from tests.extensions.sample_plugins import PluginSample\n'), ((546, 579), 'saleor.extensions.models.PluginConfiguration.objects.all', 'PluginConfiguration.objects.all', ([], {}), '()\n', (577, 579), Fals... |
"""
author: <NAME>, <EMAIL>
date: 3/2021
This script takes in a polygon GIS feature class of 1 to X features and uses a bunch of
pre-generated GIS data describing various things that are important to determining
solar site suitability and spits out a table of all those things for each site, one line per
input s... | [
"pandas.DataFrame",
"arcpy.SelectLayerByLocation_management",
"arcpy.da.SearchCursor",
"arcpy.CheckOutExtension",
"pandas.read_csv",
"arcpy.sa.Times",
"arcpy.SearchCursor",
"arcpy.CopyFeatures_management",
"arcpy.gp.ZonalStatisticsAsTable",
"arcpy.MakeFeatureLayer_management",
"arcpy.Copy_manage... | [((634, 668), 'arcpy.CheckOutExtension', 'arcpy.CheckOutExtension', (['"""spatial"""'], {}), "('spatial')\n", (657, 668), False, 'import arcpy\n'), ((866, 929), 'pandas.read_csv', 'pan.read_csv', (["(ws + '\\\\Python\\\\SiteProfileOutputTemplateTwo.csv')"], {}), "(ws + '\\\\Python\\\\SiteProfileOutputTemplateTwo.csv')\... |
import django
from pkg_resources import DistributionNotFound, get_distribution
try:
__version__ = get_distribution("django-silk").version
except DistributionNotFound:
pass
if django.VERSION < (3, 2):
default_app_config = "silk.apps.SilkAppConfig"
| [
"pkg_resources.get_distribution"
] | [((103, 134), 'pkg_resources.get_distribution', 'get_distribution', (['"""django-silk"""'], {}), "('django-silk')\n", (119, 134), False, 'from pkg_resources import DistributionNotFound, get_distribution\n')] |
"""Docstring"""
from .wrapper import Amber
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
try:
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
except Exception as e:
print(e)
tf.logging.set_verbosity(tf.logging.ERROR)
from .wrapper import Amber
from . import archi... | [
"tensorflow.compat.v1.logging.set_verbosity",
"tensorflow.logging.set_verbosity"
] | [((127, 189), 'tensorflow.compat.v1.logging.set_verbosity', 'tf.compat.v1.logging.set_verbosity', (['tf.compat.v1.logging.ERROR'], {}), '(tf.compat.v1.logging.ERROR)\n', (161, 189), True, 'import tensorflow as tf\n'), ((230, 272), 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.ERROR'], {}... |
import pytest
from botocore.exceptions import ClientError
from moto import mock_s3
@pytest.mark.parametrize('path, key', [
(
'test_server/hourly/file1.txt',
'test_server/hourly/file1.txt'
),
(
's3://test-bucket/test_server/hourly/file1.txt',
'test_server/hourly/file1.txt'
... | [
"pytest.mark.parametrize",
"pytest.raises"
] | [((86, 286), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""path, key"""', "[('test_server/hourly/file1.txt', 'test_server/hourly/file1.txt'), (\n 's3://test-bucket/test_server/hourly/file1.txt',\n 'test_server/hourly/file1.txt')]"], {}), "('path, key', [('test_server/hourly/file1.txt',\n 'test_se... |
#
# Metrix++, Copyright 2009-2013, Metrix++ Project
# Link: http://metrixplusplus.sourceforge.net
#
# This file is a part of Metrix++ Tool.
#
# Metrix++ is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the ... | [
"sys._getframe"
] | [((47207, 47223), 'sys._getframe', 'sys._getframe', (['(1)'], {}), '(1)\n', (47220, 47223), False, 'import sys\n')] |
import os
from bs4 import BeautifulSoup
import pickle
path = '/Users/brianandika/Documents/HACKATHON/ingredients'
allIngredientsSet = set()
allDishes = list()
dishToIngredientsDict = {}
dishHTMLDict = {}
for filename in os.listdir(path):
## print(filename)
f = open(path+'/'+filename)
soup = BeautifulSou... | [
"bs4.BeautifulSoup",
"pickle.dump",
"os.listdir"
] | [((222, 238), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (232, 238), False, 'import os\n'), ((308, 339), 'bs4.BeautifulSoup', 'BeautifulSoup', (['f', '"""html.parser"""'], {}), "(f, 'html.parser')\n", (321, 339), False, 'from bs4 import BeautifulSoup\n'), ((1201, 1268), 'pickle.dump', 'pickle.dump', (['dis... |
from asyncio import Queue as AsyncioQueue, AbstractEventLoop, iscoroutinefunction
from collections import deque as Deque
from typing import (Deque as TypingDeque, TypeVar, Callable as TypingCallable, Coroutine as TypingCoroutine,
AsyncGenerator as TypingAsyncGenerator, Union as TypingUnion)
from wea... | [
"asyncio.iscoroutinefunction",
"typing.TypeVar",
"weakref.ref",
"asyncio.Queue",
"collections.deque"
] | [((361, 381), 'typing.TypeVar', 'TypeVar', (['"""EventData"""'], {}), "('EventData')\n", (368, 381), False, 'from typing import Deque as TypingDeque, TypeVar, Callable as TypingCallable, Coroutine as TypingCoroutine, AsyncGenerator as TypingAsyncGenerator, Union as TypingUnion\n'), ((690, 697), 'collections.deque', 'De... |
# Copyright (c) 2012 <NAME> <<EMAIL>> and
# CARET, University of Cambridge http://www.caret.cam.ac.uk/
#
# 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 restrictio... | [
"django.utils.crypto.constant_time_compare",
"raven.Validator",
"django.contrib.auth.models.User.objects.get_or_create"
] | [((1648, 1707), 'raven.Validator', 'raven.Validator', (['keys'], {'expected_post_login_url': 'expected_url'}), '(keys, expected_post_login_url=expected_url)\n', (1663, 1707), False, 'import raven\n'), ((4189, 4234), 'django.contrib.auth.models.User.objects.get_or_create', 'User.objects.get_or_create', ([], {'username':... |
import socket
import time
import pytest
from caper.server_heartbeat import ServerHeartbeat, ServerHeartbeatTimeoutError
def test_server_heartbeat(tmp_path):
"""All methods will be tested here.
This willl test 3 things:
- can read from file
- can get hostname of this machine
- can ign... | [
"socket.gethostname",
"pytest.raises",
"time.sleep"
] | [((753, 766), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (763, 766), False, 'import time\n'), ((626, 639), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (636, 639), False, 'import time\n'), ((806, 848), 'pytest.raises', 'pytest.raises', (['ServerHeartbeatTimeoutError'], {}), '(ServerHeartbeatTimeoutError... |
def btrain(names,homepath):
import numpy as np
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
#reading data and doing work
cresult=pd.DataFrame()
nresult=pd.DataFrame()
for index in range(len(names)):
Cancer = pd.read_csv(homepath+"/train_data/cancer/"+
... | [
"pandas.DataFrame",
"pandas.concat",
"pandas.read_csv",
"warnings.filterwarnings"
] | [((91, 124), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (114, 124), False, 'import warnings\n'), ((168, 182), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (180, 182), True, 'import pandas as pd\n'), ((193, 207), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '(... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from dynamic_search.api import register
from inventory.models import Supplier, ItemTemplate
class PurchaseRequestStatus(models.Model):
name = models.CharField(verbose_name=_(u'Name'), max_length=32)
class Meta:
verb... | [
"django.utils.translation.ugettext_lazy"
] | [((5410, 5439), 'django.utils.translation.ugettext_lazy', '_', (['u"""Purchase request status"""'], {}), "(u'Purchase request status')\n", (5411, 5439), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((5477, 5499), 'django.utils.translation.ugettext_lazy', '_', (['u"""Purchase request"""'], {}), "(... |
from grift import BaseConfig, ConfigProperty
from schematics.types import IntType, StringType
from config.settings_loader import get_settings_loaders
class ExternalSearchConfig(BaseConfig):
# REDIS App Settings
REDIS_HOST = ConfigProperty(property_type=StringType())
REDIS_PASSWORD = ConfigProperty(requir... | [
"schematics.types.IntType",
"config.settings_loader.get_settings_loaders",
"grift.BaseConfig.__init__",
"schematics.types.StringType",
"grift.ConfigProperty"
] | [((299, 353), 'grift.ConfigProperty', 'ConfigProperty', ([], {'required': '(False)', 'exclude_from_varz': '(True)'}), '(required=False, exclude_from_varz=True)\n', (313, 353), False, 'from grift import BaseConfig, ConfigProperty\n'), ((586, 608), 'config.settings_loader.get_settings_loaders', 'get_settings_loaders', ([... |
"""
<NAME>
<NAME>
March 2021
Final project for Climate Dynamics
presented to Kyle Armour and <NAME>
Ocean 2-layer model
"""
## Import packages ##
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
import sys
pht = os.path.abspath('/Users/jadesauve/Documents/Python/scripts/2_layer_carb... | [
"pandas.DataFrame",
"matplotlib.pyplot.title",
"os.path.abspath",
"sys.path.append",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"numpy.arange",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] | [((249, 325), 'os.path.abspath', 'os.path.abspath', (['"""/Users/jadesauve/Documents/Python/scripts/2_layer_carbon/"""'], {}), "('/Users/jadesauve/Documents/Python/scripts/2_layer_carbon/')\n", (264, 325), False, 'import os\n'), ((1174, 1194), 'numpy.arange', 'np.arange', (['num_years'], {}), '(num_years)\n', (1183, 11... |
import subprocess
subprocess.run("pip install -r requirements.txt")
| [
"subprocess.run"
] | [((18, 67), 'subprocess.run', 'subprocess.run', (['"""pip install -r requirements.txt"""'], {}), "('pip install -r requirements.txt')\n", (32, 67), False, 'import subprocess\n')] |
#------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------------------------------------------------... | [
"atom.api.Unicode",
"atom.api.Str",
"atom.api.Bool",
"re.match",
"atom.api.Enum",
"atom.api.Typed"
] | [((808, 817), 'atom.api.Unicode', 'Unicode', ([], {}), '()\n', (815, 817), False, 'from atom.api import Atom, Bool, Typed, Enum, Str, Unicode\n'), ((2195, 2205), 'atom.api.Typed', 'Typed', (['int'], {}), '(int)\n', (2200, 2205), False, 'from atom.api import Atom, Bool, Typed, Enum, Str, Unicode\n'), ((2321, 2331), 'ato... |
"""Contains the logic for handling read model corruption invocation"""
from multiprocessing import Process, Queue
import time
import pysam
import numpy as np
from mitty.simulation.sequencing.writefastq import writer, load_qname_sidecar, parse_qname
import logging
logger = logging.getLogger(__name__)
SEED_MAX = (1 ... | [
"pysam.FastxFile",
"mitty.simulation.sequencing.writefastq.load_qname_sidecar",
"numpy.random.RandomState",
"time.time",
"mitty.simulation.sequencing.writefastq.parse_qname",
"multiprocessing.Queue",
"multiprocessing.Process",
"logging.getLogger"
] | [((276, 303), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (293, 303), False, 'import logging\n'), ((811, 841), 'mitty.simulation.sequencing.writefastq.load_qname_sidecar', 'load_qname_sidecar', (['sidecar_in'], {}), '(sidecar_in)\n', (829, 841), False, 'from mitty.simulation.sequencing... |
#!/usr/bin/env python3
import logging
import requests
import sys
from .base import get
logger = logging.getLogger(__name__)
def get_maintenance(apikey, username, state="ACT"):
endpoint = "Maintenance"
params = {
"state": state
}
try:
response = get(apikey, username, endpoint, param... | [
"sys.exit",
"logging.getLogger"
] | [((99, 126), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (116, 126), False, 'import logging\n'), ((559, 570), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (567, 570), False, 'import sys\n')] |
from vkbottle import ManySessionManager
from vkbottle.tools.test_utils import MockedClient
import pytest
@pytest.mark.asyncio
async def test_client():
client = MockedClient("some text")
text = await client.request_text("GET", "https://example.com")
await client.close()
assert text == "some text"
@py... | [
"vkbottle.tools.test_utils.MockedClient"
] | [((166, 191), 'vkbottle.tools.test_utils.MockedClient', 'MockedClient', (['"""some text"""'], {}), "('some text')\n", (178, 191), False, 'from vkbottle.tools.test_utils import MockedClient\n'), ((421, 446), 'vkbottle.tools.test_utils.MockedClient', 'MockedClient', (['"""some text"""'], {}), "('some text')\n", (433, 446... |
from datetime import timedelta
from django.core import mail
from django.db import connection
import mock
from django.utils import timezone
from bluebottle.clients.utils import LocalTenant
from bluebottle.events.models import Event
from bluebottle.events.tasks import event_tasks
from bluebottle.events.tests.factories i... | [
"bluebottle.events.models.Event.objects.get",
"bluebottle.events.tests.factories.ParticipantFactory.create_batch",
"django.utils.timezone.now",
"bluebottle.events.tasks.event_tasks",
"mock.patch",
"bluebottle.initiatives.tests.factories.InitiativeFactory.create",
"datetime.timedelta",
"bluebottle.even... | [((492, 549), 'mock.patch', 'mock.patch', (['"""bluebottle.events.models.Event.triggers"""', '[]'], {}), "('bluebottle.events.models.Event.triggers', [])\n", (502, 549), False, 'import mock\n'), ((710, 753), 'bluebottle.initiatives.tests.factories.InitiativeFactory.create', 'InitiativeFactory.create', ([], {'status': '... |
from django.shortcuts import render, redirect
from django.db.models import Sum, Count
from .forms import AddEntryForm
from django.contrib.auth.decorators import login_required
import readabledelta
import datetime
from .models import Client, TimeEntry, WorkDay
@login_required()
def index(request):
entries = Tim... | [
"django.contrib.auth.decorators.login_required",
"django.shortcuts.redirect",
"readabledelta.readabledelta",
"django.db.models.Count",
"datetime.timedelta",
"django.shortcuts.render",
"datetime.datetime.now"
] | [((265, 281), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {}), '()\n', (279, 281), False, 'from django.contrib.auth.decorators import login_required\n'), ((535, 551), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {}), '()\n', (549, 551), False, 'from django.contrib.... |
import tarfile
import tempfile
from pathlib import Path
import pytest
from dm import Dm
class TestControlArchive:
def test_build_control_archive(self) -> None:
with tempfile.TemporaryDirectory() as tempdir:
staging = Path(tempdir)
# Given a valid control directory
debi... | [
"tempfile.TemporaryDirectory",
"pathlib.Path",
"pytest.raises",
"tarfile.open",
"dm.Dm._build_control_archive"
] | [((180, 209), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (207, 209), False, 'import tempfile\n'), ((244, 257), 'pathlib.Path', 'Path', (['tempdir'], {}), '(tempdir)\n', (248, 257), False, 'from pathlib import Path\n'), ((638, 672), 'dm.Dm._build_control_archive', 'Dm._build_control_... |
from PyQt4 import QtGui
from epubcreator.gui.forms import author_data_edit_dialog_ui
from epubcreator.gui import image_edit
from epubcreator.epubbase import images, ebook_metadata
from epubcreator.misc import gui_utils, settings_store, utils
class AuthorDataEdit(QtGui.QDialog, author_data_edit_dialog_ui.Ui_AuthorDat... | [
"PyQt4.QtGui.QFileDialog.getOpenFileName",
"epubcreator.misc.gui_utils.displayStdErrorDialog",
"epubcreator.misc.settings_store.SettingsStore",
"epubcreator.gui.image_edit.ImageEdit",
"epubcreator.epubbase.images.AuthorImage",
"PyQt4.QtGui.QPixmap",
"epubcreator.epubbase.images.AuthorImage.allowedFormat... | [((1212, 1242), 'epubcreator.misc.settings_store.SettingsStore', 'settings_store.SettingsStore', ([], {}), '()\n', (1240, 1242), False, 'from epubcreator.misc import gui_utils, settings_store, utils\n'), ((1475, 1562), 'PyQt4.QtGui.QFileDialog.getOpenFileName', 'QtGui.QFileDialog.getOpenFileName', (['self', '"""Selecci... |
# Why the hell do I need to do this for python3??
import sys
import os
sys.path.append(os.path.dirname(__file__))
from appdata import Shortcut, ShortcutContext, ApplicationConfig
from keynames import get_all_valid_keynames, get_valid_keynames, is_valid_keyname
from logger import getlog, setuplog
from constants import ... | [
"os.path.dirname"
] | [((87, 112), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (102, 112), False, 'import os\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Functions to deal sample split test."""
import copy
import numpy as np
from scipy.spatial import cKDTree
from scipy.optimize import curve_fit
from astropy.table import Column, vstack
from . import wlensing
from . import visual
__all__ = ["get_mask_strait_line", "st... | [
"copy.deepcopy",
"numpy.ceil",
"numpy.asarray",
"numpy.unique",
"numpy.isfinite",
"numpy.nanmin",
"scipy.optimize.curve_fit",
"astropy.table.vstack",
"numpy.arange",
"numpy.linspace",
"scipy.spatial.cKDTree",
"astropy.table.Column",
"numpy.diag",
"numpy.digitize",
"numpy.nanmax"
] | [((713, 761), 'scipy.optimize.curve_fit', 'curve_fit', (['strait_line', 'x_arr[mask]', 'y_arr[mask]'], {}), '(strait_line, x_arr[mask], y_arr[mask])\n', (722, 761), False, 'from scipy.optimize import curve_fit\n'), ((2775, 2809), 'numpy.digitize', 'np.digitize', (['X', 'X_bins'], {'right': '(True)'}), '(X, X_bins, righ... |
#!/usr/bin/env python
#
# ----------------------------------------------------------------------
#
# <NAME>, U.S. Geological Survey
# <NAME>, GNS Science
# <NAME>, University of Chicago
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copyright (c) ... | [
"TimeStep.TimeStep.__init__",
"TimeStep.TimeStep._configure"
] | [((1720, 1749), 'TimeStep.TimeStep.__init__', 'TimeStep.__init__', (['self', 'name'], {}), '(self, name)\n', (1737, 1749), False, 'from TimeStep import TimeStep\n'), ((2568, 2593), 'TimeStep.TimeStep._configure', 'TimeStep._configure', (['self'], {}), '(self)\n', (2587, 2593), False, 'from TimeStep import TimeStep\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 28 18:30:44 2019
@author: <NAME>
Edited on Apr 18th 2019
@author: <NAME>
"""
from keras.datasets import mnist
from keras.models import Sequential, Model
from keras.layers import Input, Dense, LeakyReLU, Dropout
from keras.optimizers import Adam
imp... | [
"numpy.random.seed",
"numpy.empty",
"numpy.ones",
"keras.models.Model",
"matplotlib.pyplot.figure",
"numpy.random.randint",
"numpy.random.normal",
"keras.layers.Input",
"matplotlib.pyplot.imshow",
"keras.layers.LeakyReLU",
"matplotlib.pyplot.show",
"keras.layers.Dropout",
"matplotlib.pyplot.... | [((404, 421), 'keras.datasets.mnist.load_data', 'mnist.load_data', ([], {}), '()\n', (419, 421), False, 'from keras.datasets import mnist\n'), ((581, 608), 'keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.0002)', 'beta_1': '(0.5)'}), '(lr=0.0002, beta_1=0.5)\n', (585, 608), False, 'from keras.optimizers import Adam\n')... |
import socket
from _thread import *
import sys
import pygame
import math
import time
ip = "localhost"
port = 5555
#Color definitions
BLACK = (0,0,0)
RED = (255,0,0)
WHITE = (255,255,255)
GREEN = (0,255,0)
BLUE = (0,0,255)
PURPLE = (255,0,255)
CYAN = (0,255,255)
YELLOW = (255,255,0)
s = socket.socket(socket.AF_INET, soc... | [
"pygame.draw.line",
"pygame.draw.circle",
"math.atan2",
"pygame.draw.rect",
"pygame.display.set_mode",
"pygame.event.get",
"socket.socket",
"pygame.init",
"time.sleep",
"pygame.display.flip",
"math.degrees",
"pygame.font.Font",
"pygame.image.load",
"pygame.mouse.get_pos",
"pygame.display... | [((287, 336), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (300, 336), False, 'import socket\n'), ((495, 536), 'pygame.font.Font', 'pygame.font.Font', (['"""freesansbold.ttf"""', '(115)'], {}), "('freesansbold.ttf', 115)\n", (511, 536), Fals... |
# pylint: disable=no-member
__all__ = (
"structlog",
"LoggingConfig",
)
import logging.handlers
import traceback
import typing
import orjson
import structlog
from attack_surface_pypy import context
class LoggingConfig:
# TODO: slots?
def __init__(self, log_level: str, traceback_depth: typing.Optio... | [
"structlog.BytesLoggerFactory",
"traceback.format_exception",
"structlog.processors.StackInfoRenderer",
"structlog.processors.UnicodeDecoder",
"structlog.processors.TimeStamper",
"structlog.stdlib.PositionalArgumentsFormatter",
"attack_surface_pypy.context.request_id_var.get",
"structlog.processors.JS... | [((3070, 3102), 'attack_surface_pypy.context.request_id_var.get', 'context.request_id_var.get', (['None'], {}), '(None)\n', (3096, 3102), False, 'from attack_surface_pypy import context\n'), ((1741, 1783), 'structlog.processors.TimeStamper', 'structlog.processors.TimeStamper', ([], {'utc': '(True)'}), '(utc=True)\n', (... |
import pandas as pd
import numpy as np
df = pd.read_csv('netflix_titles.csv')
df = df.drop(['date_added', 'duration'], axis=1)
def convert_to_list(text):
try:
text = text.split(',')
if(len(text)>5):
return text[:5]
else:
return text
except:
... | [
"pandas.read_csv",
"sklearn.feature_extraction.text.CountVectorizer",
"sklearn.metrics.pairwise.cosine_similarity"
] | [((48, 81), 'pandas.read_csv', 'pd.read_csv', (['"""netflix_titles.csv"""'], {}), "('netflix_titles.csv')\n", (59, 81), True, 'import pandas as pd\n'), ((1683, 1739), 'sklearn.feature_extraction.text.CountVectorizer', 'CountVectorizer', ([], {'max_features': '(4000)', 'stop_words': '"""english"""'}), "(max_features=400... |
"""
Scrapping from command line.
"""
import argparse
import importlib
import logging
import re
from funnel_web.scrape import scrape_pkg, run_server, dump, EXCLUDES
def regex(expression):
"""
Return a compiled regular expression.
:param expression: Expression to compile.
:type expression: :class:`str`... | [
"argparse.ArgumentParser",
"funnel_web.scrape.EXCLUDES.extend",
"funnel_web.scrape.dump",
"funnel_web.scrape.scrape_pkg",
"funnel_web.scrape.run_server",
"re.compile"
] | [((419, 448), 're.compile', 're.compile', (["('%s' % expression)"], {}), "('%s' % expression)\n", (429, 448), False, 'import re\n'), ((541, 650), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Generate an indepth directed dependency graph for a given module."""'}), "(description=\n 'G... |
"""
https://leetcode.com/problems/divisor-game/
https://leetcode.com/submissions/detail/225249529/
"""
class Solution:
def divisorGame(self, N: int) -> bool:
return N % 2 == 0
import unittest
class Test(unittest.TestCase):
def test(self):
solution = Solution()
self.assertEqual(solu... | [
"unittest.main"
] | [((437, 452), 'unittest.main', 'unittest.main', ([], {}), '()\n', (450, 452), False, 'import unittest\n')] |
from context import ascii_magic
ascii_art = ascii_magic.from_image_file('lion.jpg', mode=ascii_magic.Modes.ASCII)
ascii_magic.to_file('lion.txt', ascii_art)
| [
"context.ascii_magic.to_file",
"context.ascii_magic.from_image_file"
] | [((45, 114), 'context.ascii_magic.from_image_file', 'ascii_magic.from_image_file', (['"""lion.jpg"""'], {'mode': 'ascii_magic.Modes.ASCII'}), "('lion.jpg', mode=ascii_magic.Modes.ASCII)\n", (72, 114), False, 'from context import ascii_magic\n'), ((115, 157), 'context.ascii_magic.to_file', 'ascii_magic.to_file', (['"""l... |
"""
Implementation of the @search command that resembles MUX2.
"""
from django.db.models import Q
#from src.objects.models import Object
from src.utils import OBJECT as Object
from src import defines_global
from src.cmdtable import GLOBAL_CMD_TABLE
def _parse_restriction_split(source_object, restriction_split, search... | [
"src.utils.OBJECT.objects.all",
"src.cmdtable.GLOBAL_CMD_TABLE.add_command",
"django.db.models.Q"
] | [((9347, 9459), 'src.cmdtable.GLOBAL_CMD_TABLE.add_command', 'GLOBAL_CMD_TABLE.add_command', (['"""@search"""', 'cmd_search'], {'priv_tuple': "('objects.info',)", 'help_category': '"""Building"""'}), "('@search', cmd_search, priv_tuple=(\n 'objects.info',), help_category='Building')\n", (9375, 9459), False, 'from sr... |
from __future__ import unicode_literals
from green.config import default_args
from green.output import GreenStream
from green.junit import JUnitXML, JUnitDialect, Verdict
from green.result import GreenTestResult, BaseTestResult, ProtoTest, proto_error
from io import StringIO
from sys import exc_info
from unittest i... | [
"green.junit.JUnitXML",
"io.StringIO",
"green.result.ProtoTest",
"sys.exc_info"
] | [((470, 481), 'green.result.ProtoTest', 'ProtoTest', ([], {}), '()\n', (479, 481), False, 'from green.result import GreenTestResult, BaseTestResult, ProtoTest, proto_error\n'), ((694, 704), 'io.StringIO', 'StringIO', ([], {}), '()\n', (702, 704), False, 'from io import StringIO\n'), ((858, 868), 'green.junit.JUnitXML',... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import math
import argparse
import itertools
import concurrent.futures
import pyproj
import numpy as np
import scipy.ndimage
from PIL import Image
from osgeo import gdal
gdal.UseExceptions()
def num2deg(xtile, ytile, zoom):
n = 2 ** zoom
lat = math.d... | [
"numpy.amin",
"argparse.ArgumentParser",
"numpy.clip",
"math.radians",
"os.path.dirname",
"math.cos",
"numpy.rollaxis",
"math.sinh",
"math.ceil",
"osgeo.gdal.UseExceptions",
"numpy.linalg.inv",
"osgeo.gdal.Open",
"math.tan",
"numpy.zeros",
"math.floor",
"numpy.amax",
"os.cpu_count",
... | [((230, 250), 'osgeo.gdal.UseExceptions', 'gdal.UseExceptions', ([], {}), '()\n', (248, 250), False, 'from osgeo import gdal\n'), ((477, 494), 'math.radians', 'math.radians', (['lat'], {}), '(lat)\n', (489, 494), False, 'import math\n'), ((774, 819), 'pyproj.Transformer.from_crs', 'pyproj.Transformer.from_crs', (['"""E... |
import requests
import pprint
from bs4 import BeautifulSoup
response = requests.get('https://news.ycombinator.com/news')
# print(response.text)
soup = BeautifulSoup(response.text, 'html.parser')
# print(soup)
# print(soup.body)
# print(soup.find_all('a')) => finds all the a tags
# print(soup.select('.score')) ... | [
"bs4.BeautifulSoup",
"requests.get"
] | [((72, 121), 'requests.get', 'requests.get', (['"""https://news.ycombinator.com/news"""'], {}), "('https://news.ycombinator.com/news')\n", (84, 121), False, 'import requests\n'), ((154, 197), 'bs4.BeautifulSoup', 'BeautifulSoup', (['response.text', '"""html.parser"""'], {}), "(response.text, 'html.parser')\n", (167, 19... |
#!/usr/bin/python
################################################################################
# File: led_on.py
# Usage: Called from rc.local to denote Raspberry Pi switched ON
# Description: Switches on LED at pin position 7 and ground
########################################################... | [
"RPi.GPIO.setup",
"RPi.GPIO.setmode",
"RPi.GPIO.output"
] | [((375, 397), 'RPi.GPIO.setmode', 'GPIO.setmode', (['GPIO.BCM'], {}), '(GPIO.BCM)\n', (387, 397), True, 'import RPi.GPIO as GPIO\n'), ((399, 422), 'RPi.GPIO.setup', 'GPIO.setup', (['(4)', 'GPIO.OUT'], {}), '(4, GPIO.OUT)\n', (409, 422), True, 'import RPi.GPIO as GPIO\n'), ((424, 444), 'RPi.GPIO.output', 'GPIO.output', ... |
from random import randrange, random
from pymetaheuristics.genetic_algorithm.types import Genome
def inter_mutation(
genome: Genome,
q: int = 2,
probability: float = 0.75,
**kwargs
) -> Genome:
"""At a random chance, change interposition of q genes on the Genome."""
for _ in range(q):
... | [
"random.random"
] | [((364, 372), 'random.random', 'random', ([], {}), '()\n', (370, 372), False, 'from random import randrange, random\n')] |
#!/usr/bin/env python
import os
import webbrowser
def get_bundle_id(plugin):
try:
with open(f'{plugin}/Contents/Info.plist', 'r') as info:
found = False
for line in info:
if found:
return line.partition('>')[2].partition('<')[0]
i... | [
"webbrowser.open",
"os.scandir"
] | [((517, 541), 'os.scandir', 'os.scandir', (['aaxDirectory'], {}), '(aaxDirectory)\n', (527, 541), False, 'import os\n'), ((1408, 1428), 'webbrowser.open', 'webbrowser.open', (['url'], {}), '(url)\n', (1423, 1428), False, 'import webbrowser\n')] |
import json
import logging
import os
from unittest import TestCase, skipUnless
from unittest.mock import MagicMock
from reliabilly.settings import Settings, Constants
from reliabilly.components.services.newrelic import NewRelicQueryExecutor, ResultTypes
# noinspection SqlDialectInspection
class NewRelicTests(TestCase... | [
"json.load",
"unittest.mock.MagicMock",
"os.path.dirname",
"unittest.skipUnless",
"logging.disable",
"reliabilly.components.services.newrelic.NewRelicQueryExecutor"
] | [((3672, 3731), 'unittest.skipUnless', 'skipUnless', (['Settings.RUN_SKIPPED', 'Constants.RUN_SKIPPED_MSG'], {}), '(Settings.RUN_SKIPPED, Constants.RUN_SKIPPED_MSG)\n', (3682, 3731), False, 'from unittest import TestCase, skipUnless\n'), ((352, 385), 'logging.disable', 'logging.disable', (['logging.CRITICAL'], {}), '(l... |
"""
Use the EMNIST datasets to test for SGD convergence vs randomization
"""
# ===============================================================================
#
# Imports
#
# ===============================================================================
from __future__ import print_function
import os
import argparse... | [
"pickle.dump",
"numpy.random.seed",
"argparse.ArgumentParser",
"numpy.arange",
"numpy.unique",
"keras.optimizers.adam",
"keras.layers.Flatten",
"os.path.exists",
"keras.layers.MaxPooling2D",
"numpy.random.shuffle",
"keras.utils.to_categorical",
"numpy.ceil",
"keras.layers.Dropout",
"keras.... | [((2788, 2800), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (2798, 2800), False, 'from keras.models import Sequential\n'), ((3871, 3883), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (3881, 3883), False, 'from keras.models import Sequential\n'), ((5282, 5303), 'numpy.lexsort', 'np.lexsort',... |
#******************************************************************************
# * Copyright (c) 2019, XtremeDV. 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
... | [
"os.path.dirname"
] | [((1008, 1025), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (1015, 1025), False, 'from os.path import dirname, join, abspath\n')] |
import copy
import time
import numpy as np
import open3d
import torch
import torch.nn.functional as F
# from lapsolver import solve_dense
from matplotlib import cm
from open3d import *
from open3d import *
from torch.autograd import Function
from train_open_spline_utils.src.VisUtils import tessalate_points
from train... | [
"numpy.random.seed",
"numpy.sum",
"matplotlib.cm.get_cmap",
"numpy.argmax",
"torch.sqrt",
"ipdb.set_trace",
"torch.eye",
"torch.cat",
"numpy.argmin",
"numpy.argsort",
"open3d.visualization.draw_geometries",
"numpy.mean",
"train_open_spline_utils.src.utils.visualize_point_cloud",
"numpy.ara... | [((829, 840), 'train_open_spline_utils.src.curve_utils.DrawSurfs', 'DrawSurfs', ([], {}), '()\n', (838, 840), False, 'from train_open_spline_utils.src.curve_utils import DrawSurfs\n'), ((879, 899), 'torch.manual_seed', 'torch.manual_seed', (['(2)'], {}), '(2)\n', (896, 899), False, 'import torch\n'), ((900, 917), 'nump... |
"""Chatbot script"""
# pylint: disable=invalid-name
import os
import re
import ast
import sys
import json
import math
import codecs
import decimal
import datetime
import operator
import fractions
import itertools
# Subprocess must know this is a win32 system.
sys.platform = "win32"
import subprocess # pylint: disabl... | [
"System.AppDomain.CurrentDomain.GetAssemblies",
"subprocess.Popen",
"simpleeval.SimpleEval",
"json.load",
"os.path.join",
"json.loads",
"decimal.Decimal",
"os.path.dirname",
"datetime.datetime.now",
"decimal.getcontext",
"re.sub"
] | [((388, 411), 'simpleeval.SimpleEval', 'simpleeval.SimpleEval', ([], {}), '()\n', (409, 411), False, 'import simpleeval\n'), ((8388, 8413), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (8403, 8413), False, 'import os\n'), ((10189, 10252), 'subprocess.Popen', 'subprocess.Popen', (['command']... |
from histomics_detect.anchors.create import create_anchors
from histomics_detect.anchors.filter import filter_anchors
from histomics_detect.anchors.sampling import sample_anchors
from histomics_detect.boxes import (
parameterize,
unparameterize,
clip_boxes,
tf_box_transform,
filter_edge_boxes,
)
fro... | [
"tensorflow.print",
"histomics_detect.networks.field_size.field_size",
"tensorflow.greater",
"tensorflow.reduce_max",
"histomics_detect.metrics.FalseNegativeRate",
"histomics_detect.anchors.sampling.sample_anchors",
"histomics_detect.networks.fast_rcnn.fast_rcnn",
"histomics_detect.boxes.tf_box_transf... | [((2566, 2628), 'tensorflow.cast', 'tf.cast', (['((anchors[:, 0] + anchors[:, 2] / 2) / field)', 'tf.int32'], {}), '((anchors[:, 0] + anchors[:, 2] / 2) / field, tf.int32)\n', (2573, 2628), True, 'import tensorflow as tf\n'), ((2638, 2700), 'tensorflow.cast', 'tf.cast', (['((anchors[:, 1] + anchors[:, 3] / 2) / field)'... |
#!/usr/bin/python
import sys
from apple_game import AppleFinder
from littlepython import Compiler
from CYLGame.Database import GameDB
from CYLGame.Comp import sim_competition
assert len(sys.argv) >= 2
comp_token = sys.argv[1]
game = AppleFinder
compiler = Compiler()
gamedb = GameDB(sys.argv[2])
assert gamedb.is_comp... | [
"CYLGame.Database.GameDB",
"littlepython.Compiler",
"CYLGame.Comp.sim_competition"
] | [((259, 269), 'littlepython.Compiler', 'Compiler', ([], {}), '()\n', (267, 269), False, 'from littlepython import Compiler\n'), ((279, 298), 'CYLGame.Database.GameDB', 'GameDB', (['sys.argv[2]'], {}), '(sys.argv[2])\n', (285, 298), False, 'from CYLGame.Database import GameDB\n'), ((340, 445), 'CYLGame.Comp.sim_competit... |
from mauveinternet.ordering.order import OrderItemList
def get_basket(request):
request.session.modified = True # baskets retrieved with get_basket are typically modified
try:
return request.session['BASKET']
except KeyError:
return new_basket(request)
def get_basket_if_exists(request):
... | [
"mauveinternet.ordering.order.OrderItemList"
] | [((769, 784), 'mauveinternet.ordering.order.OrderItemList', 'OrderItemList', ([], {}), '()\n', (782, 784), False, 'from mauveinternet.ordering.order import OrderItemList\n')] |
# <NAME>
# Mayo, 2020
# <EMAIL>
# Variables aleatorias
# La variable aleatoria es una función, se caracteriza por ser determinista
#
#Datos a partir de la base llamada datos.cvs
#### **************** Algoritmo **************** ####
#**********************************************... | [
"numpy.random.uniform",
"scipy.stats.norm",
"csv.reader",
"scipy.stats.rayleigh.fit",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.legend",
"scipy.stats.rayleigh",
"matplotlib.pyplot.cla",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"numpy.sqrt"
] | [((1972, 2007), 'csv.reader', 'csv.reader', (['csv_file'], {'delimiter': '""","""'}), "(csv_file, delimiter=',')\n", (1982, 2007), False, 'import csv\n'), ((2664, 2688), 'scipy.stats.rayleigh.fit', 'stats.rayleigh.fit', (['data'], {}), '(data)\n', (2682, 2688), True, 'import scipy.stats as stats\n'), ((2726, 2751), 'sc... |
import requests
url = 'https://gmit.ie'
response = requests.get(url)
#print(response.status_code)
#print(response.text)
#print(response.status_text)
#print(response.headers)
| [
"requests.get"
] | [((52, 69), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (64, 69), False, 'import requests\n')] |
#
# This file is part of pretix (Community Edition).
#
# Copyright (C) 2014-2020 <NAME> and contributors
# Copyright (C) 2020-2021 rami.io GmbH and contributors
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
# Public License as published by the Free... | [
"os.remove",
"os.path.exists",
"os.getpid"
] | [((1587, 1616), 'os.path.exists', 'os.path.exists', (['"""crashed.tmp"""'], {}), "('crashed.tmp')\n", (1601, 1616), False, 'import os\n'), ((1643, 1667), 'os.remove', 'os.remove', (['"""crashed.tmp"""'], {}), "('crashed.tmp')\n", (1652, 1667), False, 'import os\n'), ((1764, 1775), 'os.getpid', 'os.getpid', ([], {}), '(... |
import matplotlib.pyplot as plt
import numpy as np
# import numpy.linalg as la
from kernels import eval_sp_dp_QBX, sommerfeld
plt.gca().set_aspect("equal")
k = 10
alpha = k # CFIE parameter
beta = 0
interval = 10
xs = 0
ys = 5
sp, dp, _, _, _, _, _, _ = eval_sp_dp_QBX(4, k)
som_sp, _ = sommerfeld(k, beta, interval... | [
"numpy.meshgrid",
"matplotlib.pyplot.show",
"matplotlib.pyplot.gca",
"kernels.eval_sp_dp_QBX",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.figure",
"kernels.sommerfeld",
"numpy.linspace",
"numpy.real"
] | [((259, 279), 'kernels.eval_sp_dp_QBX', 'eval_sp_dp_QBX', (['(4)', 'k'], {}), '(4, k)\n', (273, 279), False, 'from kernels import eval_sp_dp_QBX, sommerfeld\n'), ((292, 329), 'kernels.sommerfeld', 'sommerfeld', (['k', 'beta', 'interval', '"""full"""'], {}), "(k, beta, interval, 'full')\n", (302, 329), False, 'from kern... |
# Copyright (c) 2017 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | [
"argparse.ArgumentParser",
"os.getcwd",
"collections.defaultdict",
"openstack_requirements.requirement.parse",
"packaging.version.Version",
"sys.exit"
] | [((896, 982), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Check if project requirements have changed"""'}), "(description=\n 'Check if project requirements have changed')\n", (919, 982), False, 'import argparse\n'), ((1222, 1252), 'collections.defaultdict', 'collections.defaultdict... |
'''
API wrapper for holytransaction blockexplorer.
See https://peercoin.holytransaction.com/info for more information.
'''
import requests
from decimal import Decimal
from .common import Provider
class Holy(Provider):
"""API wrapper for holytransaction.com blockexplorer,
it only implements queries relevant... | [
"requests.Session"
] | [((1108, 1126), 'requests.Session', 'requests.Session', ([], {}), '()\n', (1124, 1126), False, 'import requests\n')] |
"""Check the summary is not more than 54 characters."""
from pre_commit_commit_msg_hooks.common import get_commit_msg_lines
def main():
summary, _ = get_commit_msg_lines()
limit = 54
summary_len = len(summary)
if summary_len > limit:
print(summary)
print(f'Summary too long. {summary_le... | [
"pre_commit_commit_msg_hooks.common.get_commit_msg_lines"
] | [((155, 177), 'pre_commit_commit_msg_hooks.common.get_commit_msg_lines', 'get_commit_msg_lines', ([], {}), '()\n', (175, 177), False, 'from pre_commit_commit_msg_hooks.common import get_commit_msg_lines\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2018-03-27 22:07
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependen... | [
"django.db.models.TextField",
"django.db.migrations.swappable_dependency",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.FloatField",
"django.db.models.AutoField",
"django.db.models.IntegerField"
] | [((291, 348), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (322, 348), False, 'from django.db import migrations, models\n'), ((529, 622), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)... |
import sqlite3
import ProjTools as pt
conn = sqlite3.connect('music_library.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS music (
path text,
title text,
author text,
name text
)""")
def add_tape(tape):
with conn:
c.execute("INS... | [
"sqlite3.connect"
] | [((46, 81), 'sqlite3.connect', 'sqlite3.connect', (['"""music_library.db"""'], {}), "('music_library.db')\n", (61, 81), False, 'import sqlite3\n')] |
# Copyright (c) 2016 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | [
"pkgutil.iter_modules",
"pkgutil.walk_packages",
"inspect.getmembers"
] | [((893, 928), 'pkgutil.walk_packages', 'pkgutil.walk_packages', (['mod.__path__'], {}), '(mod.__path__)\n', (914, 928), False, 'import pkgutil\n'), ((1342, 1380), 'pkgutil.iter_modules', 'pkgutil.iter_modules', (['package.__path__'], {}), '(package.__path__)\n', (1362, 1380), False, 'import pkgutil\n'), ((1612, 1662), ... |
from pylo.engines.prolog import (
SWIProlog,
# GNUProlog,
XSBProlog
)
from pylo.language.lp import c_pred, c_functor, c_var, List, c_const
def test(pl):
pred1 = c_pred("pred1",1)
pred2 = c_pred("pred2",1)
const1 = c_const("const1")
const2 = c_const("const2")
x = c_var("X")
y = c... | [
"pylo.language.lp.c_pred",
"pylo.engines.prolog.SWIProlog",
"pylo.language.lp.c_var",
"pylo.engines.prolog.XSBProlog",
"pylo.language.lp.c_const"
] | [((822, 833), 'pylo.engines.prolog.SWIProlog', 'SWIProlog', ([], {}), '()\n', (831, 833), False, 'from pylo.engines.prolog import SWIProlog, XSBProlog\n'), ((853, 893), 'pylo.engines.prolog.XSBProlog', 'XSBProlog', (['"""/home/quinten/Software/XSB/"""'], {}), "('/home/quinten/Software/XSB/')\n", (862, 893), False, 'fro... |
# Generated by Django 2.2.12 on 2020-05-02 20:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stats', '0009_auto_20171026_2217'),
]
operations = [
migrations.AlterField(
model_name='plot',
name='type',
... | [
"django.db.models.CharField"
] | [((331, 788), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('KVT', 'Kamervraag vs time'), ('KVTP', 'Kamervraag vs time per party'), (\n 'KVTPS', 'Kamervraag vs time per party seat'), ('KRTH',\n 'Kamervraag reply time histogram'), ('KRT2D',\n 'Kamervraag reply time 2D histogram'), ('KRTP... |
import copy
import os
from utils.file_utils.dataset_reader_pack.ml_dataset_reader import get_TV_T_dataset, get_T_V_T_dataset
from ml_sl.rf.dt_0 import Node, save_node, load_node
from ml_sl.rf.rf_0 import RF, save_random_forest, load_random_forest
from ml_sl.ml_data_wrapper import pack_list_2_list, single_point_list_2_... | [
"utils.file_utils.dataset_reader_pack.ml_dataset_reader.get_TV_T_dataset",
"ml_sl.ml_critrions.cal_kappa",
"utils.file_utils.dataset_reader_pack.ml_dataset_reader.get_T_V_T_dataset",
"ml_sl.rf.rf_0.load_random_forest",
"ml_sl.ml_critrions.cal_accuracy",
"ml_sl.ml_data_wrapper.split_labeled_dataset_list",
... | [((894, 950), 'utils.file_utils.dataset_reader_pack.ml_dataset_reader.get_T_V_T_dataset', 'get_T_V_T_dataset', ([], {'file_path': 'ml_dataset_pickle_file_path'}), '(file_path=ml_dataset_pickle_file_path)\n', (911, 950), False, 'from utils.file_utils.dataset_reader_pack.ml_dataset_reader import get_TV_T_dataset, get_T_V... |
"""some lots are products for G-Cloud 9
Revision ID: 800
Revises: 790
Create Date: 2017-01-30 10:00:00.000000
"""
# revision identifiers, used by Alembic.
revision = '800'
down_revision = '790'
from alembic import op
def upgrade():
# Update G-Cloud 9 lot records
op.execute("""
UPDATE lots SET dat... | [
"alembic.op.execute"
] | [((278, 457), 'alembic.op.execute', 'op.execute', (['"""\n UPDATE lots SET data = \'{"unitSingular": "product", "unitPlural": "products"}\'\n WHERE slug in (\'cloud-hosting\', \'cloud-software\');\n """'], {}), '(\n """\n UPDATE lots SET data = \'{"unitSingular": "product", "unitPlural": "pro... |
"""
Tests for waffle utils views.
"""
# pylint: disable=toggle-missing-annotation
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from common.djangoapps.student.tests.factories import UserFactory
from .. import models
from .. import views as toggle_state_views
class ToggleStateVie... | [
"rest_framework.test.APIRequestFactory",
"common.djangoapps.student.tests.factories.UserFactory"
] | [((4062, 4092), 'common.djangoapps.student.tests.factories.UserFactory', 'UserFactory', ([], {'is_staff': 'is_staff'}), '(is_staff=is_staff)\n', (4073, 4092), False, 'from common.djangoapps.student.tests.factories import UserFactory\n'), ((3996, 4015), 'rest_framework.test.APIRequestFactory', 'APIRequestFactory', ([], ... |
import mountaincar
from Tilecoder import numTilings, numTiles, tilecode
from pylab import * # includes numpy
numRuns = 1
n = numTiles * 3
numEpisodes=200
gamma=1
stepsArray = zeros(numEpisodes)
returnsArray = zeros(numEpisodes)
def Qs (f,theta1):
Q=[0,0,0];
for action in range(3):
for index in f... | [
"Tilecoder.tilecode",
"mountaincar.init",
"mountaincar.sample"
] | [((641, 659), 'mountaincar.init', 'mountaincar.init', ([], {}), '()\n', (657, 659), False, 'import mountaincar\n'), ((678, 717), 'Tilecoder.tilecode', 'tilecode', (['S[0]', 'S[1]', '([-1] * numTilings)'], {}), '(S[0], S[1], [-1] * numTilings)\n', (686, 717), False, 'from Tilecoder import numTilings, numTiles, tilecode\... |
"""Authors: <NAME> and <NAME>."""
from nwb_conversion_tools.basedatainterface import BaseDataInterface
from pynwb import NWBFile
import os
import warnings
from lxml import etree as et
import numpy as np
from ..utils.neuroscope import read_lfp, write_lfp, write_spike_waveforms
class GrosmarkLFPInterface(BaseDataInter... | [
"lxml.etree.parse",
"warnings.warn",
"os.path.split",
"numpy.concatenate"
] | [((881, 908), 'os.path.split', 'os.path.split', (['session_path'], {}), '(session_path)\n', (894, 908), False, 'import os\n'), ((1354, 1384), 'numpy.concatenate', 'np.concatenate', (['shank_channels'], {}), '(shank_channels)\n', (1368, 1384), True, 'import numpy as np\n'), ((1640, 1667), 'os.path.split', 'os.path.split... |
solution_student = [] # Das ist eine Liste in der eure Antworten gespeichert werden :)
# Assignment 00:
# x = 1
# y = 1
# x == y ?? True or False ?
solution_student.append(True) # Hier wird die erste Antwort an die Liste gehangen.
# Assignment 01:
# x = [1,2]
# y = [1,2]
# x == y ?? True or False ?
solution_stude... | [
"_pickle.load"
] | [((1385, 1412), '_pickle.load', '_pickle.load', (['solution_file'], {}), '(solution_file)\n', (1397, 1412), False, 'import _pickle\n')] |
'''
URL: https://leetcode.com/problems/top-k-frequent-words/description/
Time complexity: O(nlogk)
Space complexity: O(n)
'''
from collections import defaultdict
from heapq import heappush, heappop
class FrequentNode:
def __init__(self, word, count):
self.word = word
self.count = count
def __... | [
"collections.defaultdict",
"heapq.heappop"
] | [((792, 808), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (803, 808), False, 'from collections import defaultdict\n'), ((1180, 1199), 'heapq.heappop', 'heappop', (['heap_words'], {}), '(heap_words)\n', (1187, 1199), False, 'from heapq import heappush, heappop\n'), ((1070, 1089), 'heapq.heappop',... |
from flask import Flask
app = Flask(__name__)
@app.route('/hello')
def hello():
return "Hello World , I am Flask! Test me"
'''
How to run:
$ export FLASK_APP=hello_world.py
$ export FLASK_ENV=development
$ flask.run
change export to set when using windows!
'''
| [
"flask.Flask"
] | [((31, 46), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (36, 46), False, 'from flask import Flask\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: Ampel-core/ampel/core/AmpelContext.py
# License: BSD-3-Clause
# Author: <NAME> <<EMAIL>>
# Date: 18.02.2020
# Last Modified Date: 09.01.2022
# Last Modified By: <NAME> <<EMAIL>>
from typing import Any, Lite... | [
"ampel.config.AmpelConfig.AmpelConfig",
"ampel.core.AmpelDB.AmpelDB.new",
"ampel.secret.AESecretProvider.AESecretProvider",
"ampel.core.UnitLoader.UnitLoader",
"ampel.config.builder.DistConfigBuilder.DistConfigBuilder",
"ampel.config.AmpelConfig.AmpelConfig.load",
"ampel.base.AuxUnitRegister.AuxUnitRegi... | [((3134, 3175), 'ampel.core.AmpelDB.AmpelDB.new', 'AmpelDB.new', (['alconf', 'vault'], {'one_db': 'one_db'}), '(alconf, vault, one_db=one_db)\n', (3145, 3175), False, 'from ampel.core.AmpelDB import AmpelDB\n'), ((4163, 4197), 'ampel.config.builder.DistConfigBuilder.DistConfigBuilder', 'DistConfigBuilder', ([], {'verbo... |
from decimal import Decimal
import math
import numpy as np
import pyproj
WGS84_LATLON_EPSG = 4326
# There's significant overhead in pyproj when building a Transformer object.
# Without a cache a Transformer can be built many times per request, even for
# the same CRS.
_TRANSFORMER_CACHE = {}
def reproject_latlons... | [
"math.isnan",
"pyproj.transformer.Transformer.from_crs",
"decimal.Decimal",
"numpy.floor"
] | [((1140, 1213), 'pyproj.transformer.Transformer.from_crs', 'pyproj.transformer.Transformer.from_crs', (['from_crs', 'to_crs'], {'always_xy': '(True)'}), '(from_crs, to_crs, always_xy=True)\n', (1179, 1213), False, 'import pyproj\n'), ((1476, 1494), 'numpy.floor', 'np.floor', (['(x / base)'], {}), '(x / base)\n', (1484,... |
#!/usr/bin/env python
"""Ignition API."""
from setuptools import setup
setup()
| [
"setuptools.setup"
] | [((74, 81), 'setuptools.setup', 'setup', ([], {}), '()\n', (79, 81), False, 'from setuptools import setup\n')] |
import os
import json
import unittest
from bkash_webhook import *
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
def file_reader(path: str) -> dict:
with open(path) as reader:
return json.loads(reader.read())
class BKashWebhookListenerTest(unittest.TestCase):
def setUp(self) -> None:
... | [
"os.path.dirname"
] | [((95, 120), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (110, 120), False, 'import os\n')] |
from functools import reduce
def old_fashion():
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
squared.append(i**2)
print('squared value:',squared)
def map_lambda():
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))
print('map example:',squared)
def filter_la... | [
"functools.reduce"
] | [((509, 549), 'functools.reduce', 'reduce', (['(lambda x, y: x * y)', '[1, 2, 3, 4]'], {}), '(lambda x, y: x * y, [1, 2, 3, 4])\n', (515, 549), False, 'from functools import reduce\n')] |
import requests
from collections import Counter
STOCK_DATA = 'https://bit.ly/2MzKAQg'
# pre-work: load JSON data into program
with requests.Session() as s:
data = s.get(STOCK_DATA).json()
# your turn:
def _cap_str_to_mln_float(cap):
"""If cap = 'n/a' return 0, else:
- strip off leadi... | [
"collections.Counter",
"requests.Session"
] | [((141, 159), 'requests.Session', 'requests.Session', ([], {}), '()\n', (157, 159), False, 'import requests\n'), ((1382, 1440), 'collections.Counter', 'Counter', (["(_['sector'] for _ in data if _['sector'] != 'n/a')"], {}), "(_['sector'] for _ in data if _['sector'] != 'n/a')\n", (1389, 1440), False, 'from collections... |
from fabric.api import run, env, roles
from fabric.contrib.project import rsync_project
env.roledefs = {
'web': ['bokeh.pydata.org']}
@roles('web')
def deploy(user=False):
if user:
env.user = user
run("rm -rf /www/bokeh-old")
run("cp -ar /www/bokeh-latest /www/bokeh-old")
run("rm /www/boke... | [
"fabric.contrib.project.rsync_project",
"fabric.api.run",
"fabric.api.roles"
] | [((141, 153), 'fabric.api.roles', 'roles', (['"""web"""'], {}), "('web')\n", (146, 153), False, 'from fabric.api import run, env, roles\n'), ((219, 247), 'fabric.api.run', 'run', (['"""rm -rf /www/bokeh-old"""'], {}), "('rm -rf /www/bokeh-old')\n", (222, 247), False, 'from fabric.api import run, env, roles\n'), ((252, ... |
# -*- coding: utf-8 -*-
import logging
from utils import mongo
from utils import config
class MasterEntitiesParser:
def __init__(self):
self._logger = logging.getLogger('spud')
self.db = mongo.MongoInterface()
self.mapped_mps = config.mapped_mps
self._titles = [
"Earl",... | [
"utils.mongo.MongoInterface",
"logging.getLogger"
] | [((165, 190), 'logging.getLogger', 'logging.getLogger', (['"""spud"""'], {}), "('spud')\n", (182, 190), False, 'import logging\n'), ((209, 231), 'utils.mongo.MongoInterface', 'mongo.MongoInterface', ([], {}), '()\n', (229, 231), False, 'from utils import mongo\n')] |
# ===============================================================================
# Copyright 2015 <NAME>
#
# 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/LI... | [
"json.load"
] | [((2043, 2059), 'json.load', 'json.load', (['rfile'], {}), '(rfile)\n', (2052, 2059), False, 'import json\n')] |
import datetime
import pytest
from aiohttp.web_exceptions import HTTPOk
from freezegun import freeze_time
from sqlalchemy import desc
from auth.models import users
from its_on.models import switch_history, switches
@pytest.mark.usefixtures('setup_tables_and_data')
async def test_switches_list_without_auhtorize(clie... | [
"its_on.models.switch_history.select",
"datetime.datetime",
"its_on.models.switches.select",
"sqlalchemy.desc",
"auth.models.users.select",
"pytest.mark.parametrize",
"freezegun.freeze_time",
"its_on.models.switches.count",
"pytest.mark.usefixtures"
] | [((220, 268), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""setup_tables_and_data"""'], {}), "('setup_tables_and_data')\n", (243, 268), False, 'import pytest\n'), ((412, 460), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""setup_tables_and_data"""'], {}), "('setup_tables_and_data')\n", (435, ... |
# Import necessary modules
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
# TODO
# import ridge_x and ridge_y from /datasets
def display_plot(cv_scores, cv_scores_std):
fig = plt.figure()
ax = fig.add_subplot(1, 1,... | [
"matplotlib.pyplot.show",
"numpy.std",
"numpy.logspace",
"sklearn.model_selection.cross_val_score",
"matplotlib.pyplot.figure",
"numpy.max",
"numpy.mean",
"sklearn.linear_model.Ridge",
"numpy.sqrt"
] | [((799, 820), 'sklearn.linear_model.Ridge', 'Ridge', ([], {'normalize': '(True)'}), '(normalize=True)\n', (804, 820), False, 'from sklearn.linear_model import Ridge\n'), ((876, 898), 'numpy.logspace', 'np.logspace', (['(-4)', '(0)', '(50)'], {}), '(-4, 0, 50)\n', (887, 898), True, 'import numpy as np\n'), ((277, 289), ... |
#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(name='rasterprynt',
version='1.0.5',
description='Print raster graphics on Brother P950NW and 9800PCN',
author='<NAME> (Boxine GmbH)',
author_email='<EMAIL>',
licens... | [
"distutils.core.setup"
] | [((119, 419), 'distutils.core.setup', 'setup', ([], {'name': '"""rasterprynt"""', 'version': '"""1.0.5"""', 'description': '"""Print raster graphics on Brother P950NW and 9800PCN"""', 'author': '"""<NAME> (Boxine GmbH)"""', 'author_email': '"""<EMAIL>"""', 'license': '"""MIT"""', 'packages': "['rasterprynt']", 'install... |
import csv
import json
import os
############ You should set this ################
url = "" # url that you want to send request (e.g. https://somesites.com/graphql))
depth = 5 # depth that you want
#################################################
############ You can change this ########... | [
"json.dump",
"os.path.abspath",
"csv.reader",
"csv.writer",
"os.path.split"
] | [((343, 368), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (358, 368), False, 'import os\n'), ((376, 402), 'os.path.split', 'os.path.split', (['absFilePath'], {}), '(absFilePath)\n', (389, 402), False, 'import os\n'), ((1318, 1331), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (1328, 1... |
# Generated by Django 3.2.7 on 2021-09-24 18:03
from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migr... | [
"django.db.models.TextField",
"django.db.models.ManyToManyField",
"django.db.models.ForeignKey",
"django.db.models.CharField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.EmailField",
"django.db.models.IntegerField",
"django.db.models.DateTimeField"
] | [((5868, 5999), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'default': 'None', 'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""ProjectManager.teacherassignment"""'}), "(default=None, null=True, on_delete=django.db.models.\n deletion.CASCADE, to='ProjectManager.teacherassig... |
import torch
from model import ModelVis
import cv2
import torchvision.transforms as transforms
CLASSES = {0:"Nothing",1:"Something"}
IMAGE = "WeZmyWFd95"
# Image cropping settings
X = 700
Y = 420
SIZE = 200
# INITIALIZE THE NN
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = ModelVis(... | [
"cv2.putText",
"cv2.waitKey",
"cv2.destroyAllWindows",
"torch.load",
"cv2.imwrite",
"model.ModelVis",
"cv2.imread",
"torch.cuda.is_available",
"torchvision.transforms.Grayscale",
"torch.unsqueeze",
"torchvision.transforms.Resize",
"cv2.imshow",
"cv2.resize",
"torchvision.transforms.ToTenso... | [((311, 321), 'model.ModelVis', 'ModelVis', ([], {}), '()\n', (319, 321), False, 'from model import ModelVis\n'), ((495, 554), 'cv2.imread', 'cv2.imread', (['f"""RealtimeClassifDataCol/Something/{IMAGE}.jpg"""'], {}), "(f'RealtimeClassifDataCol/Something/{IMAGE}.jpg')\n", (505, 554), False, 'import cv2\n'), ((998, 1090... |
#!/usr/bin/env python
from __future__ import division
from __future__ import print_function
from builtins import map
from builtins import filter
from builtins import range
from past.utils import old_div
# import adddeps # fix sys.path
import math
import argparse
import ast
import collections
import json
import loggin... | [
"os.path.expanduser",
"uptune.tune",
"subprocess.Popen",
"uptune.target",
"argparse.ArgumentParser",
"past.utils.old_div",
"re.finditer",
"subprocess.check_output",
"time.time",
"time.sleep",
"os.path.isfile",
"builtins.filter",
"multiprocessing.Process",
"builtins.range",
"logging.getLo... | [((634, 663), 'logging.getLogger', 'logging.getLogger', (['"""gccflags"""'], {}), "('gccflags')\n", (651, 663), False, 'import logging\n'), ((677, 702), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (700, 702), False, 'import argparse\n'), ((3948, 3988), 'os.path.isfile', 'os.path.isfile', (['... |
"""
@File : game
@author : yulosun
@Date : 10/11/19
@license:
"""
import actr
import time
import math
import numpy as np
import numbers
import matplotlib.pyplot as plt
import SYL_spt2
import datetime
actr.load_act_r_model(r"C:\Users\syl\Desktop\ACTR_ATO\sp_new.lisp")
response = False
t = 0... | [
"matplotlib.pyplot.title",
"actr.run",
"actr.process_events",
"actr.copy_chunk",
"actr.add_text_to_exp_window",
"actr.monitor_command",
"actr.chunk_slot_value",
"numpy.arange",
"actr.remove_items_from_exp_window",
"actr.add_command",
"actr.buffer_read",
"actr.load_act_r_model",
"matplotlib.p... | [((224, 295), 'actr.load_act_r_model', 'actr.load_act_r_model', (['"""C:\\\\Users\\\\syl\\\\Desktop\\\\ACTR_ATO\\\\sp_new.lisp"""'], {}), "('C:\\\\Users\\\\syl\\\\Desktop\\\\ACTR_ATO\\\\sp_new.lisp')\n", (245, 295), False, 'import actr\n'), ((1076, 1104), 'actr.buffer_read', 'actr.buffer_read', (['"""imaginal"""'], {})... |
import asyncio
import timeit
import aiohttp
import httpx
import requests
import torequests
result: dict = {}
def print_msg(name, cost, ok):
qps = round(TOTAL_REQUEST_COUNTS / cost)
msg = f'{name: <25}: {ok} / {TOTAL_REQUEST_COUNTS} = {ok * 100 / (TOTAL_REQUEST_COUNTS)}%, cost {round(cost, 3):0>5}s, {qps: >4... | [
"timeit.default_timer",
"platform.platform",
"uvloop.install",
"aiohttp.ClientSession",
"httpx.AsyncClient",
"torequests.aiohttp_dummy.Requests",
"asyncio.ProactorEventLoop",
"asyncio.WindowsProactorEventLoopPolicy",
"torequests.main.tPool"
] | [((2547, 2554), 'torequests.main.tPool', 'tPool', ([], {}), '()\n', (2552, 2554), False, 'from torequests.main import tPool\n'), ((2567, 2589), 'timeit.default_timer', 'timeit.default_timer', ([], {}), '()\n', (2587, 2589), False, 'import timeit\n'), ((3059, 3081), 'timeit.default_timer', 'timeit.default_timer', ([], {... |
#!/usr/bin/env python3
from os.path import dirname
from os.path import realpath
from os.path import join
import time
import pytest
import sys
import re
sys.path.append(join(dirname(realpath(__file__)), *[".."]))
def transform_input(input_):
# custom transform for the day
data = input_.splitlines()
# Dic... | [
"os.path.join",
"os.path.realpath",
"time.time",
"pytest.mark.parametrize",
"re.search"
] | [((3332, 3468), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""input1, output1"""', "[('data/test_input0.txt', 2), ('data/test_input1.txt', 2), (\n 'data/test_input2.txt', 3)]"], {}), "('input1, output1', [('data/test_input0.txt', 2), (\n 'data/test_input1.txt', 2), ('data/test_input2.txt', 3)])\n", ... |
#! /usr/bin/python
import time
import _inotify
import errno
def on_write(event):
print('write')
def on_read(event):
print("read")
def on_attrib(event):
print("attribute change")
def on_move(event):
print("move")
def on_open(event):
print("open")
def on_close(event):
print("close")
def on... | [
"_inotify.create",
"_inotify.read_event",
"time.sleep",
"_inotify.add"
] | [((1322, 1339), '_inotify.create', '_inotify.create', ([], {}), '()\n', (1337, 1339), False, 'import _inotify\n'), ((1345, 1393), '_inotify.add', '_inotify.add', (['fd', '"""example"""', '_inotify.ALL_EVENTS'], {}), "(fd, 'example', _inotify.ALL_EVENTS)\n", (1357, 1393), False, 'import _inotify\n'), ((1412, 1427), 'tim... |
# Solution of;
# Project Euler Problem 568: Reciprocal games II
# https://projecteuler.net/problem=568
#
# Tom has built a random generator that is connected to a row of $n$ light
# bulbs. Whenever the random generator is activated each of the $n$ lights is
# turned on with the probability of $\frac 1 2$, independen... | [
"timed.caller"
] | [((2223, 2257), 'timed.caller', 'timed.caller', (['dummy', 'n', 'i', 'prob_id'], {}), '(dummy, n, i, prob_id)\n', (2235, 2257), False, 'import timed\n')] |
import logging
from forge_sdk import did as forge_did, utils as forge_utils
from forge_symposia.server import utils
from forge_symposia.server.app import forge
from forge_symposia.server.endpoints.lib import auth_component
def get_handler(**args):
tx = forge_utils.build_poke_tx(
chain_id=forge.confi... | [
"logging.error",
"forge_symposia.server.utils.mark_token_status",
"logging.debug",
"forge_symposia.server.endpoints.lib.auth_component.create",
"forge_symposia.server.app.forge.rpc.send_tx"
] | [((1314, 1403), 'forge_symposia.server.endpoints.lib.auth_component.create', 'auth_component.create', (['"""checkin"""'], {'get_handler': 'get_handler', 'post_handler': 'post_handler'}), "('checkin', get_handler=get_handler, post_handler=\n post_handler)\n", (1335, 1403), False, 'from forge_symposia.server.endpoints... |
# Copyright (c) 2022, Skolkovo Institute of Science and Technology (Skoltech)
#
# 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 req... | [
"evops.metrics.DefaultBenchmark.__recall",
"evops.metrics.IoUBenchmark.__iou",
"evops.utils.CheckInput.__default_benchmark_asserts",
"evops.metrics.DefaultBenchmark.__precision",
"evops.metrics.MeanBenchmark.__mean",
"evops.metrics.DiceBenchmark.__dice",
"evops.metrics.MultiValueBenchmark.__multi_value_... | [((1490, 1546), 'evops.utils.CheckInput.__iou_dice_mean_bechmark_asserts', '__iou_dice_mean_bechmark_asserts', (['pred_labels', 'gt_labels'], {}), '(pred_labels, gt_labels)\n', (1522, 1546), False, 'from evops.utils.CheckInput import __default_benchmark_asserts, __iou_dice_mean_bechmark_asserts\n'), ((1559, 1588), 'evo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
def locate_usb() -> list:
import win32file
from winapi__get_logical_drives import get_logical_drives
usb_list = list()
for drive_name in get_logical_drives():
drive_type = win32file.GetDriveType(drive_name)
if d... | [
"win32file.GetDriveType",
"winapi__get_logical_drives.get_logical_drives"
] | [((229, 249), 'winapi__get_logical_drives.get_logical_drives', 'get_logical_drives', ([], {}), '()\n', (247, 249), False, 'from winapi__get_logical_drives import get_logical_drives\n'), ((272, 306), 'win32file.GetDriveType', 'win32file.GetDriveType', (['drive_name'], {}), '(drive_name)\n', (294, 306), False, 'import wi... |
#!/usr/bin/env python
import argparse
import collections
import fileinput
import os
import sys
import time
# Require python 3
if sys.version_info[0] < 3:
print("This script requires Python version 3")
sys.exit(1)
# Structure to hold stat info
FileStat = collections.namedtuple( 'FileStat', [ 'inode',
... | [
"argparse.ArgumentParser",
"os.makedirs",
"fileinput.input",
"time.time",
"collections.namedtuple",
"sys.exit"
] | [((266, 380), 'collections.namedtuple', 'collections.namedtuple', (['"""FileStat"""', "['inode', 'na1', 'na2', 'uid', 'gid', 'perms', 'flags', 'sep', 'filename']"], {}), "('FileStat', ['inode', 'na1', 'na2', 'uid', 'gid',\n 'perms', 'flags', 'sep', 'filename'])\n", (288, 380), False, 'import collections\n'), ((212, ... |
"""
Builtin serializers.
"""
import json
from redset.interfaces import Serializer
class NamedtupleSerializer(Serializer):
"""
Serialize namedtuple classes.
"""
def __init__(self, NTClass):
"""
:param NTClass: the namedtuple class that you'd like to marshal to and
from.
... | [
"json.loads"
] | [((460, 486), 'json.loads', 'json.loads', (['str_from_redis'], {}), '(str_from_redis)\n', (470, 486), False, 'import json\n')] |
from collections import defaultdict
import networkx
from lib import puzzle
class Day06(puzzle.Puzzle):
year = '2019'
day = '6'
universal_center = 'COM'
def get_data(self):
return self.input_data.splitlines()
def part1(self):
data = list(self.get_data())
orbits = {}
... | [
"collections.defaultdict",
"networkx.Graph",
"networkx.shortest_path_length"
] | [((335, 352), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (346, 352), False, 'from collections import defaultdict\n'), ((517, 534), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (528, 534), False, 'from collections import defaultdict\n'), ((1124, 1140), 'networkx.Graph'... |
# Copyright (c) <NAME>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | [
"lib.utils.distributed.init_dist_gpu",
"random.randint",
"argparse.ArgumentParser",
"torch.utils.data.DataLoader",
"lib.utils.distributed.init_dist_node",
"torch.multiprocessing.spawn",
"torch.nn.parallel.DistributedDataParallel",
"ruamel.yaml.safe_load",
"lib.core.optimizer.get_optimizer",
"torch... | [((966, 1013), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Template"""'}), "(description='Template')\n", (989, 1013), False, 'import argparse\n'), ((5445, 5473), 'random.randint', 'random.randint', (['(49152)', '(65535)'], {}), '(49152, 65535)\n', (5459, 5473), False, 'import submitit... |