code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# Generated by Django 2.2.13 on 2020-11-11 14:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('studygroups', '0140_auto_20201110_0854'),
]
operations = [
migrations.AddField(
model_name='studygroup',
name='onli... | [
"django.db.models.BooleanField"
] | [((343, 377), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (362, 377), False, 'from django.db import migrations, models\n')] |
from django.db import models
class PaymentItem(models.Model):
display_name = models.CharField(max_length=100, blank=True)
api_url = models.URLField(max_length=200, verbose_name='API URL', blank=True)
description = models.TextField(blank=True)
enabled = models.BooleanField(default=True)
class Meta... | [
"reversion.register",
"django.db.models.TextField",
"django.db.models.BooleanField",
"django.db.models.URLField",
"django.db.models.CharField"
] | [((430, 461), 'reversion.register', 'reversion.register', (['PaymentItem'], {}), '(PaymentItem)\n', (448, 461), False, 'import reversion\n'), ((83, 127), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)', 'blank': '(True)'}), '(max_length=100, blank=True)\n', (99, 127), False, 'from django.d... |
from django.urls import path
from django.views.generic import TemplateView
urlpatterns = [
path('', TemplateView.as_view(template_name='index.html'), name='index'),
path('formulario/', TemplateView.as_view(template_name='index.html'), name='formulario'),
] | [
"django.views.generic.TemplateView.as_view"
] | [((107, 155), 'django.views.generic.TemplateView.as_view', 'TemplateView.as_view', ([], {'template_name': '"""index.html"""'}), "(template_name='index.html')\n", (127, 155), False, 'from django.views.generic import TemplateView\n'), ((196, 244), 'django.views.generic.TemplateView.as_view', 'TemplateView.as_view', ([], ... |
import numpy as np
from sknet.network_construction import KNNConstructor
class ModularityLabelPropagation():
"""
Semi-supervised method that propagates labels to instances not
classified using the Modularity Propagation method.
Attributes
----------
generated_y_ : {ndarray, pandas series}, s... | [
"numpy.array",
"sknet.network_construction.KNNConstructor",
"numpy.isnan"
] | [((2279, 2312), 'sknet.network_construction.KNNConstructor', 'KNNConstructor', (['(5)'], {'sep_comp': '(False)'}), '(5, sep_comp=False)\n', (2293, 2312), False, 'from sknet.network_construction import KNNConstructor\n'), ((6195, 6206), 'numpy.array', 'np.array', (['Q'], {}), '(Q)\n', (6203, 6206), True, 'import numpy a... |
import numpy as np
from mlp_train import *
# Predict classes from weights
def output(inputs, weights, biases):
"""Get the output of a trained MLP for a given set of inputs."""
return forward_propagation(inputs, weights, biases)[-1]
def predict_single(output):
"""Convert MLP outputs into class predictions,... | [
"numpy.mean",
"numpy.argmax"
] | [((377, 397), 'numpy.argmax', 'np.argmax', (['output', '(1)'], {}), '(output, 1)\n', (386, 397), True, 'import numpy as np\n'), ((556, 586), 'numpy.mean', 'np.mean', (['(predictions == labels)'], {}), '(predictions == labels)\n', (563, 586), True, 'import numpy as np\n')] |
#!/usr/bin/env python3
from collections import defaultdict, Counter, OrderedDict
import json
ALL_TEXTS = [
"Sloane2320",
"Sloane3566", "Trinity", "Boston",
"Gonville", "Takamiya",
]
def normalise(x):
return x.lower()
class Similarity:
def __init__(self):
self.p = {}
self.raw = []... | [
"collections.Counter",
"json.load",
"collections.defaultdict",
"json.dump"
] | [((2077, 2100), 'collections.defaultdict', 'defaultdict', (['Similarity'], {}), '(Similarity)\n', (2088, 2100), False, 'from collections import defaultdict, Counter, OrderedDict\n'), ((1010, 1027), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (1021, 1027), False, 'from collections import defaul... |
import random
import math
import torch
from PIL import Image, ImageOps, ImageEnhance, ImageDraw
from torchvision.transforms import functional as F
import transforms
from transforms import check_prob, PIL_INTER_MAP, RandomTransform
def rescale_float(level, max_val, param_max=10):
return float(level) ... | [
"transforms.check_prob",
"torchvision.transforms.functional.autocontrast",
"PIL.ImageEnhance.Contrast",
"torchvision.transforms.functional.rotate",
"random.choices",
"PIL.ImageDraw.Draw",
"PIL.ImageOps.posterize",
"torchvision.transforms.functional.invert",
"torchvision.transforms.functional.adjust_... | [((2816, 2938), 'torchvision.transforms.functional.affine', 'F.affine', (['img'], {'angle': '(0.0)', 'translate': '(translate_x, 0)', 'scale': '(1.0)', 'shear': '(0, 0)', 'resample': 'resample', 'fillcolor': 'fillcolor'}), '(img, angle=0.0, translate=(translate_x, 0), scale=1.0, shear=(0, 0\n ), resample=resample, f... |
# Copyright 2017 Battelle Energy Alliance, LLC
#
# 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 t... | [
"convert_utils.standardMain"
] | [((1365, 1410), 'convert_utils.standardMain', 'convert_utils.standardMain', (['sys.argv', 'convert'], {}), '(sys.argv, convert)\n', (1391, 1410), False, 'import convert_utils\n')] |
from sqlalchemy import create_engine,text
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import NullPool
from models import Protocols, LogDetail, DiseaseDiagnosis, ProtocolStatus, ProtocolAccrual
import logging
import os
logging.basicConfig(filename=os.environ.get('log_file', None), level=logging.DEBUG)
... | [
"sqlalchemy.orm.sessionmaker",
"sqlalchemy.create_engine",
"os.environ.get",
"models.LogDetail",
"logging.info"
] | [((265, 297), 'os.environ.get', 'os.environ.get', (['"""log_file"""', 'None'], {}), "('log_file', None)\n", (279, 297), False, 'import os\n'), ((715, 756), 'sqlalchemy.create_engine', 'create_engine', (['engine'], {'poolclass': 'NullPool'}), '(engine, poolclass=NullPool)\n', (728, 756), False, 'from sqlalchemy import c... |
from unittest import TestCase
from dltb.tool import Tool
from dltb.tool.detector import Detections
from dltb.base.image import Image
class TestDetector(TestCase):
def setUp(self):
self.detector = Tool['haar']
self.detector.prepare()
# self.image = imread('examples/reservoir-dogs.jpg')
... | [
"dltb.base.image.Image.as_data"
] | [((339, 383), 'dltb.base.image.Image.as_data', 'Image.as_data', (['"""examples/reservoir-dogs.jpg"""'], {}), "('examples/reservoir-dogs.jpg')\n", (352, 383), False, 'from dltb.base.image import Image\n')] |
from collections import Counter
class Solution:
def canBeEqual(self, target, arr):
return Counter(target) == Counter(arr)
| [
"collections.Counter"
] | [((104, 119), 'collections.Counter', 'Counter', (['target'], {}), '(target)\n', (111, 119), False, 'from collections import Counter\n'), ((123, 135), 'collections.Counter', 'Counter', (['arr'], {}), '(arr)\n', (130, 135), False, 'from collections import Counter\n')] |
# Copyright (c) 2018-2022, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of condit... | [
"json.JSONEncoder.default",
"numpy.asarray",
"os.path.dirname",
"json.load",
"numpy.save",
"json.dump",
"numpy.load"
] | [((2719, 2754), 'json.JSONEncoder.default', 'json.JSONEncoder.default', (['self', 'obj'], {}), '(self, obj)\n', (2743, 2754), False, 'import json\n'), ((2857, 2907), 'numpy.asarray', 'np.asarray', (["dct['__ndarray__']"], {'dtype': "dct['dtype']"}), "(dct['__ndarray__'], dtype=dct['dtype'])\n", (2867, 2907), True, 'imp... |
import math
def solution(w,h):
answer = (w*h) - (w + h - math.gcd(w, h))
return answer | [
"math.gcd"
] | [((62, 76), 'math.gcd', 'math.gcd', (['w', 'h'], {}), '(w, h)\n', (70, 76), False, 'import math\n')] |
""" Creates a vocabulary from a tsv file.
"""
import codecs
from torchMoji.torchmoji.create_vocab import VocabBuilder
from torchMoji.torchmoji.word_generator import TweetWordGenerator
with codecs.open('../../twitterdata/tweets.2016-09-01', 'rU', 'utf-8') as stream:
wg = TweetWordGenerator(stream)
vb = VocabBu... | [
"torchMoji.torchmoji.create_vocab.VocabBuilder",
"codecs.open",
"torchMoji.torchmoji.word_generator.TweetWordGenerator"
] | [((191, 256), 'codecs.open', 'codecs.open', (['"""../../twitterdata/tweets.2016-09-01"""', '"""rU"""', '"""utf-8"""'], {}), "('../../twitterdata/tweets.2016-09-01', 'rU', 'utf-8')\n", (202, 256), False, 'import codecs\n'), ((277, 303), 'torchMoji.torchmoji.word_generator.TweetWordGenerator', 'TweetWordGenerator', (['st... |
from decimal import Decimal as D
from unit_converter.units import UnitPrefix, Unit
# ----------
# Prefix SI
# ----------
PREFIXES = {
'y': UnitPrefix(symbol='y', name='yocto', factor=D('1E-24')),
'z': UnitPrefix(symbol='z', name='zepto', factor=D('1E-21')),
'a': UnitPrefix(symbol='a', name='atto', factor=... | [
"unit_converter.units.Unit",
"decimal.Decimal"
] | [((1591, 1614), 'unit_converter.units.Unit', 'Unit', (['"""m"""', '"""meter"""'], {'L': '(1)'}), "('m', 'meter', L=1)\n", (1595, 1614), False, 'from unit_converter.units import UnitPrefix, Unit\n'), ((1674, 1698), 'unit_converter.units.Unit', 'Unit', (['"""s"""', '"""second"""'], {'T': '(1)'}), "('s', 'second', T=1)\n"... |
import requests
import constants
class Moodle:
def __init__(self):
self.interactions = []
@staticmethod
def submit_request(wsfunction, payload, verb='POST'):
# url = '{}?wstoken={}&moodlewsrestfromat={}&wsfunction={}'.format(constants.MOODLE_QUERY_URL,
# ... | [
"requests.post"
] | [((635, 753), 'requests.post', 'requests.post', ([], {'url': 'constants.MOODLE_QUERY_URL', 'data': 'payload', 'headers': 'constants.MOODLE_HEADERS', 'params': 'querystring'}), '(url=constants.MOODLE_QUERY_URL, data=payload, headers=\n constants.MOODLE_HEADERS, params=querystring)\n', (648, 753), False, 'import reque... |
from django.urls import path
from AuthorizationManagement import views
from django.urls.conf import re_path
from .admin import resource_manager
from .admin import user_manager
from .views import *
urlpatterns = [
path('', views.homeView, name='home'),
re_path(r'^resource-manager/', resource_manager.urls),
... | [
"AuthorizationManagement.views.ChosenRequestsView.as_view",
"AuthorizationManagement.views.ResourcesOverview.as_view",
"AuthorizationManagement.views.ProfileView.as_view",
"AuthorizationManagement.views.PermissionEditingView.as_view",
"AuthorizationManagement.views.ResourcesOverviewSearch.as_view",
"Autho... | [((219, 256), 'django.urls.path', 'path', (['""""""', 'views.homeView'], {'name': '"""home"""'}), "('', views.homeView, name='home')\n", (223, 256), False, 'from django.urls import path\n'), ((262, 314), 'django.urls.conf.re_path', 're_path', (['"""^resource-manager/"""', 'resource_manager.urls'], {}), "('^resource-man... |
# Dropout Module
import torch
from torch import nn as nn
from src.modules.base_generator import GeneratorAbstract
class Dropout(nn.Module):
"""Dropout module."""
def __init__(self, prob: int =0.5):
"""
Args:
prob: dropout probability
"""
super().__init__()
... | [
"torch.nn.Dropout"
] | [((336, 352), 'torch.nn.Dropout', 'nn.Dropout', (['prob'], {}), '(prob)\n', (346, 352), True, 'from torch import nn as nn\n')] |
import json
from django import template
from django.utils.html import format_html
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter(is_safe=True)
def json_script_with_non_ascii(value, element_id):
from django.core.serializers.json import DjangoJSONEncoder
_json_sc... | [
"django.utils.safestring.mark_safe",
"json.dumps",
"django.template.Library"
] | [((142, 160), 'django.template.Library', 'template.Library', ([], {}), '()\n', (158, 160), False, 'from django import template\n'), ((669, 690), 'django.utils.safestring.mark_safe', 'mark_safe', (['value_json'], {}), '(value_json)\n', (678, 690), False, 'from django.utils.safestring import mark_safe\n'), ((447, 507), '... |
import ujson
from dataclasses import dataclass, asdict
@dataclass
class BaseModelMixin:
@property
def as_json_string(self):
return ujson.dumps(asdict(self))
@classmethod
def from_json(cls, jstr):
if not jstr:
return None
d = ujson.loads(jstr)
return cls(**d... | [
"dataclasses.asdict",
"ujson.loads"
] | [((280, 297), 'ujson.loads', 'ujson.loads', (['jstr'], {}), '(jstr)\n', (291, 297), False, 'import ujson\n'), ((161, 173), 'dataclasses.asdict', 'asdict', (['self'], {}), '(self)\n', (167, 173), False, 'from dataclasses import dataclass, asdict\n')] |
import numpy as np
from pretreat import read
from utils.dispatcher import dispatch
from utils.debugger import Logger
# set logging test update lcx added by wenake
logger = Logger(__name__)
def getINF():
"""
function:
return the INF of this tool.
parameters:
None, no ... | [
"utils.debugger.Logger",
"pretreat.read",
"utils.dispatcher.dispatch"
] | [((181, 197), 'utils.debugger.Logger', 'Logger', (['__name__'], {}), '(__name__)\n', (187, 197), False, 'from utils.debugger import Logger\n'), ((1662, 1801), 'utils.dispatcher.dispatch', 'dispatch', ([], {'graph': 'graph', 'useCUDA': 'useCUDA', 'useMultiPro': 'useMultiPro', 'pathRecordBool': 'pathRecordBool', 'srclist... |
from builtins import object
from rest_framework import serializers
from bluebottle.funding.base_serializers import PaymentSerializer, BaseBankAccountSerializer
from bluebottle.funding_vitepay.models import VitepayPayment, VitepayBankAccount
from bluebottle.funding_vitepay.utils import get_payment_url
class VitepayPay... | [
"bluebottle.funding_vitepay.utils.get_payment_url",
"rest_framework.serializers.CharField"
] | [((373, 410), 'rest_framework.serializers.CharField', 'serializers.CharField', ([], {'read_only': '(True)'}), '(read_only=True)\n', (394, 410), False, 'from rest_framework import serializers\n'), ((820, 844), 'bluebottle.funding_vitepay.utils.get_payment_url', 'get_payment_url', (['payment'], {}), '(payment)\n', (835, ... |
import os
import shutil
from .base import GnuRecipe
class FastCppCsvParserRecipe(GnuRecipe):
def __init__(self, *args, **kwargs):
super(FastCppCsvParserRecipe, self).__init__(*args, **kwargs)
self.sha256 = '5e2beea28f8e85f8e26a37e5a34ff918' \
'0f817f75049d5bf395ab6e0759c7f8ca... | [
"os.path.join",
"os.makedirs",
"shutil.copy2"
] | [((702, 762), 'os.path.join', 'os.path.join', (['self.prefix_dir', '"""include"""', '"""fastcppcsvparser"""'], {}), "(self.prefix_dir, 'include', 'fastcppcsvparser')\n", (714, 762), False, 'import os\n'), ((771, 791), 'os.makedirs', 'os.makedirs', (['destdir'], {}), '(destdir)\n', (782, 791), False, 'import os\n'), ((8... |
from secret.extensions import db
class Entries(db.Model):
"""Database model for entry links."""
__tablename__ = "links"
id = db.Column(db.Integer, primary_key=True)
encrypted_text = db.Column(db.LargeBinary)
date_created = db.Column(db.DateTime)
date_expires = db.Column(db.DateTime, nullable... | [
"secret.extensions.db.Column",
"secret.extensions.db.String"
] | [((141, 180), 'secret.extensions.db.Column', 'db.Column', (['db.Integer'], {'primary_key': '(True)'}), '(db.Integer, primary_key=True)\n', (150, 180), False, 'from secret.extensions import db\n'), ((202, 227), 'secret.extensions.db.Column', 'db.Column', (['db.LargeBinary'], {}), '(db.LargeBinary)\n', (211, 227), False,... |
from datetime import timedelta
from unittest import mock
import pytest
from django.utils import timezone
from rest_framework import status
from rest_framework.test import APIClient
from apps.accounts.factories import UserFactory
from apps.costcontrol.factories import (
BalanceRecordFactory,
ProceedCategoryFac... | [
"apps.accounts.factories.UserFactory.create_batch",
"apps.costcontrol.factories.ProceedCategoryFactory",
"apps.costcontrol.factories.ProceedRecordFactory.create_batch",
"apps.costcontrol.factories.ProceedCategoryFactory.create_batch",
"apps.costcontrol.factories.SpendingRecordFactory",
"apps.costcontrol.f... | [((413, 473), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""url"""', "['history', 'filled-months']"], {}), "('url', ['history', 'filled-months'])\n", (436, 473), False, 'import pytest\n'), ((657, 717), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""url"""', "['history', 'filled-months']"], {}... |
# coding=utf-8
import json
import re
from typing import List
import pandas as pd
from collections import defaultdict
from dataclasses import dataclass
import numpy as np
from backend.integrations import database
def normalize_test_name(tests: np.ndarray):
"""
Normalize test names to match database.
- ... | [
"backend.integrations.database.get_test_execution_times",
"numpy.where",
"re.match",
"collections.defaultdict",
"json.load",
"backend.integrations.database.get_test_name_fails",
"numpy.all",
"re.search"
] | [((870, 902), 're.match', 're.match', (['"""(.*\\\\..+)\\\\+.+"""', 'test'], {}), "('(.*\\\\..+)\\\\+.+', test)\n", (878, 902), False, 'import re\n'), ((1347, 1363), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (1358, 1363), False, 'from collections import defaultdict\n'), ((2666, 2723), 'backend... |
"""
This file contains all methods needed to perform the quality check procedure after t1-linear preprocessing.
"""
from os import makedirs
from os.path import dirname, join, exists, splitext, abspath
from pathlib import Path
import pandas as pd
import torch
from torch.utils.data import DataLoader
from .utils import ... | [
"os.path.exists",
"os.makedirs",
"torch.nn.Softmax",
"pathlib.Path.home",
"torch.load",
"os.path.join",
"clinica.utils.inputs.RemoteFileStructure",
"os.path.splitext",
"clinica.utils.inputs.fetch_file",
"torch.utils.data.DataLoader",
"pandas.DataFrame",
"os.path.abspath"
] | [((848, 891), 'os.path.join', 'join', (['home', '""".cache"""', '"""clinicadl"""', '"""models"""'], {}), "(home, '.cache', 'clinicadl', 'models')\n", (852, 891), False, 'from os.path import dirname, join, exists, splitext, abspath\n'), ((981, 1127), 'clinica.utils.inputs.RemoteFileStructure', 'RemoteFileStructure', ([]... |
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
def get_mnist_dataset():
train_dataset = torchvision.datasets.MNIST(root='../data/',
train=True,
transform=transforms.ToTe... | [
"torchvision.datasets.CIFAR10",
"torchvision.transforms.ToTensor",
"torch.utils.data.DataLoader"
] | [((761, 852), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', ([], {'dataset': 'train_dataset', 'batch_size': 'batch_size', 'shuffle': '(True)'}), '(dataset=train_dataset, batch_size=batch_size,\n shuffle=True)\n', (788, 852), False, 'import torch\n'), ((962, 1053), 'torch.utils.data.DataLoader', 'torc... |
"""
This module provides auth token authorization for djapi.
It is closely based on rest_framework.authtoken module coming under following license.
Copyright (c) 2011-2017, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the foll... | [
"django.core.exceptions.PermissionDenied",
"funcy.re_find",
"django.utils.translation.ugettext_lazy"
] | [((1738, 1753), 'django.utils.translation.ugettext_lazy', '_', (['"""Auth Token"""'], {}), "('Auth Token')\n", (1739, 1753), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1960, 2015), 'funcy.re_find', 're_find', (['"""^\\\\s*token\\\\s+([a-z0-9]+)\\\\s*$"""', 'header', 're.I'], {}), "('^\\\\s*to... |
# Copyright 2018 The TensorFlow Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | [
"tensorflow.random.uniform",
"tensorflow.shape",
"tensorflow.math.add_n",
"tensorflow.stop_gradient",
"tensorflow.keras.layers.ZeroPadding2D",
"tensorflow.keras.models.Model",
"tensorflow.keras.layers.Cropping2D"
] | [((4039, 4066), 'tensorflow.math.add_n', 'tf.math.add_n', (['rand_forward'], {}), '(rand_forward)\n', (4052, 4066), True, 'import tensorflow as tf\n'), ((4086, 4114), 'tensorflow.math.add_n', 'tf.math.add_n', (['rand_backward'], {}), '(rand_backward)\n', (4099, 4114), True, 'import tensorflow as tf\n'), ((6481, 6523), ... |
# Generated by Django 3.1 on 2020-10-06 12:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backend', '0010_auto_20201003_1802'),
]
operations = [
migrations.AddField(
model_name='booking1',
name='phone',
... | [
"django.db.models.CharField"
] | [((333, 376), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(11)'}), '(blank=True, max_length=11)\n', (349, 376), False, 'from django.db import migrations, models\n'), ((497, 540), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(11)'... |
#!/usr/bin/env python3
# Copyright (c) 2020 <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... | [
"logging.basicConfig",
"os.path.exists",
"supernotelib.converter.ImageConverter",
"os.close",
"threading.Lock",
"os.statvfs",
"os.open",
"os.access",
"fuse.FuseOSError",
"os.lseek",
"os.scandir",
"os.path.realpath",
"io.BytesIO",
"supernotelib.load_notebook",
"collections.defaultdict",
... | [((954, 988), 'os.path.exists', 'os.path.exists', (["(path[:-3] + 'note')"], {}), "(path[:-3] + 'note')\n", (968, 988), False, 'import os\n'), ((4618, 4657), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (4637, 4657), False, 'import logging\n'), ((900, 920), 'o... |
import pygame
text = input('Nome da musica: ')
pygame.init()
pygame.mixer.music.load(text)
pygame.mixer.music.play()
print('S para parar.')
text2 = input('-> ')
if text2 == 'S':
pygame.mixer.stop()
else:
pygame.event.wait()
| [
"pygame.init",
"pygame.mixer.stop",
"pygame.event.wait",
"pygame.mixer.music.load",
"pygame.mixer.music.play"
] | [((49, 62), 'pygame.init', 'pygame.init', ([], {}), '()\n', (60, 62), False, 'import pygame\n'), ((63, 92), 'pygame.mixer.music.load', 'pygame.mixer.music.load', (['text'], {}), '(text)\n', (86, 92), False, 'import pygame\n'), ((93, 118), 'pygame.mixer.music.play', 'pygame.mixer.music.play', ([], {}), '()\n', (116, 118... |
#!/usr/bin/env python3
import argparse
import subprocess
import os, os.path, shutil, sys, tempfile
SOLVERS = {
"lingeling": "-q -t {proof} {cnf}",
"kissat": "-q {cnf} {proof}",
"cadical": "-q {cnf} {proof}",
"cryptominisat5": "--verb 0 {cnf} {proof}",
"satch": "-q {cnf} {proof}",
"picosat": "-... | [
"tempfile.TemporaryDirectory",
"argparse.ArgumentParser",
"shutil.which",
"os.path.join",
"os.path.dirname",
"sys.stdin.buffer.read",
"os.path.basename"
] | [((456, 481), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (479, 481), False, 'import argparse\n'), ((417, 442), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (432, 442), False, 'import os, os.path, shutil, sys, tempfile\n'), ((579, 608), 'tempfile.TemporaryDirecto... |
import time
from googlesearch import search
import urllib.request
#one of my more major projects that I've worked on
#url = "https://paintwithbob.com"
#testing url opener with paintwithbob
#f = urllib.request.urlopen(url)
#test = f.read()
#if ("Paint".encode("utf-8") in test):
# print (test)
searchterm = input("S... | [
"googlesearch.search",
"time.sleep"
] | [((575, 602), 'googlesearch.search', 'search', (['searchterm'], {'stop': '(20)'}), '(searchterm, stop=20)\n', (581, 602), False, 'from googlesearch import search\n'), ((948, 961), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (958, 961), False, 'import time\n')] |
from lst28 import *
import pygraphviz as pgv
G = pgv.AGraph(strict=False, directed=False)
G.graph_attr['rankdir'] = 'LR'
G.node_attr['shape'] = 'circle'
values = [UA[ui][ai] for ui in UA for ai in UA[ui]]
x_min = min(values)
x_max = max(values)
y_min = 1.0
y_max = 5.0
for ui in UA:
for ai in UA[ui]:
x... | [
"pygraphviz.AGraph"
] | [((51, 91), 'pygraphviz.AGraph', 'pgv.AGraph', ([], {'strict': '(False)', 'directed': '(False)'}), '(strict=False, directed=False)\n', (61, 91), True, 'import pygraphviz as pgv\n')] |
from flask import Blueprint
from pfms.swagger.pfms_swagger_decorator import pfms_create, pfms_details, pfms_pagination_sort_search_list, pfms_restore, pfms_delete
from pfrf_example.dto.person_dto import PersonCreateDto, PersonDetailsDto, PersonUpdateDto
from pfrf_example.service.person_service import PersonService
pe... | [
"pfms.swagger.pfms_swagger_decorator.pfms_restore",
"pfms.swagger.pfms_swagger_decorator.pfms_delete",
"pfms.swagger.pfms_swagger_decorator.pfms_pagination_sort_search_list",
"pfms.swagger.pfms_swagger_decorator.pfms_details",
"pfms.swagger.pfms_swagger_decorator.pfms_create",
"pfrf_example.service.person... | [((338, 407), 'flask.Blueprint', 'Blueprint', (['"""person_controller"""', '__name__'], {'url_prefix': '"""/api/v1/person"""'}), "('person_controller', __name__, url_prefix='/api/v1/person')\n", (347, 407), False, 'from flask import Blueprint\n'), ((425, 440), 'pfrf_example.service.person_service.PersonService', 'Perso... |
import numpy as np
import pygame as pg
class Tiles(object):
def __init__(self, size):
"""
:param size: How many tiles wide and high
"""
self.size = size
self.screen_rect = pg.display.get_surface().get_rect()
self.screen_width = self.screen_rect.width
self.s... | [
"pygame.display.get_surface",
"pygame.draw.rect",
"numpy.empty",
"pygame.Color",
"pygame.Rect"
] | [((639, 662), 'pygame.Color', 'pg.Color', (['"""GreenYellow"""'], {}), "('GreenYellow')\n", (647, 662), True, 'import pygame as pg\n'), ((689, 710), 'pygame.Color', 'pg.Color', (['"""LawnGreen"""'], {}), "('LawnGreen')\n", (697, 710), True, 'import pygame as pg\n'), ((1015, 1056), 'numpy.empty', 'np.empty', (['(self.si... |
from flask import current_app
from wk_client import logic
from wk_client.constants import FEE_TYPE, INTEREST_TYPES, REPAYMENT_TYPES, DECLINED_STATE_NAME
from wk_client.constants import MIN_LOAN_AMOUNT, MAX_LOAN_AMOUNT
from wk_client.logic import approve_user, decline_user
from wk_client.request_utils import time_now
f... | [
"wk_client.logic.evaluate_decision",
"flask.current_app.logger.error",
"wk_client.utils.get_date",
"wk_client.request_utils.time_now",
"wk_client.logic.check_requirements",
"wk_client.logic.get_requirements"
] | [((1195, 1223), 'wk_client.logic.get_requirements', 'logic.get_requirements', (['data'], {}), '(data)\n', (1217, 1223), False, 'from wk_client import logic\n'), ((1235, 1279), 'wk_client.logic.check_requirements', 'logic.check_requirements', (['data', 'requirements'], {}), '(data, requirements)\n', (1259, 1279), False,... |
import pandas as pd
import numpy as np
import netCDF4 as nc
from .subroutines import *
class SpecificDoses(pd.DataFrame):
"""A class for specific dose estimates akin to dosimetry measurements
High resolution data allows for personal and ambient dose estimation without the need for
direct measurement. Thi... | [
"pandas.DataFrame.from_records",
"numpy.mean",
"numpy.median",
"numpy.amin",
"pandas.read_csv",
"numpy.average",
"pandas.DatetimeIndex",
"numpy.sum",
"numpy.zeros",
"numpy.std",
"numpy.amax",
"numpy.var"
] | [((7021, 7033), 'numpy.zeros', 'np.zeros', (['(24)'], {}), '(24)\n', (7029, 7033), True, 'import numpy as np\n'), ((10556, 11298), 'pandas.DataFrame.from_records', 'pd.DataFrame.from_records', ([], {'columns': "['Seated', 'Kneeling', 'Standing erect arms down', 'Standing erect arms up',\n 'Standing bowing']", 'index... |
import falcon
import json
from data.operators.PersonOperator import PersonOperator
from utils.logger import Log
from utils.form.fields import Fields
fields = Fields()
class PersonSearchHandler(object):
"""
It handles the request to no specific persons
Args:
object (object): No info
"""
de... | [
"json.dumps",
"data.operators.PersonOperator.PersonOperator.searchBy",
"utils.logger.Log",
"utils.form.fields.Fields"
] | [((159, 167), 'utils.form.fields.Fields', 'Fields', ([], {}), '()\n', (165, 167), False, 'from utils.form.fields import Fields\n'), ((820, 857), 'utils.logger.Log', 'Log', (['f"""GET Request Received"""'], {'req': 'req'}), "(f'GET Request Received', req=req)\n", (823, 857), False, 'from utils.logger import Log\n'), ((1... |
from django.db import models
from common.models import Lang
FEMALE = 1
MALE = 2
GENDER_CHOICES = (
(FEMALE, "Female"),
(MALE, "Male")
)
class Person(models.Model):
"""
`Person` represents a person that work in the cinema world could be
an actor, producer, director ...
Attributes:
"""
... | [
"django.db.models.DateField",
"django.db.models.TextField",
"django.db.models.IntegerField",
"django.db.models.ForeignKey",
"django.db.models.ManyToManyField",
"django.db.models.URLField",
"django.db.models.CharField"
] | [((329, 361), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (345, 361), False, 'from django.db import models\n'), ((377, 416), 'django.db.models.DateField', 'models.DateField', ([], {'null': '(True)', 'blank': '(True)'}), '(null=True, blank=True)\n', (393, 416), ... |
import json
import logging
import boto3
import cfnresponse
import time
ec2_client = boto3.client('ec2')
logs_client = boto3.client('logs')
def boto_throttle_backoff(boto_method, max_retries=10, backoff_multiplier=2, **kwargs):
retry = 0
results = None
while not results:
try:
results ... | [
"boto3.client",
"json.dumps",
"time.sleep",
"cfnresponse.send",
"logging.error"
] | [((86, 105), 'boto3.client', 'boto3.client', (['"""ec2"""'], {}), "('ec2')\n", (98, 105), False, 'import boto3\n'), ((120, 140), 'boto3.client', 'boto3.client', (['"""logs"""'], {}), "('logs')\n", (132, 140), False, 'import boto3\n'), ((2490, 2566), 'cfnresponse.send', 'cfnresponse.send', (['event', 'context', 'status'... |
import numpy as np
from sklearn.preprocessing import MinMaxScaler as mms
import ONN_Simulation_Class as ONN_Cls
from plot_scatter_matrix import plot_scatter_matrix
import ONN_Setups
import training_onn as train
import test_trained_onns as test
import create_datasets
from sklearn import preprocessing
import sys
sys.path... | [
"numpy.linspace",
"sys.path.append",
"numpy.argmax",
"ONN_Simulation_Class.ONN_Simulation"
] | [((312, 334), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (327, 334), False, 'import sys\n'), ((367, 391), 'ONN_Simulation_Class.ONN_Simulation', 'ONN_Cls.ONN_Simulation', ([], {}), '()\n', (389, 391), True, 'import ONN_Simulation_Class as ONN_Cls\n'), ((1135, 1155), 'numpy.linspace', 'np.li... |
# -*- coding: utf-8 -*-
"""Example for sending batch information to InfluxDB via UDP."""
"""
INFO: In order to use UDP, one should enable the UDP service from the
`influxdb.conf` under section
[[udp]]
enabled = true
bind-address = ":8089" # port number for sending data via UDP
database = "u... | [
"influxdb.InfluxDBClient",
"argparse.ArgumentParser"
] | [((1304, 1348), 'influxdb.InfluxDBClient', 'InfluxDBClient', ([], {'use_udp': '(True)', 'udp_port': 'uport'}), '(use_udp=True, udp_port=uport)\n', (1318, 1348), False, 'from influxdb import InfluxDBClient\n'), ((1493, 1591), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""example code to ... |
'''
util.py
the utility functions of the project
'''
import os
import sys
from warnings import warn
from datetime import datetime
from pathlib import Path
from importlib import import_module
import torch
import torch.nn as nn
import frontend
import util.audio as audio
from config import config
import numpy as np
impor... | [
"util.wavenet_util.is_mulaw",
"matplotlib.pyplot.ylabel",
"util.wavenet_util.is_scalar_input",
"util.audio.inv_mulaw",
"torch.from_numpy",
"torch.cuda.is_available",
"util.wavenet_util.is_mulaw_quantize",
"librosa.display.waveplot",
"torch.arange",
"numpy.flip",
"model.Decoder",
"matplotlib.py... | [((333, 354), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (347, 354), False, 'import matplotlib\n'), ((550, 575), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (573, 575), False, 'import torch\n'), ((1819, 2165), 'model.Encoder', 'Encoder', (['n_vocab', 'embed_dim'], ... |
from magictranslator import translator
if __name__ == '__main__':
t = translator.FromJSONConfigFile('config.json')
res = t.Translate('ありがとうございます')
print(res)
# Yandex test
res = t.Translate('Мне подойдёт любой день')
print(res)
# AWS
res = t.Translate('hola amigo buenas noches'... | [
"magictranslator.translator.FromJSONConfigFile"
] | [((77, 121), 'magictranslator.translator.FromJSONConfigFile', 'translator.FromJSONConfigFile', (['"""config.json"""'], {}), "('config.json')\n", (106, 121), False, 'from magictranslator import translator\n')] |
import os
import time
import gc
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.onnx as torch_onnx
from torchvision import datasets, transforms
from torch.autograd import Variable
import tensorrt as trt
TRT_LOGGER = trt.Logger(trt.Logger.WARNING)
from src ... | [
"torch.load",
"os.path.join",
"tensorrt.Logger",
"torch.randn",
"torch.onnx.export"
] | [((279, 309), 'tensorrt.Logger', 'trt.Logger', (['trt.Logger.WARNING'], {}), '(trt.Logger.WARNING)\n', (289, 309), True, 'import tensorrt as trt\n'), ((421, 443), 'torch.load', 'torch.load', (['model_path'], {}), '(model_path)\n', (431, 443), False, 'import torch\n'), ((853, 888), 'os.path.join', 'os.path.join', (['mod... |
import os
fileList = os.listdir('.') #replace the . with your article directory
foreignList=['(4E)',
'(AA)',
'(AAP)',
'(ABR)',
'(AFNEWS)',
'(AFP)',
'(AFPS)',
'(AGERPRES)',
'(AGI)',
'(AHN)',
'(AIP)',
'(AMNA)',
'(ANA)',
'(ANI)',
'(ANN)',
'(ANNCOL)',
'(ANP)',
'(ANSA)',
'(ANTARA)',
'(AP)',
'(APA)',
'(APEM)',
'(APP)',
'(A... | [
"os.listdir",
"os.remove"
] | [((22, 37), 'os.listdir', 'os.listdir', (['"""."""'], {}), "('.')\n", (32, 37), False, 'import os\n'), ((8086, 8101), 'os.listdir', 'os.listdir', (['"""."""'], {}), "('.')\n", (8096, 8101), False, 'import os\n'), ((7931, 7956), 'os.remove', 'os.remove', (["('.' + filename)"], {}), "('.' + filename)\n", (7940, 7956), Fa... |
# Standard Library
import logging
# Third-Party
import pydf
from rest_framework_json_api.filters import OrderingFilter
from rest_framework_json_api.django_filters import DjangoFilterBackend
from django_fsm import TransitionNotAllowed
from django_fsm_log.models import StateLog
from dry_rest_permissions.generics import... | [
"logging.getLogger",
"rest_framework.response.Response",
"rest_framework.decorators.action"
] | [((1657, 1684), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1674, 1684), False, 'import logging\n'), ((2469, 2506), 'rest_framework.decorators.action', 'action', ([], {'methods': "['post']", 'detail': '(True)'}), "(methods=['post'], detail=True)\n", (2475, 2506), False, 'from rest_fra... |
from datetime import datetime
from coinbase.wallet.client import Client
from colorama import Fore, Back, Style
class Crypto:
def __init__(self, environment):
self.api_key = environment["api_key"]
self.api_secret = environment["api_secret"]
self.currency = environment["currency"]
se... | [
"datetime.datetime.now",
"coinbase.wallet.client.Client"
] | [((406, 443), 'coinbase.wallet.client.Client', 'Client', (['self.api_key', 'self.api_secret'], {}), '(self.api_key, self.api_secret)\n', (412, 443), False, 'from coinbase.wallet.client import Client\n'), ((669, 683), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (681, 683), False, 'from datetime import dat... |
"""empty message
Revision ID: 779014da<PASSWORD>d
Revises: <PASSWORD>
Create Date: 2016-02-04 12:41:50.300585
"""
# revision identifiers, used by Alembic.
revision = '7<PASSWORD>'
down_revision = '<PASSWORD>'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic ... | [
"sqlalchemy.String",
"alembic.op.drop_column"
] | [((545, 576), 'alembic.op.drop_column', 'op.drop_column', (['"""posts"""', '"""slug"""'], {}), "('posts', 'slug')\n", (559, 576), False, 'from alembic import op\n'), ((386, 407), 'sqlalchemy.String', 'sa.String', ([], {'length': '(120)'}), '(length=120)\n', (395, 407), True, 'import sqlalchemy as sa\n')] |
#!/usr/bin/env python
"""
Global export symbols (Radare2)
"""
import os
import json
import subprocess
import logging
import lib_uris
import lib_common
from lib_properties import pc
def Main():
cgiEnv = lib_common.ScriptEnvironment()
file_exe_or_dll = cgiEnv.GetId()
grph = cgiEnv.GetGraph()
node_... | [
"lib_uris.gUriGen.FileUri",
"json.loads",
"logging.debug",
"lib_common.ScriptEnvironment",
"subprocess.Popen",
"lib_common.MakeProp",
"lib_uris.gUriGen.SymbolUri"
] | [((211, 241), 'lib_common.ScriptEnvironment', 'lib_common.ScriptEnvironment', ([], {}), '()\n', (239, 241), False, 'import lib_common\n'), ((333, 374), 'lib_uris.gUriGen.FileUri', 'lib_uris.gUriGen.FileUri', (['file_exe_or_dll'], {}), '(file_exe_or_dll)\n', (357, 374), False, 'import lib_uris\n'), ((501, 600), 'subproc... |
"""Fuzzy K-means clustering"""
# ==============================================================================
# Author: <NAME> <ammarsherif90 [at] gmail [dot] com >
# License: MIT
# ==============================================================================
# =====================================================... | [
"numpy.sum",
"numpy.zeros",
"sklearn.utils.check_random_state"
] | [((2284, 2316), 'numpy.zeros', 'np.zeros', (['(n_points, n_clusters)'], {}), '((n_points, n_clusters))\n', (2292, 2316), True, 'import numpy as np\n'), ((3285, 3316), 'numpy.sum', 'np.sum', (['(fmm ** self.__m)'], {'axis': '(0)'}), '(fmm ** self.__m, axis=0)\n', (3291, 3316), True, 'import numpy as np\n'), ((3621, 3655... |
import requests
def whois_more(IP):
result = requests.get('http://api.hackertarget.com/whois/?q=' + IP).text
print('\n'+ result + '\n')
| [
"requests.get"
] | [((54, 112), 'requests.get', 'requests.get', (["('http://api.hackertarget.com/whois/?q=' + IP)"], {}), "('http://api.hackertarget.com/whois/?q=' + IP)\n", (66, 112), False, 'import requests\n')] |
import numpy as np
import matplotlib.pyplot as plt
def penalty(t, k):
return np.log(1+np.exp(k*t))/k
# return k * t / (k - t + 1)
temp_lb = 310
temp = np.linspace(temp_lb-1, temp_lb+2, 1000)
k = 10
diff = temp_lb-temp
p = penalty(diff, k)
plt.close('all')
plt.figure()
plt.plot(diff, 1445*p)
plt.plot(diff,... | [
"matplotlib.pyplot.plot",
"matplotlib.pyplot.close",
"numpy.exp",
"numpy.linspace",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.show"
] | [((163, 206), 'numpy.linspace', 'np.linspace', (['(temp_lb - 1)', '(temp_lb + 2)', '(1000)'], {}), '(temp_lb - 1, temp_lb + 2, 1000)\n', (174, 206), True, 'import numpy as np\n'), ((253, 269), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (262, 269), True, 'import matplotlib.pyplot as plt\n'... |
import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from web.lib.base import BaseController, render
log = logging.getLogger(__name__)
class FormtestController(BaseController):
def index(self):
# Return a rendered templ... | [
"logging.getLogger",
"web.lib.base.render"
] | [((194, 221), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (211, 221), False, 'import logging\n'), ((460, 480), 'web.lib.base.render', 'render', (['"""/form.mako"""'], {}), "('/form.mako')\n", (466, 480), False, 'from web.lib.base import BaseController, render\n')] |
import logging
import re
class Grade:
def __init__(self, grade):
self.grade = grade
def to_dict(self):
return { "grade": self.grade, "sort_index": self.index() }
def index(self):
pass
class YDS(Grade):
static_indexes = ["3rd", "4th", "Easy 5th"]
single_digit_mplier = 3
... | [
"re.match",
"logging.error"
] | [((3425, 3455), 're.match', 're.match', (['"""\\\\d+-\\\\d+"""', 'v_grade'], {}), "('\\\\d+-\\\\d+', v_grade)\n", (3433, 3455), False, 'import re\n'), ((4709, 4741), 're.match', 're.match', (['"""\\\\d+-\\\\d+"""', 'ice_grade'], {}), "('\\\\d+-\\\\d+', ice_grade)\n", (4717, 4741), False, 'import re\n'), ((6975, 7009), ... |
# -*- coding: utf-8 -*-
"""The XFS path specification implementation."""
from dfvfs.lib import definitions
from dfvfs.path import factory
from dfvfs.path import path_spec
class XFSPathSpec(path_spec.PathSpec):
"""XFS path specification implementation.
Attributes:
inode (int): inode.
location (str): loca... | [
"dfvfs.path.factory.Factory.RegisterPathSpec"
] | [((1447, 1492), 'dfvfs.path.factory.Factory.RegisterPathSpec', 'factory.Factory.RegisterPathSpec', (['XFSPathSpec'], {}), '(XFSPathSpec)\n', (1479, 1492), False, 'from dfvfs.path import factory\n')] |
import numpy as np
import unittest
from network_attack_simulator.envs.action import Action
from network_attack_simulator.envs.machine import Machine
A_COST = 10
class MachineTestCase(unittest.TestCase):
def setUp(self):
self.test_r = 5000.0
self.services = np.asarray([True, False, True])
... | [
"unittest.main",
"network_attack_simulator.envs.action.Action",
"numpy.asarray",
"network_attack_simulator.envs.machine.Machine"
] | [((2902, 2917), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2915, 2917), False, 'import unittest\n'), ((281, 312), 'numpy.asarray', 'np.asarray', (['[True, False, True]'], {}), '([True, False, True])\n', (291, 312), True, 'import numpy as np\n'), ((336, 366), 'network_attack_simulator.envs.machine.Machine', 'M... |
##print("<-----Fibonacci Sequence----->")
##print("Created by EarlierMeat1", '\n')
from tkinter import *
from PIL import ImageTk,Image
from tkinter import messagebox
###--- Start Up Window
root = Tk()
root.title('Fibonacci Sequence')
root.geometry('400x400')
# Setting Variables
n1, n2 = 0, 1
###---... | [
"tkinter.messagebox.askokcancel"
] | [((646, 724), 'tkinter.messagebox.askokcancel', 'messagebox.askokcancel', (['"""Close Application"""', '"""Are you sure you want to close?"""'], {}), "('Close Application', 'Are you sure you want to close?')\n", (668, 724), False, 'from tkinter import messagebox\n')] |
import time
import math
import random
from ..ga.individual import Individual
from ..utils import stats
def start(tests, config):
TIME_LIMIT = config['TIME_LIMIT']
start_time = time.time()
elapsed = 0
last_elapsed_time_floored = 0
iteration_number = 0
evaluation_graph = stats.Graph()
# Gene... | [
"math.ceil",
"time.time",
"math.floor"
] | [((186, 197), 'time.time', 'time.time', ([], {}), '()\n', (195, 197), False, 'import time\n'), ((684, 703), 'math.floor', 'math.floor', (['elapsed'], {}), '(elapsed)\n', (694, 703), False, 'import math\n'), ((620, 631), 'time.time', 'time.time', ([], {}), '()\n', (629, 631), False, 'import time\n'), ((928, 959), 'math.... |
"""TIPOS NÚMERICOS """
import random #importa rndom
num_i = 10
num_f = 5.2
num_c = 1j
num_r = random.randrange(0,59)#define o intervalo de valores
x=num_r
print ("Valor: "+ str (x) + " Tipo: " + str(type(x) )) | [
"random.randrange"
] | [((97, 120), 'random.randrange', 'random.randrange', (['(0)', '(59)'], {}), '(0, 59)\n', (113, 120), False, 'import random\n')] |
import json
class SoundModelParams:
"""
Hyperparameters, or perhaps mega-hyperparameters or hyper-hyperparameters,
related to a trained MFCC model. Including:
mfccRows: The window size of MFCC rows needed to run the model against.
The window must be normalized with MfccWav.normalizeMfccArray().
... | [
"json.dump"
] | [((720, 794), 'json.dump', 'json.dump', (["{'mfccRows': self.mfccRows, 'instruments': self.instruments}", 'j'], {}), "({'mfccRows': self.mfccRows, 'instruments': self.instruments}, j)\n", (729, 794), False, 'import json\n')] |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 <NAME>, CESNET.
#
# oarepo-references is free software; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.
"""OArepo module for tracking and updating references in Invenio records."""
import abc
import typing
... | [
"uuid",
"invenio_base.utils.obj_or_import_string",
"marshmallow.validates_schema",
"uuid.uuid4",
"flask_principal.Permission"
] | [((3326, 3370), 'marshmallow.validates_schema', 'validates_schema', ([], {'skip_on_field_errors': '(False)'}), '(skip_on_field_errors=False)\n', (3342, 3370), False, 'from marshmallow import missing, post_load, pre_load, validates_schema\n'), ((5681, 5726), 'invenio_base.utils.obj_or_import_string', 'obj_or_import_stri... |
from mva_demo.users.models import User
from django.db import models
from django.urls import reverse
class SongManager(models.Manager):
def get_queryset(self):
return super(SongManager, self).get_queryset().filter(is_active=True)
class Category(models.Model):
name = models.CharField(max_length=255, db... | [
"django.db.models.Manager",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.SlugField",
"django.urls.reverse",
"django.db.models.DateTimeField",
"django.db.models.CharField"
] | [((285, 332), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(255)', 'db_index': '(True)'}), '(max_length=255, db_index=True)\n', (301, 332), False, 'from django.db import models\n'), ((344, 389), 'django.db.models.SlugField', 'models.SlugField', ([], {'max_length': '(255)', 'unique': '(True)'})... |
import os
import csv
election_csv = os.path.join("..", "election_data.csv")
with open(election_csv, newline="") as electionfile:
ereader = csv.reader(electionfile, delimiter=",")
election_header = next(electionfile, None)
Total_Votes = 0
Khan_Votes = 0
Correy_Votes = 0
Li_Votes = 0
OToo... | [
"os.path.join",
"csv.reader"
] | [((37, 76), 'os.path.join', 'os.path.join', (['""".."""', '"""election_data.csv"""'], {}), "('..', 'election_data.csv')\n", (49, 76), False, 'import os\n'), ((145, 184), 'csv.reader', 'csv.reader', (['electionfile'], {'delimiter': '""","""'}), "(electionfile, delimiter=',')\n", (155, 184), False, 'import csv\n')] |
from django.contrib.auth.models import User
import factory
class UserFactory(factory.django.DjangoModelFactory):
username = factory.Faker('name')
email = factory.Sequence(lambda n: '<EMAIL>' % n)
class Meta:
model = User
| [
"factory.Faker",
"factory.Sequence"
] | [((130, 151), 'factory.Faker', 'factory.Faker', (['"""name"""'], {}), "('name')\n", (143, 151), False, 'import factory\n'), ((164, 205), 'factory.Sequence', 'factory.Sequence', (["(lambda n: '<EMAIL>' % n)"], {}), "(lambda n: '<EMAIL>' % n)\n", (180, 205), False, 'import factory\n')] |
import numpy as np
from datetime import datetime
import System
from System import Array
from DHI.Generic.MikeZero import eumUnit, eumQuantity
from DHI.Generic.MikeZero.DFS import (
DfsFileFactory,
DfsFactory,
DfsSimpleType,
DataValueType,
)
from DHI.Generic.MikeZero.DFS.dfs123 import Dfs1Builder
from .... | [
"DHI.Generic.MikeZero.DFS.DfsFileFactory.Dfs1FileOpenEdit",
"datetime.datetime.strptime",
"DHI.Generic.MikeZero.eumQuantity.Create",
"DHI.Generic.MikeZero.DFS.DfsFileFactory.DfsGenericOpen",
"datetime.datetime.now",
"DHI.Generic.MikeZero.DFS.dfs123.Dfs1Builder.Create",
"System.DateTime",
"numpy.ndarra... | [((1138, 1177), 'DHI.Generic.MikeZero.DFS.DfsFileFactory.DfsGenericOpen', 'DfsFileFactory.DfsGenericOpen', (['filename'], {}), '(filename)\n', (1167, 1177), False, 'from DHI.Generic.MikeZero.DFS import DfsFileFactory, DfsFactory, DfsSimpleType, DataValueType\n'), ((3210, 3251), 'DHI.Generic.MikeZero.DFS.DfsFileFactory.... |
# Generated by Django 3.1.2 on 2020-10-14 12:24
import os
from django.db import migrations
from koku import migration_sql_helpers as msh
def apply_clone_schema(apps, schema_editor):
path = msh.find_db_functions_dir()
msh.apply_sql_file(schema_editor, os.path.join(path, "clone_schema.sql"), literal_placehold... | [
"os.path.join",
"django.db.migrations.RunPython",
"koku.migration_sql_helpers.find_db_functions_dir"
] | [((197, 224), 'koku.migration_sql_helpers.find_db_functions_dir', 'msh.find_db_functions_dir', ([], {}), '()\n', (222, 224), True, 'from koku import migration_sql_helpers as msh\n'), ((263, 301), 'os.path.join', 'os.path.join', (['path', '"""clone_schema.sql"""'], {}), "(path, 'clone_schema.sql')\n", (275, 301), False,... |
#!/usr/bin/python -W ignore -tt
"""Module to collect data from network devices."""
from collections import defaultdict
from datetime import datetime
import sys
import re
import warnings
import ipaddress
import helpers
import netspot
import netspot_settings
from napalm import get_network_driver
from spotmax import S... | [
"netspot.NetSPOT",
"helpers.resolv",
"warnings.catch_warnings",
"datetime.datetime.now",
"collections.defaultdict",
"napalm.get_network_driver",
"sys.exit",
"spotmax.SpotMAX.__init__",
"warnings.filterwarnings"
] | [((730, 743), 'collections.defaultdict', 'defaultdict', ([], {}), '()\n', (741, 743), False, 'from collections import defaultdict\n'), ((1566, 1593), 'napalm.get_network_driver', 'get_network_driver', (['"""junos"""'], {}), "('junos')\n", (1584, 1593), False, 'from napalm import get_network_driver\n'), ((4450, 4494), '... |
import argparse
from tools.trainer import Trainer
def make_parser():
parser = argparse.ArgumentParser()
# training config
parser.add_argument("--train", default=False, action="store_true")
parser.add_argument("--epochs", type=int, default=100, help="training epochs")
parser.add_argument("--batch-... | [
"tools.trainer.Trainer",
"argparse.ArgumentParser"
] | [((85, 110), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (108, 110), False, 'import argparse\n'), ((1871, 1884), 'tools.trainer.Trainer', 'Trainer', (['args'], {}), '(args)\n', (1878, 1884), False, 'from tools.trainer import Trainer\n')] |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 11 14:27:45 2018
@author: aceituno
"""
import data_processing as dp
import matplotlib.pyplot as plt
import numpy as np
path_fig = './'
showPlots = True
savePlots = True
def plot_spiking_rate_with_learning(spikesInitial, spikesFinal, neurons, ti... | [
"matplotlib.pyplot.hist",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"data_processing.spike_timing_evolution",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"data_processing.spike_timing_evolution_percentiles",
"matplotlib.pyplot.ioff",
"matplotlib.pyplot.fill_between",
"nump... | [((371, 401), 'numpy.linspace', 'np.linspace', (['(0)', 'timePlot', 'bins'], {}), '(0, timePlot, bins)\n', (382, 401), True, 'import numpy as np\n'), ((472, 525), 'matplotlib.pyplot.hist', 'plt.hist', (['times', 'bins'], {'alpha': '(0.5)', 'label': '"""Before STDP"""'}), "(times, bins, alpha=0.5, label='Before STDP')\n... |
""" addons.xml generator """
import os
import gzip
import requests
import hashlib
GITHUB_USERNAME = "abprime"
ADDONS = [
"repository.botallen",
"plugin.video.jiotv"
]
class Generator:
"""
Generates a new addons.xml file from each addons addon.xml file
and a new addons.xml.md5 hash file. ... | [
"hashlib.md5",
"gzip.open",
"os.path.join",
"requests.get",
"os.path.isdir"
] | [((936, 956), 'os.path.isdir', 'os.path.isdir', (['addon'], {}), '(addon)\n', (949, 956), False, 'import os\n'), ((2325, 2357), 'gzip.open', 'gzip.open', (['"""addons.xml.gz"""', '"""wb"""'], {}), "('addons.xml.gz', 'wb')\n", (2334, 2357), False, 'import gzip\n'), ((2523, 2536), 'hashlib.md5', 'hashlib.md5', ([], {}), ... |
import numpy as np
#import simpleaudio as sa
import scipy.io.wavfile as sw
'''
def audioplay(fs, y):
yout = np.iinfo(np.int16).max / np.max(np.abs(y)) * y
yout = yout.astype(np.int16)
play_obj = sa.play_buffer(yout, y.ndim, 2, fs)
'''
def wavread(wavefile):
fs, y = sw.read(wavefile)
if y.dtype == ... | [
"numpy.abs",
"numpy.iinfo",
"scipy.io.wavfile.read",
"scipy.io.wavfile.write"
] | [((284, 301), 'scipy.io.wavfile.read', 'sw.read', (['wavefile'], {}), '(wavefile)\n', (291, 301), True, 'import scipy.io.wavfile as sw\n'), ((1057, 1085), 'scipy.io.wavfile.write', 'sw.write', (['wavefile', 'fs', 'data'], {}), '(wavefile, fs, data)\n', (1065, 1085), True, 'import scipy.io.wavfile as sw\n'), ((758, 770)... |
import RPi.GPIO as GPIO
import sys
import Adafruit_DHT
import time
try:
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(23,GPIO.OUT)#GPIO23
GPIO.setup(24,GPIO.OUT)#GPIO24
flag=0
while True:
humidity, temperature = Adafruit_DHT.read_retry(11, 4)#DHT11, GPIO 4
... | [
"RPi.GPIO.cleanup",
"RPi.GPIO.setup",
"RPi.GPIO.output",
"RPi.GPIO.setwarnings",
"time.sleep",
"Adafruit_DHT.read_retry",
"RPi.GPIO.setmode"
] | [((81, 103), 'RPi.GPIO.setmode', 'GPIO.setmode', (['GPIO.BCM'], {}), '(GPIO.BCM)\n', (93, 103), True, 'import RPi.GPIO as GPIO\n'), ((109, 132), 'RPi.GPIO.setwarnings', 'GPIO.setwarnings', (['(False)'], {}), '(False)\n', (125, 132), True, 'import RPi.GPIO as GPIO\n'), ((138, 162), 'RPi.GPIO.setup', 'GPIO.setup', (['(23... |
##################################################
## / ___/ _ \| _ \/ ___|| | | |_ _| \ | | ____|##
##| | | | | | |_) \___ \| |_| || || \| | _| ##
##| |__| |_| | _ < ___) | _ || || |\ | |___ ##
## \____\___/|_| \_\____/|_| |_|___|_| \_|_____|##
##################################################
#Usage: pytho... | [
"requests.get"
] | [((538, 564), 'requests.get', 'requests.get', (['url_to_check'], {}), '(url_to_check)\n', (550, 564), False, 'import requests\n')] |
import pytest
pytest.importorskip("speedtest")
def test_load_module():
__import__("modules.core.speedtest")
| [
"pytest.importorskip"
] | [((15, 47), 'pytest.importorskip', 'pytest.importorskip', (['"""speedtest"""'], {}), "('speedtest')\n", (34, 47), False, 'import pytest\n')] |
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from osmaxx.excerptexport.models import Export
def tracker(request, export_id):
export = get_object_or_404(Export, pk=export_id)
export.set_and_handle_new_status(request.GET['status'], incoming_request=request)
response ... | [
"django.http.HttpResponse",
"django.shortcuts.get_object_or_404"
] | [((180, 219), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['Export'], {'pk': 'export_id'}), '(Export, pk=export_id)\n', (197, 219), False, 'from django.shortcuts import get_object_or_404\n'), ((322, 338), 'django.http.HttpResponse', 'HttpResponse', (['""""""'], {}), "('')\n", (334, 338), False, 'from dj... |
# Generated by Django 3.1.5 on 2021-02-05 03:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('barovian_activity_map', '0002_auto_20210128_2228'),
]
operations = [
migrations.CreateModel(
na... | [
"django.db.models.TextField",
"django.db.models.IntegerField",
"django.db.models.ForeignKey",
"django.db.models.AutoField",
"django.db.models.DateTimeField",
"django.db.models.CharField"
] | [((392, 443), 'django.db.models.AutoField', 'models.AutoField', ([], {'primary_key': '(True)', 'serialize': '(False)'}), '(primary_key=True, serialize=False)\n', (408, 443), False, 'from django.db import migrations, models\n'), ((471, 503), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'})... |
'''Proxy Server'''
import os
import socket
import sys
import threading
import time
import ipaddress
BUFFER_SIZE = 1024
MAX_CONNECTION = 25
ALLOWED_ACTIONS = ['GET', 'POST']
CACHE_SIZE = 3
TIMEOUT = 300
PORT = 20100
HOST = ''
BLACK_LIST = []
blocked = []
blocked_ips = []
admins = []
BLACKLIST_FILE = "blacklist.txt"
U... | [
"threading.Thread",
"time.time",
"socket.socket",
"sys.exit"
] | [((505, 554), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (518, 554), False, 'import socket\n'), ((1414, 1476), 'threading.Thread', 'threading.Thread', ([], {'target': 'self.clientService', 'args': '(conn, addr)'}), '(target=self.clientServ... |
from cky import CKY
from chart import CHART
import json
def main():
with open("text.txt") as f:
sentence = f.read().split()
print("sentence : %s\n" %sentence)
with open("rule.json", 'r') as f:
json_dict = json.load(f)
grammar = json_dict["gram"]
dictionary = json_dict["... | [
"json.load",
"cky.CKY"
] | [((420, 454), 'cky.CKY', 'CKY', (['grammar', 'dictionary', 'sentence'], {}), '(grammar, dictionary, sentence)\n', (423, 454), False, 'from cky import CKY\n'), ((239, 251), 'json.load', 'json.load', (['f'], {}), '(f)\n', (248, 251), False, 'import json\n')] |
import numpy as np
# Compute element-wise square of vector
def vsquare(V):
R = np.power(V, 2)
| [
"numpy.power"
] | [((85, 99), 'numpy.power', 'np.power', (['V', '(2)'], {}), '(V, 2)\n', (93, 99), True, 'import numpy as np\n')] |
# The MIT License (MIT)
# Copyright (c) 2014 <NAME> <<EMAIL>>
# 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, mo... | [
"inspect.getargspec"
] | [((1747, 1764), 'inspect.getargspec', 'getargspec', (['value'], {}), '(value)\n', (1757, 1764), False, 'from inspect import getargspec\n')] |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'd:\Dropbox\hobby\Modding\Programs\Github\My_Repos\PyQt_Socius\designer_files\links_tab_widget.ui'
#
# Created by: PyQt5 UI code generator 5.15.1
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do n... | [
"PyQt5.QtWidgets.QPlainTextEdit",
"PyQt5.QtWidgets.QSpacerItem",
"PyQt5.QtWidgets.QTableView",
"PyQt5.QtWidgets.QGridLayout",
"PyQt5.QtWidgets.QGroupBox",
"PyQt5.QtWidgets.QLabel",
"PyQt5.QtWidgets.QPushButton",
"PyQt5.QtWidgets.QLineEdit",
"PyQt5.QtCore.QSize"
] | [((586, 617), 'PyQt5.QtWidgets.QGridLayout', 'QtWidgets.QGridLayout', (['LinksTab'], {}), '(LinksTab)\n', (607, 617), False, 'from PyQt5 import QtCore, QtGui, QtWidgets\n'), ((703, 732), 'PyQt5.QtWidgets.QGroupBox', 'QtWidgets.QGroupBox', (['LinksTab'], {}), '(LinksTab)\n', (722, 732), False, 'from PyQt5 import QtCore,... |
# wenshengwang at gmail dot com
# BSD License
"""This is a TCP server. It is started by the JuicyRaspberryPie plugin/mod and
listen on localhost port 4731(plugin) or 4732(mod).
When it start, it scan the "pplugins" directory for any python files and try
to load them as modules, in these modules, it search for any ... | [
"socketserver.TCPServer",
"sys.path.insert",
"importlib.import_module",
"os.path.join",
"time.sleep",
"threading.Event",
"os.path.dirname",
"yaml.safe_load",
"os.path.basename",
"importlib.reload",
"threading.Thread"
] | [((753, 783), 'sys.path.insert', 'sys.path.insert', (['(0)', 'plugin_dir'], {}), '(0, plugin_dir)\n', (768, 783), False, 'import sys\n'), ((1269, 1286), 'threading.Event', 'threading.Event', ([], {}), '()\n', (1284, 1286), False, 'import threading\n'), ((4019, 4069), 'socketserver.TCPServer', 'socketserver.TCPServer', ... |
# Import packages
import xml.etree.ElementTree as ET
import xml.dom.minidom as DOM
def add_GoalKeeper(annotations, teamId, goalKeeperId):
track = ET.SubElement(annotations, 'track')
track.attrib['id'] = str(-1)
track.attrib['label'] = "GoalKeeper"
box = ET.SubElement(track, 'box')
box.attrib['fr... | [
"xml.etree.ElementTree.Element",
"xml.etree.ElementTree.SubElement",
"xml.etree.ElementTree.tostring"
] | [((153, 188), 'xml.etree.ElementTree.SubElement', 'ET.SubElement', (['annotations', '"""track"""'], {}), "(annotations, 'track')\n", (166, 188), True, 'import xml.etree.ElementTree as ET\n'), ((274, 301), 'xml.etree.ElementTree.SubElement', 'ET.SubElement', (['track', '"""box"""'], {}), "(track, 'box')\n", (287, 301), ... |
#author:<NAME>
#insitution: MIT
import matplotlib.pyplot as plt
import time
import numpy as np
try:
from HAPILite import CalcCrossSection
except:
from ..HAPILite import CalcCrossSection
WaveNumber = np.arange(0,10000,0.001)
StartTime = time.time()
CrossSection = CalcCrossSection("CO2",Temp=1000.0,WN_Grid=... | [
"matplotlib.pyplot.plot",
"HAPILite.CalcCrossSection",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"time.time",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((211, 237), 'numpy.arange', 'np.arange', (['(0)', '(10000)', '(0.001)'], {}), '(0, 10000, 0.001)\n', (220, 237), True, 'import numpy as np\n'), ((249, 260), 'time.time', 'time.time', ([], {}), '()\n', (258, 260), False, 'import time\n'), ((277, 367), 'HAPILite.CalcCrossSection', 'CalcCrossSection', (['"""CO2"""'], {'... |
# pylint: disable=missing-docstring,no-self-use
import re
import pytest
from context import esperanto_analyzer
from esperanto_analyzer.speech import Article
from esperanto_analyzer.analyzers.morphological import ArticleMorphologicalAnalyzer
class TestArticleMorphologicalAnalyzerBasic():
TEST_WORD = 'la'
de... | [
"esperanto_analyzer.analyzers.morphological.ArticleMorphologicalAnalyzer.ARTICLES_MATCH_REGEXP.match",
"esperanto_analyzer.analyzers.morphological.ArticleMorphologicalAnalyzer.MATCH_REGEXP.match",
"esperanto_analyzer.analyzers.morphological.ArticleMorphologicalAnalyzer.word_class",
"esperanto_analyzer.analyze... | [((452, 496), 'esperanto_analyzer.analyzers.morphological.ArticleMorphologicalAnalyzer', 'ArticleMorphologicalAnalyzer', (['self.TEST_WORD'], {}), '(self.TEST_WORD)\n', (480, 496), False, 'from esperanto_analyzer.analyzers.morphological import ArticleMorphologicalAnalyzer\n'), ((787, 831), 'esperanto_analyzer.analyzers... |
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship, backref
# TODO: db_uri
# dialect+driver://username:password@host:port/database?charset=utf8
DB_URI = 'mysql+pymysql://root:root123@127... | [
"sqlalchemy.orm.sessionmaker",
"sqlalchemy.orm.backref",
"sqlalchemy.create_engine",
"sqlalchemy.ForeignKey",
"sqlalchemy.String",
"sqlalchemy.ext.declarative.declarative_base",
"sqlalchemy.Column"
] | [((373, 394), 'sqlalchemy.create_engine', 'create_engine', (['DB_URI'], {}), '(DB_URI)\n', (386, 394), False, 'from sqlalchemy import create_engine, Column, Integer, String, ForeignKey\n'), ((403, 432), 'sqlalchemy.ext.declarative.declarative_base', 'declarative_base', ([], {'bind': 'engine'}), '(bind=engine)\n', (419,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# J.V.Ojala 17.11.2021
# coinstar
import json
import datetime
import sys, getopt
import status
import gui
def time_to_posix(year, mon, day, hour=0, min=0, sec=0):
"""Takes date and time and returns POSIX timestamp in seconds"""
try:
time_object = datetim... | [
"datetime.datetime",
"getopt.getopt",
"datetime.datetime.fromtimestamp",
"gui.Gui",
"status.Status",
"json.dumps",
"sys.exit"
] | [((3604, 3619), 'status.Status', 'status.Status', ([], {}), '()\n', (3617, 3619), False, 'import status\n'), ((313, 392), 'datetime.datetime', 'datetime.datetime', (['year', 'mon', 'day', 'hour', 'min', 'sec'], {'tzinfo': 'datetime.timezone.utc'}), '(year, mon, day, hour, min, sec, tzinfo=datetime.timezone.utc)\n', (33... |
from graphene import AbstractType, String
from .UpdateMurmurations import UpdateRecords
class UpdateMutation(AbstractType):
record_type = String()
| [
"graphene.String"
] | [((145, 153), 'graphene.String', 'String', ([], {}), '()\n', (151, 153), False, 'from graphene import AbstractType, String\n')] |
from marshmallow import fields
from marshmallow import Schema
from marshmallow.validate import OneOf
class UsersListFilterSchema(Schema):
sort_key = fields.String(
OneOf(choices=['username', 'email', 'phone_number']),
missing='username')
sort_order = fields.String(missing='asc')
class UsersL... | [
"marshmallow.validate.OneOf",
"marshmallow.fields.String"
] | [((277, 305), 'marshmallow.fields.String', 'fields.String', ([], {'missing': '"""asc"""'}), "(missing='asc')\n", (290, 305), False, 'from marshmallow import fields\n'), ((354, 369), 'marshmallow.fields.String', 'fields.String', ([], {}), '()\n', (367, 369), False, 'from marshmallow import fields\n'), ((382, 397), 'mars... |
# requires inkscape to be installed
import subprocess, sys, os
from subprocess import CalledProcessError, PIPE, check_output
from PIL import Image, ImageOps
class SVGToBitmapError(Exception):
pass
class ImageMagickError(Exception):
pass
def query_svg(svg_filepath):
if not os.path.isfile(svg_filepath)... | [
"subprocess.check_output",
"PIL.Image.open",
"subprocess.run",
"PIL.ImageOps.fit",
"PIL.ImageOps.expand",
"os.path.isfile"
] | [((424, 477), 'subprocess.check_output', 'check_output', (["['inkscape', '--query-x', svg_filepath]"], {}), "(['inkscape', '--query-x', svg_filepath])\n", (436, 477), False, 'from subprocess import CalledProcessError, PIPE, check_output\n'), ((522, 575), 'subprocess.check_output', 'check_output', (["['inkscape', '--que... |
import requests
import re
from bs4 import BeautifulSoup
import json
from collections import namedtuple
from random import randint
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36',
'Accept-Encoding': ', '.join(('g... | [
"bs4.BeautifulSoup",
"random.randint",
"requests.get"
] | [((465, 479), 'random.randint', 'randint', (['(1)', '(15)'], {}), '(1, 15)\n', (472, 479), False, 'from random import randint\n'), ((625, 659), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (637, 659), False, 'import requests\n'), ((713, 740), 'bs4.BeautifulSoup', 'Beaut... |
""" Unit Tests for Py-ART's config.py module. """
import pyart
from StringIO import StringIO
def test_debug_info():
# test to see that something is written when _debug_info is called
# we don't care what is written, just that something is.
buf = StringIO()
pyart._debug_info(buf)
assert buf.len > ... | [
"StringIO.StringIO",
"pyart._debug_info"
] | [((261, 271), 'StringIO.StringIO', 'StringIO', ([], {}), '()\n', (269, 271), False, 'from StringIO import StringIO\n'), ((276, 298), 'pyart._debug_info', 'pyart._debug_info', (['buf'], {}), '(buf)\n', (293, 298), False, 'import pyart\n')] |
import pygame as pg
from math import pi, sin, cos
white = (255, 255, 255)
gray = (100, 100, 100)
black = (0, 0, 0)
radius_scale = 100
def main():
time = 0
path = []
pg.init()
pg.font.init()
font = pg.font.SysFont('Consolas', 24)
pg.display.set_caption("Fourier")
# CONFIG
width = ... | [
"pygame.draw.circle",
"pygame.init",
"pygame.event.set_allowed",
"pygame.event.get",
"pygame.draw.line",
"pygame.display.set_mode",
"pygame.draw.lines",
"math.cos",
"pygame.key.get_pressed",
"pygame.font.init",
"pygame.display.set_caption",
"pygame.display.update",
"math.sin",
"pygame.font... | [((183, 192), 'pygame.init', 'pg.init', ([], {}), '()\n', (190, 192), True, 'import pygame as pg\n'), ((197, 211), 'pygame.font.init', 'pg.font.init', ([], {}), '()\n', (209, 211), True, 'import pygame as pg\n'), ((223, 254), 'pygame.font.SysFont', 'pg.font.SysFont', (['"""Consolas"""', '(24)'], {}), "('Consolas', 24)\... |
# To run the job:
# pyats run job group_example_job.py
# Description: This example shows looping and variants in pyats
import os
from pyats.easypy import run
# Data structure used to mentions that to execute
from pyats.datastructures.logic import And, Or, Not
def main():
# Find the location of the script in rela... | [
"os.path.join",
"pyats.easypy.run",
"pyats.datastructures.logic.Not",
"pyats.datastructures.logic.Or",
"os.path.abspath",
"pyats.datastructures.logic.And"
] | [((417, 467), 'os.path.join', 'os.path.join', (['test_path', '"""group_example_script.py"""'], {}), "(test_path, 'group_example_script.py')\n", (429, 467), False, 'import os\n'), ((1803, 1855), 'pyats.easypy.run', 'run', ([], {'testscript': 'testscript', 'groups': 'group1_not_group2'}), '(testscript=testscript, groups=... |
import numpy as np
import general as gen
def cluster(dataArray, k, dim, dNo, t):
# reps = gen.initializeRandom(dataArray, k, dim, dNo)
# print(reps)
# reps = np.array([[1], [2], [3]])
reps = np.array([[1], [11], [28]])
print(reps)
for itr in range(t):
n = []
# print(dataArray)
... | [
"numpy.array",
"general.findmeanofcluster",
"general.clustering_k_means"
] | [((209, 236), 'numpy.array', 'np.array', (['[[1], [11], [28]]'], {}), '([[1], [11], [28]])\n', (217, 236), True, 'import numpy as np\n'), ((339, 386), 'general.clustering_k_means', 'gen.clustering_k_means', (['dataArray', 'k', 'reps', 'dNo'], {}), '(dataArray, k, reps, dNo)\n', (361, 386), True, 'import general as gen\... |
import numpy as np
import dp_penalty
params = dp_penalty.PenaltyParams(
tau = 0.2,
prop_sigma = np.repeat(0.008 * 5, 2),
r_clip_bound = 3.5,
ocu = True,
grw = True
)
| [
"numpy.repeat"
] | [((105, 128), 'numpy.repeat', 'np.repeat', (['(0.008 * 5)', '(2)'], {}), '(0.008 * 5, 2)\n', (114, 128), True, 'import numpy as np\n')] |