code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# Generated by Django 2.1.7 on 2019-03-18 18:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('conference', '0003_auto_20190313_1858'),
]
operations = [
migrations.AddField(
model_name='conference',
name='source... | [
"django.db.models.CharField"
] | [((341, 387), 'django.db.models.CharField', 'models.CharField', ([], {'default': '"""acm"""', 'max_length': '(32)'}), "(default='acm', max_length=32)\n", (357, 387), False, 'from django.db import migrations, models\n')] |
import MySQLdb
from starcraft import Ladder, Player, Team
class MySQL:
host = "192.168.102.128"
port = 3306
username = "starcraft"
password = "<PASSWORD>"
database = "starcraft"
def __init__(self):
self.db = MySQLdb.connect(host=self.host, port=self.port, user=self.username, passwd=se... | [
"MySQLdb.connect"
] | [((243, 355), 'MySQLdb.connect', 'MySQLdb.connect', ([], {'host': 'self.host', 'port': 'self.port', 'user': 'self.username', 'passwd': 'self.password', 'db': 'self.database'}), '(host=self.host, port=self.port, user=self.username, passwd=\n self.password, db=self.database)\n', (258, 355), False, 'import MySQLdb\n')] |
import time
from dataclasses import dataclass
import cv2
import numpy
from lib.rect import Rect
from lib.utils import dump
MAX = 255
@dataclass
class Channelmap():
r: numpy.ndarray
g: numpy.ndarray
b: numpy.ndarray
c: numpy.ndarray
m: numpy.ndarray
y: numpy.ndarray
k: numpy.ndarray
... | [
"cv2.min",
"cv2.merge",
"cv2.normalize",
"cv2.split"
] | [((916, 974), 'cv2.normalize', 'cv2.normalize', (['v', 'None', '(0)', '(256)', 'cv2.NORM_MINMAX', 'cv2.CV_8U'], {}), '(v, None, 0, 256, cv2.NORM_MINMAX, cv2.CV_8U)\n', (929, 974), False, 'import cv2\n'), ((985, 1005), 'cv2.merge', 'cv2.merge', (['(v, v, v)'], {}), '((v, v, v))\n', (994, 1005), False, 'import cv2\n'), (... |
import subprocess
import re
import os
import glob
import sys
import multiprocessing
import argparse
from Process import Process
from VariantCaller import VariantCaller
def main():
parser = argparse.ArgumentParser(prog="SC_Mutation" , description="Analyze Mutational properites of Single Cell RNA-seq data"
... | [
"VariantCaller.VariantCaller",
"Process.Process",
"argparse.ArgumentParser"
] | [((196, 355), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""SC_Mutation"""', 'description': '"""Analyze Mutational properites of Single Cell RNA-seq data"""', 'epilog': '"""Enjoy the program! :)"""'}), "(prog='SC_Mutation', description=\n 'Analyze Mutational properites of Single Cell RNA-... |
# Generated by Django 3.1.5 on 2021-01-12 17:27
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AU... | [
"django.db.models.ForeignKey",
"django.db.models.ManyToManyField",
"django.db.models.AutoField",
"django.db.migrations.swappable_dependency",
"django.db.models.CharField"
] | [((277, 334), 'django.db.migrations.swappable_dependency', 'migrations.swappable_dependency', (['settings.AUTH_USER_MODEL'], {}), '(settings.AUTH_USER_MODEL)\n', (308, 334), False, 'from django.db import migrations, models\n'), ((464, 557), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)... |
import io
import time
import picamera
framerate = 90
quality = 100
resolutions = [(1920, 1080), (1280, 720), (800, 600), (640, 480), (320, 240)]
samples = 50
with picamera.PiCamera(framerate=framerate) as camera:
time.sleep(2) # camera warm-up time
for res in resolutions:
camera.resolution = res
... | [
"time.time",
"picamera.PiCamera",
"time.sleep",
"io.BytesIO"
] | [((164, 202), 'picamera.PiCamera', 'picamera.PiCamera', ([], {'framerate': 'framerate'}), '(framerate=framerate)\n', (181, 202), False, 'import picamera\n'), ((218, 231), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (228, 231), False, 'import time\n'), ((331, 342), 'time.time', 'time.time', ([], {}), '()\n', (34... |
from __future__ import absolute_import
import openshift as oc
import base64
import json
def get_kubeconfig():
"""
:return: Returns the current kubeconfig as a python dict
"""
return json.loads(oc.invoke('config',
cmd_args=['view',
... | [
"openshift.invoke",
"base64.b64encode",
"base64.b64decode"
] | [((7179, 7204), 'base64.b64encode', 'base64.b64encode', (['ca_data'], {}), '(ca_data)\n', (7195, 7204), False, 'import base64\n'), ((5944, 5966), 'base64.b64decode', 'base64.b64decode', (['data'], {}), '(data)\n', (5960, 5966), False, 'import base64\n'), ((212, 289), 'openshift.invoke', 'oc.invoke', (['"""config"""'], ... |
import importlib
import json
import demistomock as demisto
queued_response = {u'response_code': -2,
u'resource': u'YES_THIS_IS_A_UID',
u'scan_id': u'YES_THIS_IS_A_UID',
u'verbose_msg': u'Your resource is queued for analysis'}
def load_test_data(json_path):
... | [
"json.load",
"importlib.import_module"
] | [((624, 673), 'importlib.import_module', 'importlib.import_module', (['"""VirusTotal-Private_API"""'], {}), "('VirusTotal-Private_API')\n", (647, 673), False, 'import importlib\n'), ((1465, 1514), 'importlib.import_module', 'importlib.import_module', (['"""VirusTotal-Private_API"""'], {}), "('VirusTotal-Private_API')\n... |
import unittest
class TestDynamicsModel(unittest.TestCase):
def setUp(self):
from muzero.models.dynamics_model import DynamicsModel
from muzero.environment.action import Action
import tensorflow as tf
self.dynamics_model = DynamicsModel()
self.batch_of_hidden_states = tf.o... | [
"muzero.models.representation_model.RepresentationModel",
"tensorflow.ones",
"muzero.models.dynamics_model.DynamicsModel",
"tensorflow.concat",
"numpy.array",
"muzero.environment.action.Action",
"muzero.models.prediction_model.PredictionModel"
] | [((262, 277), 'muzero.models.dynamics_model.DynamicsModel', 'DynamicsModel', ([], {}), '()\n', (275, 277), False, 'from muzero.models.dynamics_model import DynamicsModel\n'), ((316, 337), 'tensorflow.ones', 'tf.ones', (['[4, 3, 3, 1]'], {}), '([4, 3, 3, 1])\n', (323, 337), True, 'import tensorflow as tf\n'), ((368, 377... |
import os
import unittest
import pytest
from flask import Flask
# noinspection PyProtectedMember
from dash._configs import (
pathname_configs, DASH_ENV_VARS, get_combined_config, load_dash_env_vars)
from dash import Dash, exceptions as _exc
from dash._utils import get_asset_path
class TestConfigs(unittest.TestCas... | [
"dash._configs.load_dash_env_vars",
"dash._configs.get_combined_config",
"dash._configs.DASH_ENV_VARS.items",
"flask.Flask",
"dash._utils.get_asset_path",
"os.environ.pop",
"dash._configs.pathname_configs",
"unittest.main",
"dash._configs.DASH_ENV_VARS.keys",
"dash.Dash"
] | [((5678, 5708), 'dash.Dash', 'Dash', ([], {'name': 'name', 'server': 'server'}), '(name=name, server=server)\n', (5682, 5708), False, 'from dash import Dash, exceptions as _exc\n'), ((5781, 5796), 'unittest.main', 'unittest.main', ([], {}), '()\n', (5794, 5796), False, 'import unittest\n'), ((363, 383), 'dash._configs.... |
#Genel
import sys, os, math, csv, random, time, datetime, webbrowser, subprocess
#PyQt5
from PyQt5 import QtWidgets, QtCore, QtGui
from tasarim import Ui_MainWindow
from PyQt5.QtWidgets import QFileDialog, QMessageBox
#TensorFlow
import tensorflow as tf
import tensorflow.keras
from tensorflow.keras.models import Se... | [
"csv.DictWriter",
"cv2.rectangle",
"tensorflow.keras.preprocessing.image.resize",
"PyQt5.QtGui.QIcon",
"matplotlib.pyplot.ylabel",
"tensorflow.keras.preprocessing.image.ImageDataGenerator",
"webbrowser.open",
"cv2.imshow",
"numpy.array",
"random.choices",
"tensorflow.keras.layers.Dense",
"tens... | [((24653, 24685), 'PyQt5.QtWidgets.QApplication', 'QtWidgets.QApplication', (['sys.argv'], {}), '(sys.argv)\n', (24675, 24685), False, 'from PyQt5 import QtWidgets, QtCore, QtGui\n'), ((1104, 1119), 'tasarim.Ui_MainWindow', 'Ui_MainWindow', ([], {}), '()\n', (1117, 1119), False, 'from tasarim import Ui_MainWindow\n'), ... |
from zope.interface import Interface, implementer
class IProtocolAvatar(Interface):
def logout(self):
"""
Clean up per-login resources allocated to this avatar.
"""
@implementer(IProtocolAvatar)
class ClientAvatar(object):
def __init__(self):
super().__init__()
self._... | [
"zope.interface.implementer"
] | [((198, 226), 'zope.interface.implementer', 'implementer', (['IProtocolAvatar'], {}), '(IProtocolAvatar)\n', (209, 226), False, 'from zope.interface import Interface, implementer\n')] |
from functools import reduce
from operator import __mul__
from treevalue import reduce_, FastTreeValue
def multi(items):
return reduce(__mul__, items, 1)
if __name__ == '__main__':
t = FastTreeValue({'a': 1, 'b': 2, 'x': {'c': 3, 'd': 4}, 'y': {'e': 6, 'f': 8}})
print("Sum of t:", reduce_(t, lambda **... | [
"functools.reduce",
"treevalue.FastTreeValue"
] | [((135, 160), 'functools.reduce', 'reduce', (['__mul__', 'items', '(1)'], {}), '(__mul__, items, 1)\n', (141, 160), False, 'from functools import reduce\n'), ((198, 275), 'treevalue.FastTreeValue', 'FastTreeValue', (["{'a': 1, 'b': 2, 'x': {'c': 3, 'd': 4}, 'y': {'e': 6, 'f': 8}}"], {}), "({'a': 1, 'b': 2, 'x': {'c': 3... |
import numpy as np
import MITgcmutils as mit
#import xmitgcm as xmit
#import matplotlib.pyplot as plt
from scipy.interpolate import griddata
import os
import gc
from multiprocessing import Pool
#plt.ion()
#-- directories --
dir_grd12 = '/glade/p/univ/ufsu0011/runs/gridMIT_update1/'
dir_grd50 = '/glade/p/univ/ufsu0011... | [
"numpy.radians",
"numpy.fromfile",
"os.makedirs",
"numpy.zeros",
"os.path.isdir",
"multiprocessing.Pool",
"gc.collect",
"MITgcmutils.rdmds",
"numpy.arange"
] | [((1378, 1405), 'MITgcmutils.rdmds', 'mit.rdmds', (["(dir_grd50 + 'XC')"], {}), "(dir_grd50 + 'XC')\n", (1387, 1405), True, 'import MITgcmutils as mit\n'), ((1415, 1442), 'MITgcmutils.rdmds', 'mit.rdmds', (["(dir_grd50 + 'YC')"], {}), "(dir_grd50 + 'YC')\n", (1424, 1442), True, 'import MITgcmutils as mit\n'), ((1619, 1... |
import pytest
import mining
def test_compute_lowest_md5_hash():
assert mining.compute_lowest_md5_hash('abcdef') == 609043
assert mining.compute_lowest_md5_hash('pqrstuv') == 1048970 | [
"mining.compute_lowest_md5_hash"
] | [((76, 116), 'mining.compute_lowest_md5_hash', 'mining.compute_lowest_md5_hash', (['"""abcdef"""'], {}), "('abcdef')\n", (106, 116), False, 'import mining\n'), ((138, 179), 'mining.compute_lowest_md5_hash', 'mining.compute_lowest_md5_hash', (['"""pqrstuv"""'], {}), "('pqrstuv')\n", (168, 179), False, 'import mining\n')... |
import Source.Parsing_Data as pd
import pytest
from datetime import datetime, time
def test_getTime():
assert pd.getTime("16:30") == time(16, 30)
def test_getTime_ValueError():
with pytest.raises(ValueError):
pd.getTime("25:30")
def test_getDate():
assert pd.getDate("07-10-2020") == datetime(2020... | [
"datetime.datetime",
"datetime.time",
"Source.Parsing_Data.getLastDigitLicPlate",
"pytest.raises",
"Source.Parsing_Data.getDate",
"Source.Parsing_Data.getTime"
] | [((115, 134), 'Source.Parsing_Data.getTime', 'pd.getTime', (['"""16:30"""'], {}), "('16:30')\n", (125, 134), True, 'import Source.Parsing_Data as pd\n'), ((138, 150), 'datetime.time', 'time', (['(16)', '(30)'], {}), '(16, 30)\n', (142, 150), False, 'from datetime import datetime, time\n'), ((192, 217), 'pytest.raises',... |
from builtins import zip
import numpy as np
import cv2
from matplotlib import pyplot as plt
def drawMatches(img1, kp1, img2, kp2, matches):
"""
My own implementation of cv2.drawMatches as OpenCV 2.4.9
does not have this function available but it's supported in
OpenCV 3.0.0
This function takes in... | [
"matplotlib.pyplot.imshow",
"cv2.BFMatcher",
"numpy.dstack",
"matplotlib.pyplot.show",
"cv2.imshow",
"builtins.zip",
"cv2.SIFT",
"cv2.destroyAllWindows",
"cv2.waitKey",
"numpy.float32",
"cv2.imread"
] | [((3587, 3597), 'cv2.SIFT', 'cv2.SIFT', ([], {}), '()\n', (3595, 3597), False, 'import cv2\n'), ((3726, 3741), 'cv2.BFMatcher', 'cv2.BFMatcher', ([], {}), '()\n', (3739, 3741), False, 'import cv2\n'), ((1424, 1453), 'numpy.dstack', 'np.dstack', (['[img1, img1, img1]'], {}), '([img1, img1, img1])\n', (1433, 1453), True,... |
# -*- coding:utf-8 -*-
from .. import utils
from sqlalchemy.sql import text
def mostViewTaxon(connection):
sql = "SELECT * FROM atlas.vm_taxons_plus_observes"
req = connection.execute(text(sql))
tabTax = list()
for r in req:
if r.nom_vern != None:
nom_verna = r.nom_v... | [
"sqlalchemy.sql.text"
] | [((205, 214), 'sqlalchemy.sql.text', 'text', (['sql'], {}), '(sql)\n', (209, 214), False, 'from sqlalchemy.sql import text\n')] |
import os
import sys
from kubernetes.client import CoreV1Api
from kubernetes.config import load_kube_config
from kubernetes.stream import stream
from opta.utils import yaml
configuration_file = sys.argv[1]
with open(configuration_file) as f:
configuration = yaml.load(f.read())
namespace = configuration["nam... | [
"kubernetes.stream.stream",
"os.environ.get",
"kubernetes.config.load_kube_config",
"kubernetes.client.CoreV1Api"
] | [((343, 389), 'os.environ.get', 'os.environ.get', (['"""KUBECONFIG"""', '"""~/.kube/config"""'], {}), "('KUBECONFIG', '~/.kube/config')\n", (357, 389), False, 'import os\n'), ((390, 435), 'kubernetes.config.load_kube_config', 'load_kube_config', ([], {'config_file': 'KUBECONFIG_PATH'}), '(config_file=KUBECONFIG_PATH)\n... |
"""Make a heatmap of punctuation."""
import math
from string import punctuation
import nltk
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import seaborn as sns
# Install seaborn using: pip install seaborn.
PUNCT_SET = set(punctuation)
def main():
# Load text f... | [
"nltk.word_tokenize",
"matplotlib.colors.ListedColormap",
"numpy.array",
"matplotlib.pyplot.ion",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((762, 771), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (769, 771), True, 'import matplotlib.pyplot as plt\n'), ((1338, 1348), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1346, 1348), True, 'import matplotlib.pyplot as plt\n'), ((885, 906), 'numpy.array', 'np.array', (['heat[:6561]'], {}), '(he... |
import uuid
from django.db import models
from django.contrib.auth import get_user_model
class Location(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False,
)
latitude = models.FloatField()
longitude = models.FloatField()
address = mode... | [
"django.contrib.auth.get_user_model",
"django.db.models.FloatField",
"django.db.models.ForeignKey",
"django.db.models.CharField",
"django.db.models.DateTimeField",
"django.db.models.UUIDField"
] | [((129, 199), 'django.db.models.UUIDField', 'models.UUIDField', ([], {'primary_key': '(True)', 'default': 'uuid.uuid4', 'editable': '(False)'}), '(primary_key=True, default=uuid.uuid4, editable=False)\n', (145, 199), False, 'from django.db import models\n'), ((246, 265), 'django.db.models.FloatField', 'models.FloatFiel... |
from django.urls import path
from . import views
from django.conf.urls import url
urlpatterns = [
url(r'^$', views.home, name='home'),
path('', views.index, name='index'),
path('compute/', views.ocr_view, name='ocr'),
url('uploads/form/$', views.model_form_upload, name='model_form_upload'),
]
| [
"django.conf.urls.url",
"django.urls.path"
] | [((103, 137), 'django.conf.urls.url', 'url', (['"""^$"""', 'views.home'], {'name': '"""home"""'}), "('^$', views.home, name='home')\n", (106, 137), False, 'from django.conf.urls import url\n'), ((144, 179), 'django.urls.path', 'path', (['""""""', 'views.index'], {'name': '"""index"""'}), "('', views.index, name='index'... |
import itertools
from aoc_cqkh42.year_2019.computer import Computer
def find_best_config(possible_configs, intcode):
results = []
for configs in possible_configs:
input_ = 0
for config in configs:
amp = Computer(intcode, [config, input_])
amp.run()
input_ =... | [
"itertools.cycle",
"itertools.permutations",
"aoc_cqkh42.year_2019.computer.Computer"
] | [((1606, 1636), 'itertools.permutations', 'itertools.permutations', (['range_'], {}), '(range_)\n', (1628, 1636), False, 'import itertools\n'), ((242, 277), 'aoc_cqkh42.year_2019.computer.Computer', 'Computer', (['intcode', '[config, input_]'], {}), '(intcode, [config, input_])\n', (250, 277), False, 'from aoc_cqkh42.y... |
import os
import subprocess
from typing import List
from uuid import uuid4
from .IngestorInterface import IngestorInterface
from .QuoteModel import QuoteModel
class PDFIngestor(IngestorInterface):
""" Process PDF files """
allowed_extensions = ['pdf']
@classmethod
def parse(cls, path: str) ... | [
"uuid.uuid4",
"subprocess.call",
"os.remove"
] | [((717, 758), 'subprocess.call', 'subprocess.call', (["['pdftotext', path, tmp]"], {}), "(['pdftotext', path, tmp])\n", (732, 758), False, 'import subprocess\n'), ((1197, 1211), 'os.remove', 'os.remove', (['tmp'], {}), '(tmp)\n', (1206, 1211), False, 'import os\n'), ((679, 686), 'uuid.uuid4', 'uuid4', ([], {}), '()\n',... |
#!/bin/false
# Copyright (c) 2022 <NAME>. 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 conditions and th... | [
"sys.path.insert",
"datalidator.blueprints.impl.BooleanBlueprint.BooleanBlueprint",
"datalidator.blueprints.impl.StringBlueprint.StringBlueprint",
"datalidator.blueprints.specialimpl.JSONBlueprint.JSONBlueprint",
"theoretical_testutils.test_function_parameter_generator",
"os.path.join",
"datalidator.blu... | [((43911, 43972), 'theoretical_testutils.perform_test', 'theoretical_testutils.perform_test', (['blueprint', 'input_', 'output'], {}), '(blueprint, input_, output)\n', (43945, 43972), False, 'import theoretical_testutils\n'), ((43769, 43858), 'theoretical_testutils.test_function_parameter_generator', 'theoretical_testu... |
"""Strategic conflict detection Subscription put query tests:
- query with different time formats.
"""
import datetime
from monitoring.monitorlib.infrastructure import default_scope
from monitoring.monitorlib import scd
from monitoring.monitorlib.scd import SCOPE_SC
from monitoring.prober.infrastructure import for... | [
"datetime.datetime.utcnow",
"monitoring.prober.infrastructure.register_resource_type",
"monitoring.monitorlib.infrastructure.default_scope",
"monitoring.monitorlib.scd.make_circle",
"datetime.timedelta",
"monitoring.prober.infrastructure.for_api_versions"
] | [((408, 451), 'monitoring.prober.infrastructure.register_resource_type', 'register_resource_type', (['(219)', '"""Subscription"""'], {}), "(219, 'Subscription')\n", (430, 451), False, 'from monitoring.prober.infrastructure import for_api_versions, register_resource_type\n'), ((912, 959), 'monitoring.prober.infrastructu... |
from skimage.draw import line
import numpy as np
import cv2
import matplotlib.pyplot as plt
def get_eye_line(eye_landmarks):
l0, l1, l2, l3, l4, l5 = eye_landmarks.astype('int')
A= list(((np.array(l1) + np.array(l5))/2).astype('int'))
B= list(((np.array(l2) + np.array(l4))/2).astype('int'))
lin... | [
"matplotlib.pyplot.imshow",
"numpy.mean",
"numpy.array",
"cv2.circle",
"skimage.draw.line",
"matplotlib.pyplot.title",
"cv2.resize",
"matplotlib.pyplot.show"
] | [((2717, 2756), 'cv2.resize', 'cv2.resize', (['eye_image', '(resize, resize)'], {}), '(eye_image, (resize, resize))\n', (2727, 2756), False, 'import cv2\n'), ((721, 761), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image_gray_show'], {'cmap': '"""gray"""'}), "(image_gray_show, cmap='gray')\n", (731, 761), True, 'impor... |
# -*- coding: utf-8 -*-
import time
from sklearn import ensemble
from sklearn import linear_model
from sklearn import naive_bayes
from sklearn import neighbors
from sklearn import neural_network
from sklearn import svm
from sklearn import tree
from sklearn.metrics import f1_score
from sklearn.model_selection import Gri... | [
"sklearn.ensemble.ExtraTreesClassifier",
"time.clock",
"sklearn.ensemble.AdaBoostClassifier",
"sklearn.neighbors.KNeighborsClassifier",
"sklearn.naive_bayes.BernoulliNB",
"sklearn.linear_model.SGDClassifier",
"sklearn.linear_model.RidgeClassifier",
"sklearn.ensemble.HistGradientBoostingClassifier",
... | [((3504, 3533), 'sklearn.ensemble.AdaBoostClassifier', 'ensemble.AdaBoostClassifier', ([], {}), '()\n', (3531, 3533), False, 'from sklearn import ensemble\n'), ((3554, 3582), 'sklearn.ensemble.BaggingClassifier', 'ensemble.BaggingClassifier', ([], {}), '()\n', (3580, 3582), False, 'from sklearn import ensemble\n'), ((3... |
# Created by <NAME>, <NAME>, <NAME> on 2019/10/4.
# Copyright © 2019 <NAME>, <NAME>, <NAME> . All rights reserved.
import network
# import socket
import urequests
import json
# ESP8266 connects to a router
def ConnectWIFI(essid, key):
import network
sta_if = network.WLAN(network.STA_IF) # config a station object
... | [
"urequests.post",
"network.WLAN"
] | [((264, 292), 'network.WLAN', 'network.WLAN', (['network.STA_IF'], {}), '(network.STA_IF)\n', (276, 292), False, 'import network\n'), ((1052, 1071), 'urequests.post', 'urequests.post', (['url'], {}), '(url)\n', (1066, 1071), False, 'import urequests\n')] |
import loja_funcoes_auxiliares as aux
def adicionar_produto_carrinho(estoque, carrinho):
"""
Adiciona um produto do estoque ao carrinho (se nao estiver adicionado ainda)
:param estoque: lista com o estoque mais atualizado
:param carrinho: lista com carrinho de compras mais atualizado
:retu... | [
"loja_adm.recupera_estoque",
"loja_funcoes_auxiliares.confirmacao",
"loja_funcoes_auxiliares.separar_comandos_print",
"loja_funcoes_auxiliares.atualiza_arquivo",
"loja_funcoes_auxiliares.checa_vazio",
"loja_funcoes_auxiliares.ver_estoque_ou_carrinho",
"loja_funcoes_auxiliares.valida_produto"
] | [((8204, 8265), 'loja_funcoes_auxiliares.atualiza_arquivo', 'aux.atualiza_arquivo', (['"""teste_loja_estoque.txt"""', 'estoque_teste'], {}), "('teste_loja_estoque.txt', estoque_teste)\n", (8224, 8265), True, 'import loja_funcoes_auxiliares as aux\n'), ((8281, 8320), 'loja_adm.recupera_estoque', 'recupera_estoque', (['a... |
"""Preprocessing of raw LAU2 data to bring it into normalised form."""
import geopandas as gpd
import pandas as pd
from renewablepotentialslib.shape_utils import to_multi_polygon
OUTPUT_DRIVER = "GeoJSON"
KOSOVO_MUNICIPALITIES = [f"RS{x:02d}" for x in range(1, 38)]
def merge_lau(path_to_shapes, path_to_attributes, ... | [
"pandas.DataFrame",
"geopandas.read_file"
] | [((394, 423), 'geopandas.read_file', 'gpd.read_file', (['path_to_shapes'], {}), '(path_to_shapes)\n', (407, 423), True, 'import geopandas as gpd\n'), ((501, 534), 'geopandas.read_file', 'gpd.read_file', (['path_to_attributes'], {}), '(path_to_attributes)\n', (514, 534), True, 'import geopandas as gpd\n'), ((552, 576), ... |
# Copyright 2021 Alibaba Group Holding Limited. 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 ... | [
"tensorflow.python.profiler.internal.flops_registry._binary_per_element_op_flops",
"tensorflow.python.framework.ops.OpStats",
"tensorflow.python.framework.ops._stats_registry.register",
"tensorflow.core.protobuf.config_pb2.RunOptions",
"tensorflow.python.profiler.internal.flops_registry._add_flops",
"tens... | [((2003, 2067), 'tensorflow.python.framework.graph_util.tensor_shape_from_node_def_name', 'graph_util.tensor_shape_from_node_def_name', (['graph', 'node.input[0]'], {}), '(graph, node.input[0])\n', (2045, 2067), False, 'from tensorflow.python.framework import graph_util\n'), ((2197, 2257), 'tensorflow.python.framework.... |
import json
def text_file_to_list(filename):
with open(filename, 'r') as file:
return file.read().splitlines()
def list_to_text_file(filename, string_list):
with open(filename, 'w') as text_file:
for line in string_list:
text_file.write(f'{line}\n')
def json_to_dict(filename):
... | [
"json.load",
"json.dump"
] | [((373, 388), 'json.load', 'json.load', (['file'], {}), '(file)\n', (382, 388), False, 'import json\n'), ((482, 514), 'json.dump', 'json.dump', (['dictionary', 'json_file'], {}), '(dictionary, json_file)\n', (491, 514), False, 'import json\n')] |
"""
Copyright (c) 2022 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 in writin... | [
"numpy.prod",
"torch.max",
"torch.min"
] | [((745, 770), 'numpy.prod', 'np.prod', (['ref_tensor_shape'], {}), '(ref_tensor_shape)\n', (752, 770), True, 'import numpy as np\n'), ((1178, 1203), 'numpy.prod', 'np.prod', (['ref_tensor_shape'], {}), '(ref_tensor_shape)\n', (1185, 1203), True, 'import numpy as np\n'), ((1031, 1072), 'torch.max', 'torch.max', (['tmp_m... |
from os.path import dirname, join
from setuptools import setup, find_packages, Command
with open('requirements.txt') as f:
reqs = f.read().splitlines()
'''
# Implement setupext.janitor which allows for more flexible
# and powerful cleaning. Commands include:
setup.py clean --dist
Removes directories that th... | [
"os.path.dirname",
"setuptools.find_packages"
] | [((1616, 1659), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "('tests', 'tests.*')"}), "(exclude=('tests', 'tests.*'))\n", (1629, 1659), False, 'from setuptools import setup, find_packages, Command\n'), ((1078, 1095), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (1085, 1095), False... |
from torch.nn import Sequential, Module, ConvTranspose2d
class CNN(Module):
def __init__(self):
super(CNN, self).__init__()
self.layers = Sequential(
# Conv2d(6, 32, kernel_size=5, stride=1, padding=2),
ConvTranspose2d(3, 3, kernel_size=5, stride=1, padding=2),
... | [
"torch.nn.ConvTranspose2d"
] | [((253, 310), 'torch.nn.ConvTranspose2d', 'ConvTranspose2d', (['(3)', '(3)'], {'kernel_size': '(5)', 'stride': '(1)', 'padding': '(2)'}), '(3, 3, kernel_size=5, stride=1, padding=2)\n', (268, 310), False, 'from torch.nn import Sequential, Module, ConvTranspose2d\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
surface2stations.py
Extract synthetics at given stations from a NetCDF database of surface
wavefield created by AxiSEM3D (named axisem3d_surface.nc by the solver)
and save them into a NetCDF waveform database (same as the built-in
NetCDF output axisem3d_synthetics.nc)... | [
"numpy.radians",
"obspy.geodetics.gps2dist_azimuth",
"numpy.arccos",
"numpy.tan",
"argparse.ArgumentParser",
"numpy.searchsorted",
"netCDF4.Dataset",
"os.path.isfile",
"numpy.zeros",
"numpy.arctan2",
"numpy.cos",
"numpy.sin",
"numpy.degrees",
"numpy.loadtxt",
"numpy.amax",
"numpy.arang... | [((843, 940), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'aim', 'epilog': 'notes', 'formatter_class': 'RawTextHelpFormatter'}), '(description=aim, epilog=notes, formatter_class=\n RawTextHelpFormatter)\n', (866, 940), False, 'import argparse\n'), ((8596, 8623), 'numpy.zeros', 'np.zero... |
# Generated by Django 3.1.1 on 2020-10-16 09:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('info', '0013_auto_20201009_1912'),
]
operations = [
migrations.AlterField(
model_name='player',
name='points_gained'... | [
"django.db.models.IntegerField"
] | [((340, 382), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (359, 382), False, 'from django.db import migrations, models\n')] |
#!/usr/bin/env python3
from aws_cdk import core
from stacks.codebuild_stack import CodebuildStack
# Construct full set of properties for stack
stack_props = {
'namespace': 'agha-data-validation-scripts-codepipeline',
'pipeline' : {
'artifact_bucket_name': 'agha-validation-pipeline-artifact',
... | [
"stacks.codebuild_stack.CodebuildStack",
"aws_cdk.core.App"
] | [((474, 503), 'aws_cdk.core.App', 'core.App', ([], {'context': 'stack_props'}), '(context=stack_props)\n', (482, 503), False, 'from aws_cdk import core\n'), ((511, 654), 'stacks.codebuild_stack.CodebuildStack', 'CodebuildStack', (['app', '"""CodebuildAGHAValidationBuild"""'], {'tags': '{\'stack\': stack_props[\'namespa... |
import numpy as np
from .LowResHighResDataset import LowResHighResDataset, region_geometry
class NearestNeighborData(LowResHighResDataset):
def __init__(self, dataset: LowResHighResDataset, num_models=None, model_index=None, k=16):
super(NearestNeighborData, self).__init__(
dataset.geometry_lr... | [
"numpy.ones_like",
"numpy.abs",
"numpy.reshape",
"numpy.argpartition",
"numpy.sort",
"numpy.sum",
"numpy.array",
"numpy.stack",
"numpy.concatenate",
"numpy.arange",
"numpy.random.shuffle"
] | [((1569, 1588), 'numpy.sum', 'np.sum', (['(1 - mask_hr)'], {}), '(1 - mask_hr)\n', (1575, 1588), True, 'import numpy as np\n'), ((3718, 3746), 'numpy.array', 'np.array', (['input_index_lon_lr'], {}), '(input_index_lon_lr)\n', (3726, 3746), True, 'import numpy as np\n'), ((3781, 3809), 'numpy.array', 'np.array', (['inpu... |
import os
import shutil
import tempfile
from ricecooker.classes import nodes, files, licenses
from ricecooker.utils.zip import create_predictable_zip
from ricecooker.utils.browser import preview_in_browser
def make_topic_tree(license, imscp_dict):
"""Return a TopicTree node from a dict of some subset of an IMSCP... | [
"tempfile.TemporaryDirectory",
"ricecooker.classes.files.HTMLZipFile",
"ricecooker.classes.nodes.TopicNode",
"os.path.join",
"shutil.copyfile",
"ricecooker.utils.zip.create_predictable_zip",
"shutil.copy"
] | [((608, 686), 'ricecooker.classes.nodes.TopicNode', 'nodes.TopicNode', ([], {'source_id': "imscp_dict['identifier']", 'title': "imscp_dict['title']"}), "(source_id=imscp_dict['identifier'], title=imscp_dict['title'])\n", (623, 686), False, 'from ricecooker.classes import nodes, files, licenses\n'), ((1128, 1157), 'temp... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 22 00:44:51 2018
@author: hossein
"""
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau, TerminateOnNaN, CSVLogger
from keras import backend as K
from keras.models import load_model
from math import ceil
impor... | [
"keras.optimizers.Adam",
"data_generator.data_augmentation_chain_constant_input_size.DataAugmentationConstantInputSize",
"keras.callbacks.CSVLogger",
"math.ceil",
"keras_loss_function.keras_ssd_loss.SSDLoss",
"keras.callbacks.ModelCheckpoint",
"models.keras_ssd7.build_model",
"keras.callbacks.ReduceLR... | [((2689, 2706), 'keras.backend.clear_session', 'K.clear_session', ([], {}), '()\n', (2704, 2706), True, 'from keras import backend as K\n'), ((2717, 3160), 'models.keras_ssd7.build_model', 'build_model', ([], {'image_size': '(img_height, img_width, img_channels)', 'n_classes': 'n_classes', 'mode': '"""training"""', 'l2... |
from compas_ui.session import Session
s = Session(name='test')
s['test'] = {}
s.record()
s['test']['a'] = 1
s.record()
s['test']['b'] = 2
s.record()
s.undo()
# s.undo()
# s.undo()
# s.record()
s.save()
| [
"compas_ui.session.Session"
] | [((43, 63), 'compas_ui.session.Session', 'Session', ([], {'name': '"""test"""'}), "(name='test')\n", (50, 63), False, 'from compas_ui.session import Session\n')] |
""" sample usage on db_util.py
Unimelb vpn required to run the code
Couchdb UI can be accessed through: http://172.26.130.149:5984/_utils/
username/password: admin/admin1<PASSWORD>
to access the CouchDB instance, download couchDB.pem from Slack and run:
ssh -i couchDB.pem ubuntu@172.26.130.149
"""
from couchDB impor... | [
"json.loads",
"couchDB.db_util.cdb"
] | [((519, 541), 'couchDB.db_util.cdb', 'db_util.cdb', (['serverURL'], {}), '(serverURL)\n', (530, 541), False, 'from couchDB import db_util\n'), ((741, 773), 'couchDB.db_util.cdb', 'db_util.cdb', (['serverURL', '"""sample"""'], {}), "(serverURL, 'sample')\n", (752, 773), False, 'from couchDB import db_util\n'), ((879, 98... |
import RPi.GPIO as GPIO
import time
import utils
GPIO.setmode(GPIO.BOARD)
last = utils.Load()
while(1):
try:
last.store(1)
except:
pass
try:
last.store(2)
except:
pass
#pwr = utils.PSU(13, 15)
#pwr.on()
#pwr.off()
GPIO.cleanup()
| [
"RPi.GPIO.cleanup",
"utils.Load",
"RPi.GPIO.setmode"
] | [((50, 74), 'RPi.GPIO.setmode', 'GPIO.setmode', (['GPIO.BOARD'], {}), '(GPIO.BOARD)\n', (62, 74), True, 'import RPi.GPIO as GPIO\n'), ((83, 95), 'utils.Load', 'utils.Load', ([], {}), '()\n', (93, 95), False, 'import utils\n'), ((269, 283), 'RPi.GPIO.cleanup', 'GPIO.cleanup', ([], {}), '()\n', (281, 283), True, 'import ... |
import unittest
import logging
import sys
import numpy
from intervals.number import Interval as I
from intervals.methods import (intervalise,lo,hi)
from .interval_generator import pick_endpoints_at_random_uniform
class TestIntervalArithmetic(unittest.TestCase):
def test_addition_by_endpoints_analysis(self):
... | [
"intervals.methods.lo",
"numpy.random.rand",
"intervals.methods.hi",
"unittest.main",
"intervals.number.Interval"
] | [((10586, 10601), 'unittest.main', 'unittest.main', ([], {}), '()\n', (10599, 10601), False, 'import unittest\n'), ((10194, 10213), 'numpy.random.rand', 'numpy.random.rand', ([], {}), '()\n', (10211, 10213), False, 'import numpy\n'), ((10226, 10230), 'intervals.number.Interval', 'I', (['a'], {}), '(a)\n', (10227, 10230... |
# MNIST image and label reader & dataset provider for tensorflow networks
# <NAME>
# <EMAIL>
import numpy as np
import struct
from PIL import Image
# read MNIST dataset - image
def read_image(filename):
raw = open(filename, 'rb')
magic_num = struct.unpack("i", raw.read(4)[::-1])[0]
if magic_nu... | [
"numpy.argmax",
"numpy.zeros",
"numpy.unique",
"PIL.Image.fromarray"
] | [((594, 633), 'numpy.zeros', 'np.zeros', (['[item_num, row_num * col_num]'], {}), '([item_num, row_num * col_num])\n', (602, 633), True, 'import numpy as np\n'), ((1147, 1171), 'numpy.zeros', 'np.zeros', (['[item_num, 10]'], {}), '([item_num, 10])\n', (1155, 1171), True, 'import numpy as np\n'), ((1403, 1420), 'numpy.u... |
import math
from misc.callback import callback
# Drawing parameters
class ManiaSettings():
viewable_time_interval = 1000 # ms
note_width = 50 # osu!px
note_height = 15 # osu!px
note_seperation = 5 # osu!px
replay_opacity = 50 # %
@stat... | [
"math.log2",
"math.floor"
] | [((3408, 3433), 'math.floor', 'math.floor', (['(ratio * x_pos)'], {}), '(ratio * x_pos)\n', (3418, 3433), False, 'import math\n'), ((3888, 3902), 'math.log2', 'math.log2', (['bit'], {}), '(bit)\n', (3897, 3902), False, 'import math\n')] |
#!/usr/bin/env python3
# @generated AUTOGENERATED file. Do not Change!
from dataclasses import dataclass, field as _field
from functools import partial
from ...config import custom_scalars, datetime
from numbers import Number
from typing import Any, AsyncGenerator, Dict, List, Generator, Optional
from dataclasses_jso... | [
"dataclasses.dataclass"
] | [((618, 640), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (627, 640), False, 'from dataclasses import dataclass, field as _field\n')] |
import os
import sys
from difflib import SequenceMatcher
from pyproj import Proj, transform
import numpy as np
import pandas as pd
def similar(a, b):
return SequenceMatcher(None, a, b).ratio()
def extract_loc(t_array, gps_data):
_xy = gps_data[[0, -1]]
pct = ((t_array * 1.0) / np.max(t_array))[:, np.new... | [
"numpy.radians",
"numpy.unique",
"pandas.read_csv",
"numpy.sin",
"difflib.SequenceMatcher",
"os.path.join",
"pyproj.transform",
"numpy.argmax",
"numpy.max",
"numpy.dot",
"numpy.cos",
"pyproj.Proj",
"numpy.linalg.norm",
"pandas.DataFrame",
"pandas.concat"
] | [((509, 531), 'pyproj.Proj', 'Proj', ([], {'init': '"""epsg:4326"""'}), "(init='epsg:4326')\n", (513, 531), False, 'from pyproj import Proj, transform\n'), ((545, 568), 'pyproj.Proj', 'Proj', ([], {'init': '"""epsg:26911"""'}), "(init='epsg:26911')\n", (549, 568), False, 'from pyproj import Proj, transform\n'), ((578, ... |
import torch.nn.functional as F
import torch.nn as nn
import torch.optim as optim
import torch
import unittest
from label_set_loss_functions.loss import MarginalizedFocalLoss
class TestMarginalizedFocalLoss(unittest.TestCase):
def test_partial_seg_2d(self):
num_classes = 3 # labels 0 to 2
labels_... | [
"torch.unsqueeze",
"torch.tensor",
"torch.nn.functional.one_hot",
"torch.nn.Linear",
"label_set_loss_functions.loss.MarginalizedFocalLoss"
] | [((442, 512), 'torch.tensor', 'torch.tensor', (['[[0, 0, 0, 0], [0, 1, 2, 0], [0, 3, 4, 0], [0, 0, 0, 0]]'], {}), '([[0, 0, 0, 0], [0, 1, 2, 0], [0, 3, 4, 0], [0, 0, 0, 0]])\n', (454, 512), False, 'import torch\n'), ((942, 1004), 'label_set_loss_functions.loss.MarginalizedFocalLoss', 'MarginalizedFocalLoss', ([], {'lab... |
import torch
from torch import nn as nn
from typing import Any
from collections import OrderedDict
import pandas as pd
class Trader(nn.Module):
def __init__(self, days, state_size=7):
super(Trader, self).__init__()
self.days = days
self.state_size = state_size
self.buyer = self._c... | [
"torch.nn.Sigmoid",
"collections.OrderedDict",
"torch.nn.Dropout",
"torch.nn.BatchNorm2d",
"torch.nn.CrossEntropyLoss",
"torch.nn.LeakyReLU",
"torch.mean",
"torch.nn.Sequential",
"torch.nn.Conv2d",
"torch.t",
"torch.nn.init.normal_",
"torch.nn.MSELoss",
"torch.nn.MaxPool2d",
"torch.nn.Line... | [((2224, 2250), 'torch.squeeze', 'torch.squeeze', (['diff'], {'dim': '(0)'}), '(diff, dim=0)\n', (2237, 2250), False, 'import torch\n'), ((2381, 2411), 'torch.mean', 'torch.mean', (['square'], {'dim': '(2, 3)'}), '(square, dim=(2, 3))\n', (2391, 2411), False, 'import torch\n'), ((4583, 4596), 'collections.OrderedDict',... |
import json
import boto3
import os
s3Client = boto3.client('s3')
BUCKET = os.environ['BUCKET_NAME']
def handler(event, context):
try:
data = open('package.json', 'rb')
s3Client.put_object(
Bucket=BUCKET,
Body=data,
Key="package.json"
)
body = {... | [
"json.dumps",
"boto3.client"
] | [((47, 65), 'boto3.client', 'boto3.client', (['"""s3"""'], {}), "('s3')\n", (59, 65), False, 'import boto3\n'), ((453, 469), 'json.dumps', 'json.dumps', (['body'], {}), '(body)\n', (463, 469), False, 'import json\n')] |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import os
path_to_packages = os.path.abspath(os.path.join("venv/lib/site-packages"))
sys.path.insert(0, path_to_packages)
from flask import Flask, render_template, jsonify, request
from flask_wtf import FlaskForm
from flask_pagedown import PageDown
from flask_paged... | [
"flask_pagedown.PageDown",
"flask.render_template",
"sys.path.insert",
"flask.Flask",
"onmt.translate.TranslationServer",
"os.path.join",
"flask.request.form.get",
"flask_pagedown.fields.PageDownField",
"re.sub",
"wtforms.fields.SubmitField"
] | [((139, 175), 'sys.path.insert', 'sys.path.insert', (['(0)', 'path_to_packages'], {}), '(0, path_to_packages)\n', (154, 175), False, 'import sys\n'), ((632, 647), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (637, 647), False, 'from flask import Flask, jsonify, request\n'), ((696, 709), 'flask_pagedown.P... |
import sys
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils.modules.vggNet import VGGFeatureExtractor
class TVLoss(nn.Module):
def __init__(self, weight=1.0):
super(TVLoss, self).__init__()
self.weight = weight
self.l1 = nn.L1Loss... | [
"torch.nn.ReLU",
"torch.nn.L1Loss",
"torch.sqrt",
"torch.min",
"torch.nn.MSELoss",
"torch.sum",
"torch.nn.functional.interpolate",
"torch.bmm",
"torch.gather",
"torch.nn.L2loss",
"torch.abs",
"torch.transpose",
"torch.nn.functional.softplus",
"torch.norm",
"torch.nn.BCEWithLogitsLoss",
... | [((311, 338), 'torch.nn.L1Loss', 'nn.L1Loss', ([], {'reduction': '"""mean"""'}), "(reduction='mean')\n", (320, 338), True, 'import torch.nn as nn\n'), ((1074, 1108), 'torch.sqrt', 'torch.sqrt', (['(diff * diff + self.eps)'], {}), '(diff * diff + self.eps)\n', (1084, 1108), False, 'import torch\n'), ((2712, 2742), 'torc... |
import sys
from os.path import dirname, realpath
sys.path.append(realpath(dirname(__file__)))
from gimpfu import main
from _plugin_base import GimpPluginBase
class MonoDepth(GimpPluginBase):
def run(self):
self.model_file = 'Monodepth2.py'
result = self.predict(self.drawable)
self.create_... | [
"os.path.dirname",
"gimpfu.main"
] | [((599, 605), 'gimpfu.main', 'main', ([], {}), '()\n', (603, 605), False, 'from gimpfu import main\n'), ((75, 92), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (82, 92), False, 'from os.path import dirname, realpath\n')] |
import numpy as np
from scipy.stats import truncnorm, norm
def soft_threshold(r, gamma):
"""
soft-thresholding function
"""
return np.maximum(np.abs(r) - gamma, 0.0) * np.sign(r)
def df(r, gamma):
"""
divergence-free function
"""
eta = soft_threshold(r, gamma)
ret... | [
"numpy.mean",
"numpy.histogram",
"numpy.abs",
"numpy.random.rand",
"numpy.where",
"numpy.logical_not",
"numpy.argmax",
"numpy.square",
"numpy.append",
"numpy.sum",
"numpy.zeros",
"numpy.empty",
"numpy.sign",
"scipy.stats.norm.pdf",
"scipy.stats.truncnorm.rvs"
] | [((495, 514), 'numpy.zeros', 'np.zeros', (['(P, N, 1)'], {}), '((P, N, 1))\n', (503, 514), True, 'import numpy as np\n'), ((524, 540), 'numpy.zeros', 'np.zeros', (['(N, 1)'], {}), '((N, 1))\n', (532, 540), True, 'import numpy as np\n'), ((835, 852), 'numpy.sum', 'np.sum', (['R'], {'axis': '(0)'}), '(R, axis=0)\n', (841... |
"""This is the Solution for Year 2021 Day 05"""
import itertools
from collections import Counter
from dataclasses import dataclass
from aoc.abstracts.solver import Answers, StrLines
@dataclass(frozen=True)
class Point:
"""Immutable point that will define x and y on 2D plane"""
x: int
y: int
@dataclas... | [
"itertools.chain.from_iterable",
"aoc.abstracts.solver.Answers",
"dataclasses.dataclass"
] | [((187, 209), 'dataclasses.dataclass', 'dataclass', ([], {'frozen': '(True)'}), '(frozen=True)\n', (196, 209), False, 'from dataclasses import dataclass\n'), ((2449, 2494), 'itertools.chain.from_iterable', 'itertools.chain.from_iterable', (['segment_points'], {}), '(segment_points)\n', (2478, 2494), False, 'import iter... |
#import the csv file plumbing
import os
import csv
csvpath = os.path.join('Resources', 'budget_data.csv')
with open(csvpath, newline='') as csvfile:
# CSV reader specifies delimiter and variable that holds contents
csvreader = csv.reader(csvfile, delimiter=',')
#skips header
csv_header = next(csvrea... | [
"csv.writer",
"os.path.join",
"csv.reader"
] | [((62, 106), 'os.path.join', 'os.path.join', (['"""Resources"""', '"""budget_data.csv"""'], {}), "('Resources', 'budget_data.csv')\n", (74, 106), False, 'import os\n'), ((2087, 2120), 'os.path.join', 'os.path.join', (['"""Output"""', '"""new.csv"""'], {}), "('Output', 'new.csv')\n", (2099, 2120), False, 'import os\n'),... |
#! crding = utf8
from pandas import *
import numpy as np
import os, sys, subprocess
import netCDF4
import twd97
import datetime
from calendar import monthrange
from scipy.io import FortranFile
from ptse_sub import CORRECT, add_PMS, check_nan, check_landsea, FillNan, WGS_TWD, Elev_YPM
#Main
P=subprocess.check_output(... | [
"subprocess.check_output",
"ptse_sub.check_nan",
"ptse_sub.check_landsea",
"scipy.io.FortranFile",
"numpy.array",
"numpy.zeros",
"ptse_sub.Elev_YPM",
"ptse_sub.WGS_TWD",
"sys.exit"
] | [((676, 689), 'ptse_sub.check_nan', 'check_nan', (['df'], {}), '(df)\n', (685, 689), False, 'from ptse_sub import CORRECT, add_PMS, check_nan, check_landsea, FillNan, WGS_TWD, Elev_YPM\n'), ((754, 771), 'ptse_sub.check_landsea', 'check_landsea', (['df'], {}), '(df)\n', (767, 771), False, 'from ptse_sub import CORRECT, ... |
import os
from Crypto.Cipher import PKCS1_v1_5 as Cipher
from Crypto.Signature import PKCS1_v1_5 as Signature
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto import Random
from data_marketplace.utils.common import to_byte
from data_marketplace.utils.log import logging
log = logging.getLogger('... | [
"data_marketplace.utils.common.to_byte",
"Crypto.Random.new",
"Crypto.Cipher.PKCS1_v1_5.new",
"os.path.join",
"Crypto.PublicKey.RSA.generate",
"data_marketplace.utils.log.logging.getLogger",
"Crypto.Signature.PKCS1_v1_5.new",
"Crypto.PublicKey.RSA.importKey"
] | [((301, 349), 'data_marketplace.utils.log.logging.getLogger', 'logging.getLogger', (['"""data_marketplace.crypto.rsa"""'], {}), "('data_marketplace.crypto.rsa')\n", (318, 349), False, 'from data_marketplace.utils.log import logging\n'), ((386, 398), 'data_marketplace.utils.common.to_byte', 'to_byte', (['msg'], {}), '(m... |
from __future__ import absolute_import, unicode_literals
import hmac
import hashlib
import json
import logging
import os
import stat
import sys
logger = logging.getLogger(__name__)
def partition(cond, seq, parts=2):
"""
Partition function from <NAME> on Ned's blog at
http://nedbatchelder.com/blog/20060... | [
"logging.getLogger",
"json.dumps",
"hmac.new"
] | [((156, 183), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (173, 183), False, 'import logging\n'), ((1298, 1353), 'json.dumps', 'json.dumps', (['data'], {'sort_keys': '(True)', 'separators': "(',', ':')"}), "(data, sort_keys=True, separators=(',', ':'))\n", (1308, 1353), False, 'import ... |
import tensorflow as tf
import numpy as np
PROJ_EPS = 1e-5
EPS = 1e-15
MAX_TANH_ARG = 15.0
# Real x, not vector!
def tf_atanh(x):
return tf.atanh(tf.minimum(x, 1. - EPS)) # Only works for positive real x.
# Real x, not vector!
def tf_tanh(x):
return tf.tanh(tf.minimum(tf.maximum(x, -MAX_TANH_ARG), MAX_TA... | [
"tensorflow.reduce_sum",
"tensorflow.maximum",
"tensorflow.minimum",
"tensorflow.norm"
] | [((360, 403), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['(x * y)'], {'axis': '(1)', 'keepdims': '(True)'}), '(x * y, axis=1, keepdims=True)\n', (373, 403), True, 'import tensorflow as tf\n'), ((433, 474), 'tensorflow.norm', 'tf.norm', (['x'], {'ord': '(2)', 'axis': '(-1)', 'keepdims': '(True)'}), '(x, ord=2, axis=-1,... |
import time
import requests
from pysmashgg.exceptions import *
# Runs queries
def run_query(query, variables, header, auto_retry):
# This helper function is necessary for TooManyRequestsErrors
def _run_query(query, variables, header, auto_retry, seconds):
json_request = {'query': query, 'variables': v... | [
"requests.post",
"time.sleep"
] | [((365, 455), 'requests.post', 'requests.post', ([], {'url': '"""https://api.smash.gg/gql/alpha"""', 'json': 'json_request', 'headers': 'header'}), "(url='https://api.smash.gg/gql/alpha', json=json_request,\n headers=header)\n", (378, 455), False, 'import requests\n'), ((1266, 1285), 'time.sleep', 'time.sleep', (['s... |
from ctypes import POINTER, c_char_p, byref
from ...ffi import utils
from ...ffi.ontology.facades import CTtsFacade
from ...ffi.utils import hermes_protocol_handler_tts_facade, hermes_drop_tts_facade
class TtsFFI(object):
def __init__(self, use_json_api=True):
self.use_json_api = use_json_api
sel... | [
"ctypes.byref",
"ctypes.POINTER"
] | [((332, 351), 'ctypes.POINTER', 'POINTER', (['CTtsFacade'], {}), '(CTtsFacade)\n', (339, 351), False, 'from ctypes import POINTER, c_char_p, byref\n'), ((467, 486), 'ctypes.byref', 'byref', (['self._facade'], {}), '(self._facade)\n', (472, 486), False, 'from ctypes import POINTER, c_char_p, byref\n'), ((587, 606), 'cty... |
import time
import pymsteams
from datetime import datetime
from reporter.reporter import generate_report
from services.billing_service import BillingService
from services.folders_service import FoldersService
from services.projects_service import ProjectsService
from config import dry_run
from config import credenti... | [
"services.folders_service.FoldersService",
"services.projects_service.ProjectsService",
"services.billing_service.BillingService",
"time.sleep",
"datetime.datetime.now",
"pymsteams.connectorcard"
] | [((508, 544), 'services.billing_service.BillingService', 'BillingService', (['credentials', 'dry_run'], {}), '(credentials, dry_run)\n', (522, 544), False, 'from services.billing_service import BillingService\n'), ((563, 599), 'services.folders_service.FoldersService', 'FoldersService', (['credentials', 'dry_run'], {})... |
#
# (c) 2021 <NAME>
#
__author__ = '<NAME>'
__date__ = '2021/09'
import time
import click
from cuilib import Cui
from . import __prog_name__, __version__
from . import NeoPixel
from . import robot_eye
from . import get_logger
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.group(invoke_without_c... | [
"click.argument",
"click.group",
"click.option",
"time.sleep",
"cuilib.Cui",
"click.version_option"
] | [((292, 423), 'click.group', 'click.group', ([], {'invoke_without_command': '(True)', 'context_settings': 'CONTEXT_SETTINGS', 'help': '("""\nytani-neopixel: version """ + __version__)'}), '(invoke_without_command=True, context_settings=CONTEXT_SETTINGS,\n help="""\nytani-neopixel: version """ + __version__)\n', (303... |
import django
from django.contrib import admin
from django import forms
from django.urls import path
from django.utils import timezone
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from form_designer.admin import FormAdmin as FormAdminBase
from form_designer.admin import ... | [
"django.utils.text.slugify",
"django.utils.translation.ugettext_lazy",
"xlsxdocument.XLSXDocument",
"django.utils.timezone.now",
"django.contrib.admin.register",
"django.contrib.admin.site.unregister"
] | [((658, 685), 'django.contrib.admin.site.unregister', 'admin.site.unregister', (['Form'], {}), '(Form)\n', (679, 685), False, 'from django.contrib import admin\n'), ((686, 723), 'django.contrib.admin.site.unregister', 'admin.site.unregister', (['FormSubmission'], {}), '(FormSubmission)\n', (707, 723), False, 'from djan... |
from click.testing import CliRunner
from modelindex.commands.cli import cli
def test_cli_invocation():
runner = CliRunner()
result = runner.invoke(cli)
assert result.exit_code == 0
def test_cli_check_ok():
runner = CliRunner()
result = runner.invoke(cli, ["check", "tests/test-mi/11_markdown/rexn... | [
"click.testing.CliRunner"
] | [((118, 129), 'click.testing.CliRunner', 'CliRunner', ([], {}), '()\n', (127, 129), False, 'from click.testing import CliRunner\n'), ((235, 246), 'click.testing.CliRunner', 'CliRunner', ([], {}), '()\n', (244, 246), False, 'from click.testing import CliRunner\n'), ((482, 493), 'click.testing.CliRunner', 'CliRunner', ([... |
import torch
import torch.nn as nn
from models.utils import parse_model_params, get_params_str
from models.utils import sample_gauss, nll_gauss
class RNN_GAUSS(nn.Module):
"""RNN with Gaussian output distribution."""
def __init__(self, params, parser=None):
super().__init__()
self.model_arg... | [
"torch.nn.Softplus",
"torch.nn.ReLU",
"models.utils.sample_gauss",
"models.utils.nll_gauss",
"torch.nn.Linear",
"models.utils.get_params_str",
"models.utils.parse_model_params",
"torch.cat",
"torch.nn.GRU"
] | [((397, 448), 'models.utils.parse_model_params', 'parse_model_params', (['self.model_args', 'params', 'parser'], {}), '(self.model_args, params, parser)\n', (415, 448), False, 'from models.utils import parse_model_params, get_params_str\n'), ((475, 514), 'models.utils.get_params_str', 'get_params_str', (['self.model_ar... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import shutil
import unittest
from antlir.fs_utils import temp_dir
from ..gpg_keys import snapshot_gpg_ke... | [
"antlir.fs_utils.temp_dir",
"os.mkdir",
"shutil.copy"
] | [((426, 436), 'antlir.fs_utils.temp_dir', 'temp_dir', ([], {}), '()\n', (434, 436), False, 'from antlir.fs_utils import temp_dir\n'), ((626, 649), 'os.mkdir', 'os.mkdir', (['allowlist_dir'], {}), '(allowlist_dir)\n', (634, 649), False, 'import os\n'), ((1330, 1368), 'shutil.copy', 'shutil.copy', (['hello_path', 'allowl... |
#!/usr/bin/env python
#-----------------------------------------------------------------------------
# qwiic_as6212.py
#
# Python module for the AS6212 Digital Temperature Sensor Qwiic
#
#------------------------------------------------------------------------
#
# Written by <NAME>, SparkFun Electronics, Aug 2021
#
#... | [
"qwiic_i2c.getI2CDriver",
"qwiic_i2c.isDeviceConnected"
] | [((6477, 6518), 'qwiic_i2c.isDeviceConnected', 'qwiic_i2c.isDeviceConnected', (['self.address'], {}), '(self.address)\n', (6504, 6518), False, 'import qwiic_i2c\n'), ((5900, 5924), 'qwiic_i2c.getI2CDriver', 'qwiic_i2c.getI2CDriver', ([], {}), '()\n', (5922, 5924), False, 'import qwiic_i2c\n')] |
import unittest
from parameterized import parameterized
import logging
from lab1.src.onedim.one_dim_search import (
dichotomy_method,
golden_section_method,
fibonacci_method
)
DELTA = 1e-6
TEST_CASES = [
(lambda x: x + 1, -3, 4, -3),
(lambda x: -x - 1, -50, 10, 10),
(lambda x: x ** 2, -4, 6, ... | [
"logging.basicConfig",
"lab1.src.onedim.one_dim_search.fibonacci_method",
"parameterized.parameterized.expand",
"lab1.src.onedim.one_dim_search.dichotomy_method",
"unittest.main",
"lab1.src.onedim.one_dim_search.golden_section_method"
] | [((962, 994), 'parameterized.parameterized.expand', 'parameterized.expand', (['TEST_CASES'], {}), '(TEST_CASES)\n', (982, 994), False, 'from parameterized import parameterized\n'), ((1194, 1226), 'parameterized.parameterized.expand', 'parameterized.expand', (['TEST_CASES'], {}), '(TEST_CASES)\n', (1214, 1226), False, '... |
#!/usr/bin/env python3
from functools import lru_cache
from typing import NamedTuple
from datetime import datetime
import pytz
from my.config.repos.goodrexport import dal as goodrexport
from my.config import goodreads as config
def get_model():
sources = list(sorted(config.export_dir.glob('*.xml')))
model = ... | [
"my.config.goodreads.export_dir.glob",
"pytz.timezone",
"datetime.datetime.fromtimestamp",
"my.config.repos.goodrexport.dal.DAL"
] | [((320, 344), 'my.config.repos.goodrexport.dal.DAL', 'goodrexport.DAL', (['sources'], {}), '(sources)\n', (335, 344), True, 'from my.config.repos.goodrexport import dal as goodrexport\n'), ((1184, 1214), 'pytz.timezone', 'pytz.timezone', (['"""Europe/London"""'], {}), "('Europe/London')\n", (1197, 1214), False, 'import... |
import random
import time
import threading
from ycore.module.module import *
from ycore.module.listener import *
from ycore.event.event import Events
# Refactor..
class AnagramsModule(Module):
def __init__(self, chats, betpercent, betamount, wordlist, queue, owner):
super().__init__()
... | [
"threading.Timer",
"random.random",
"random.randint",
"time.clock"
] | [((3441, 3480), 'threading.Timer', 'threading.Timer', (['timeout', 'self.nextWord'], {}), '(timeout, self.nextWord)\n', (3456, 3480), False, 'import threading\n'), ((3534, 3546), 'time.clock', 'time.clock', ([], {}), '()\n', (3544, 3546), False, 'import time\n'), ((4866, 4905), 'threading.Timer', 'threading.Timer', (['... |
# 2021 June 9 12:42 - surrendered
# Important Notes:
# 1) char existence representation in 26 bits.
# 2) how bit-wise-and not zero indicates common letters.
# The idea involved here is to represent the existence of a char in a word
# as a bit in an integer, of which the rightmost 26 bits corresponds to the
# 26 lower... | [
"collections.defaultdict"
] | [((757, 773), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (768, 773), False, 'from collections import defaultdict\n')] |
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2021 Beartype authors.
# See "LICENSE" for further details.
'''
**Beartype decorator PEP-compliant type-checking code generator.**
This private submodule dynamically generates pure-Python code t... | [
"beartype._util.func.utilfuncscope.add_func_scope_attr",
"beartype._util.hint.pep.proposal.utilhintpep585.is_hint_pep585_builtin",
"beartype._util.hint.pep.proposal.utilhintpep544.get_hint_pep544_io_protocol_from_generic",
"beartype._util.hint.utilhintget.get_hint_forwardref_classname",
"beartype._util.hint... | [((26212, 26240), 'beartype._util.cache.pool.utilcachepoollistfixed.acquire_fixed_list', 'acquire_fixed_list', (['SIZE_BIG'], {}), '(SIZE_BIG)\n', (26230, 26240), False, 'from beartype._util.cache.pool.utilcachepoollistfixed import SIZE_BIG, acquire_fixed_list, release_fixed_list\n'), ((110380, 110410), 'beartype._util... |
from setuptools import setup, find_packages
import os
import codecs
HERE = os.path.abspath(os.path.dirname(__file__))
def read(*parts):
"""
Build an absolute path from *parts* and and return the contents of the
resulting file. Assume UTF-8 encoding.
"""
with codecs.open(os.path.join(HERE, *parts... | [
"os.path.dirname",
"setuptools.find_packages",
"os.path.join"
] | [((92, 117), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (107, 117), False, 'import os\n'), ((440, 455), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (453, 455), False, 'from setuptools import setup, find_packages\n'), ((295, 321), 'os.path.join', 'os.path.join', (['HERE'... |
import panel as pn
import param
import pandas as pd
import numpy as np
import holoviews as hv
from holoviews import streams
from holoviews import opts, dim
hv.extension('bokeh')
pn.extension()
class FlagChecker(param.Parameterized):
flag = param.ObjectSelector(default="UNCHECKED", objects=[
... | [
"panel.Row",
"holoviews.Points",
"param.ObjectSelector",
"panel.widgets.Button",
"holoviews.extension",
"param.Integer",
"panel.extension",
"holoviews.DynamicMap",
"holoviews.Curve",
"holoviews.streams.Selection1D",
"holoviews.dim",
"param.depends"
] | [((156, 177), 'holoviews.extension', 'hv.extension', (['"""bokeh"""'], {}), "('bokeh')\n", (168, 177), True, 'import holoviews as hv\n'), ((178, 192), 'panel.extension', 'pn.extension', ([], {}), '()\n', (190, 192), True, 'import panel as pn\n'), ((246, 332), 'param.ObjectSelector', 'param.ObjectSelector', ([], {'defau... |
from saltobserver import app, stream
from flask_sockets import Sockets
import gevent
from geventwebsocket.websocket import WebSocketError
sockets = Sockets(app)
@sockets.route('/subscribe')
def subscribe(ws):
"""WebSocket endpoint, used for liveupdates"""
while ws is not None:
gevent.sleep(0.1)
... | [
"flask_sockets.Sockets",
"saltobserver.stream.register",
"gevent.sleep"
] | [((150, 162), 'flask_sockets.Sockets', 'Sockets', (['app'], {}), '(app)\n', (157, 162), False, 'from flask_sockets import Sockets\n'), ((298, 315), 'gevent.sleep', 'gevent.sleep', (['(0.1)'], {}), '(0.1)\n', (310, 315), False, 'import gevent\n'), ((444, 472), 'saltobserver.stream.register', 'stream.register', (['ws', '... |
from .mysql_utils import MysqlApiFunctions as MAF
from greww.utils.decorators import ClassDecorator #, ArgsBooster
_databases = ""
@ClassDecorator(decorator=staticmethod)
class _MysqlPen(object):
"""
This pen have a big d, can write everywhere.
Errors raises if mysql raises one
"""
__slots__ = [me... | [
"greww.utils.decorators.ClassDecorator"
] | [((134, 172), 'greww.utils.decorators.ClassDecorator', 'ClassDecorator', ([], {'decorator': 'staticmethod'}), '(decorator=staticmethod)\n', (148, 172), False, 'from greww.utils.decorators import ClassDecorator\n')] |
# coding: utf-8
from django.conf import settings
from django.conf.urls import patterns, url, include
from django.contrib.contenttypes.models import ContentType
from tastypie.resources import ModelResource
from tastypie.serializers import Serializer
from tastypie.utils import trailing_slash
from tastypie import fields... | [
"requests.post",
"django.contrib.contenttypes.models.ContentType.objects.get_for_model",
"tastypie.serializers.Serializer",
"main.models.ResourceThematic.objects.filter",
"main.models.Descriptor.objects.filter",
"multimedia.models.Media.objects.filter",
"tastypie.utils.trailing_slash"
] | [((516, 546), 'multimedia.models.Media.objects.filter', 'Media.objects.filter', ([], {'status': '(1)'}), '(status=1)\n', (536, 546), False, 'from multimedia.models import Media\n'), ((602, 637), 'tastypie.serializers.Serializer', 'Serializer', ([], {'formats': "['json', 'xml']"}), "(formats=['json', 'xml'])\n", (612, 6... |
import numpy as np
from numpy.linalg import inv
class GeoArray(np.ndarray):
def __new__(cls, input_array, crs=4326, mat=None):
obj = np.asarray(input_array).view(cls)
obj.crs, obj.mat = crs, mat.reshape((2,3))
return obj
def __array_finalize__(self, obj):
if obj is None: re... | [
"numpy.ones",
"numpy.hstack",
"numpy.asarray",
"numpy.array",
"numpy.zeros",
"numpy.linalg.inv",
"numpy.dot",
"numpy.vstack"
] | [((2436, 2468), 'numpy.array', 'np.array', (['[[1, 1, 0], [1, 0, 1]]'], {}), '([[1, 1, 0], [1, 0, 1]])\n', (2444, 2468), True, 'import numpy as np\n'), ((2548, 2576), 'numpy.array', 'np.array', (['[0, 1, 0, 0, 0, 1]'], {}), '([0, 1, 0, 0, 0, 1])\n', (2556, 2576), True, 'import numpy as np\n'), ((1386, 1434), 'numpy.vst... |
# psycopg2 library is necessary
import pandas as pd
from sqlalchemy import create_engine
import os
engine = create_engine(
f"postgresql://neylsoncrepalde:{os.environ['PGPASS']}@database-ig<EMAIL>:5432/postgres"
)
df = pd.read_csv("data/pnadc20203.csv", sep=';')
df.to_sql('pnadc20203', con=engine, if_exists='repl... | [
"sqlalchemy.create_engine",
"pandas.read_csv"
] | [((109, 221), 'sqlalchemy.create_engine', 'create_engine', (['f"""postgresql://neylsoncrepalde:{os.environ[\'PGPASS\']}@database-ig<EMAIL>:5432/postgres"""'], {}), '(\n f"postgresql://neylsoncrepalde:{os.environ[\'PGPASS\']}@database-ig<EMAIL>:5432/postgres"\n )\n', (122, 221), False, 'from sqlalchemy import crea... |
from sqlalchemy import create_engine
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
)
from typing import Union
from .tables import (
Base,
Profile,
Guild,
Watcher,
User,
)
class DatabaseManager:
def __init__(
self,
database_url: str,
echo=False,
... | [
"sqlalchemy.orm.sessionmaker",
"sqlalchemy.create_engine",
"sqlalchemy.orm.scoped_session"
] | [((388, 426), 'sqlalchemy.create_engine', 'create_engine', (['database_url'], {'echo': 'echo'}), '(database_url, echo=echo)\n', (401, 426), False, 'from sqlalchemy import create_engine\n'), ((453, 483), 'sqlalchemy.orm.sessionmaker', 'sessionmaker', ([], {'bind': 'self.engine'}), '(bind=self.engine)\n', (465, 483), Fal... |
from collections import defaultdict
from copy import deepcopy
import logging
import math
import os
from typing import Tuple
import matplotlib.pyplot as plt
import numpy as np
from omegaconf import DictConfig, OmegaConf
import pytorch_lightning as pl
try:
from ray.tune.integration.pytorch_lightning import TuneRepor... | [
"logging.getLogger",
"deepethogram.data.augs.get_empty_gpu_transforms",
"deepethogram.callbacks.CheckpointCallback",
"ray.tune.get_trial_dir",
"deepethogram.metrics.EmptyMetrics",
"math.log2",
"torch.cuda.is_available",
"pytorch_lightning.Trainer",
"copy.deepcopy",
"deepethogram.callbacks.FPSCallb... | [((982, 1009), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (999, 1009), False, 'import logging\n'), ((15597, 15647), 'os.path.join', 'os.path.join', (['cfg.run.dir', '"""lightning_checkpoints"""'], {}), "(cfg.run.dir, 'lightning_checkpoints')\n", (15609, 15647), False, 'import os\n'), ... |
# GENERATED BY KOMAND SDK - DO NOT EDIT
import insightconnect_plugin_runtime
import json
class Component:
DESCRIPTION = "Query a routable IPv4 address in the GreyNoise Context API endpoint"
class Input:
IP_ADDRESS = "ip_address"
class Output:
ACTOR = "actor"
BOT = "bot"
CLASSIFICATION = "c... | [
"json.loads"
] | [((693, 988), 'json.loads', 'json.loads', (['"""\n {\n "type": "object",\n "title": "Variables",\n "properties": {\n "ip_address": {\n "type": "string",\n "title": "IP Address",\n "description": "Routable IPv4 address to query",\n "order": 1\n }\n },\n "required": [\n "ip_address"\n ... |
import struct
from suitcase.fields import BaseField
from suitcase.fields import BaseStructField
from suitcase.fields import BaseFixedByteSequence
class SLFloat32(BaseStructField):
"""Signed Little Endian 32-bit float field."""
PACK_FORMAT = UNPACK_FORMAT = b"<f"
def unpack(self, data, **kwargs):
... | [
"struct.unpack"
] | [((335, 374), 'struct.unpack', 'struct.unpack', (['self.UNPACK_FORMAT', 'data'], {}), '(self.UNPACK_FORMAT, data)\n', (348, 374), False, 'import struct\n')] |
"""Maigret checking logic test functions"""
import pytest
import asyncio
import logging
from maigret.executors import (
AsyncioSimpleExecutor,
AsyncioProgressbarExecutor,
AsyncioProgressbarSemaphoreExecutor,
AsyncioProgressbarQueueExecutor,
)
logger = logging.getLogger(__name__)
async def func(n):
... | [
"logging.getLogger",
"maigret.executors.AsyncioProgressbarSemaphoreExecutor",
"maigret.executors.AsyncioProgressbarExecutor",
"maigret.executors.AsyncioProgressbarQueueExecutor",
"asyncio.sleep",
"maigret.executors.AsyncioSimpleExecutor"
] | [((269, 296), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (286, 296), False, 'import logging\n'), ((499, 535), 'maigret.executors.AsyncioSimpleExecutor', 'AsyncioSimpleExecutor', ([], {'logger': 'logger'}), '(logger=logger)\n', (520, 535), False, 'from maigret.executors import AsyncioS... |
import sys
import subprocess
# use pip to install numpy:
subprocess.check_call([sys.executable, '-m', 'pip', 'install',
'numpy'])
# use pip to install matplotlib:
subprocess.check_call([sys.executable, '-m', 'pip', 'install',
'matplotlib'])
# use pip to install pandas:
... | [
"sklearn.preprocessing.LabelEncoder",
"utils.trap",
"sklearn.neural_network.MLPClassifier",
"pandas.read_csv",
"subprocess.check_call",
"sklearn.model_selection.train_test_split",
"sklearn.preprocessing.StandardScaler",
"training_data_builder.data_maker",
"matplotlib.pyplot.figure",
"matplotlib.py... | [((59, 131), 'subprocess.check_call', 'subprocess.check_call', (["[sys.executable, '-m', 'pip', 'install', 'numpy']"], {}), "([sys.executable, '-m', 'pip', 'install', 'numpy'])\n", (80, 131), False, 'import subprocess\n'), ((189, 266), 'subprocess.check_call', 'subprocess.check_call', (["[sys.executable, '-m', 'pip', '... |
from django.contrib import admin
from django import forms
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from profiles.models import FavoritesProducts, Address
from accounts.models import User
... | [
"accounts.models.User.objects.get",
"django.forms.CharField",
"django.contrib.auth.forms.ReadOnlyPasswordHashField",
"django.contrib.messages.error",
"django.contrib.admin.site.register",
"profiles.models.FavoritesProducts.objects.filter",
"orders.models.Order.objects.filter",
"products.models.Product... | [((3904, 3940), 'django.contrib.admin.site.register', 'admin.site.register', (['User', 'UserAdmin'], {}), '(User, UserAdmin)\n', (3923, 3940), False, 'from django.contrib import admin\n'), ((3941, 3969), 'django.contrib.admin.site.unregister', 'admin.site.unregister', (['Group'], {}), '(Group)\n', (3962, 3969), False, ... |
import numpy as np
from sklearn.model_selection import train_test_split, StratifiedKFold
import shutil
from src.model_torch import train_model_eegnet
from src.utils import set_seed
from src.utils import single_auc_loging
import codecs
from functools import reduce
import os
import sys
sys.path.append(os.path.join(os.pa... | [
"numpy.mean",
"numpy.ones",
"os.makedirs",
"sklearn.model_selection.train_test_split",
"numpy.std",
"os.path.join",
"numpy.argmax",
"src.utils.single_auc_loging",
"numpy.max",
"sklearn.model_selection.StratifiedKFold",
"os.getcwd",
"numpy.zeros",
"os.path.isdir",
"numpy.concatenate",
"sh... | [((623, 664), 'os.path.join', 'os.path.join', (['path_to_subj', '"""checkpoints"""'], {}), "(path_to_subj, 'checkpoints')\n", (635, 664), False, 'import os\n'), ((672, 699), 'os.path.isdir', 'os.path.isdir', (['path_to_subj'], {}), '(path_to_subj)\n', (685, 699), False, 'import os\n'), ((741, 764), 'os.makedirs', 'os.m... |
"""
Ensures it can read and write to the file
"""
import guildreader
import unittest
import random
class FakeGuild:
def __init__(self):
self.id = random.randint(1, 1000)
class FakeBot:
def __init__(self):
self.guilds = []
for _ in range(30):
self.guilds += [FakeGuild()]
... | [
"guildreader.create_file",
"guildreader.read_file",
"guildreader.write_file",
"unittest.main",
"random.randint"
] | [((1229, 1244), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1242, 1244), False, 'import unittest\n'), ((161, 184), 'random.randint', 'random.randint', (['(1)', '(1000)'], {}), '(1, 1000)\n', (175, 184), False, 'import random\n'), ((438, 497), 'guildreader.create_file', 'guildreader.create_file', (['self.bot', ... |
from app.extensions import db
from .user import User
posts_tags = db.Table(
'post_tags', db.metadata,
db.Column('post_id', db.Integer, db.ForeignKey('post.id')),
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'))
)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = d... | [
"app.extensions.db.String",
"app.extensions.db.relationship",
"app.extensions.db.Column",
"app.extensions.db.Integer",
"app.extensions.db.ForeignKey"
] | [((267, 306), 'app.extensions.db.Column', 'db.Column', (['db.Integer'], {'primary_key': '(True)'}), '(db.Integer, primary_key=True)\n', (276, 306), False, 'from app.extensions import db\n'), ((359, 377), 'app.extensions.db.Column', 'db.Column', (['db.Text'], {}), '(db.Text)\n', (368, 377), False, 'from app.extensions i... |
# this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.
from astropy.version import version as astropy_version
if astropy_version < '3.0':
# With older versions of Astrop... | [
"os.path.dirname",
"astropy.tests.helper.enable_deprecations_as_exceptions",
"astropy.tests.plugins.display.PYTEST_HEADER_MODULES.clear",
"astropy.tests.plugins.display.PYTEST_HEADER_MODULES.update"
] | [((988, 1023), 'astropy.tests.helper.enable_deprecations_as_exceptions', 'enable_deprecations_as_exceptions', ([], {}), '()\n', (1021, 1023), False, 'from astropy.tests.helper import enable_deprecations_as_exceptions\n'), ((1025, 1054), 'astropy.tests.plugins.display.PYTEST_HEADER_MODULES.clear', 'PYTEST_HEADER_MODULES... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/8/16 17:12
# @Author : zzy824
# @File : emojify_main.py
import numpy as np
from emo_utils import *
import emoji
import matplotlib.pyplot as plt
""" Baseline model: Emojifier-V1 """
X_train, Y_train = read_csv('data/train_emoji.csv')
X_test, Y_test = ... | [
"numpy.sqrt",
"numpy.log",
"numpy.dot",
"numpy.zeros",
"numpy.random.seed",
"numpy.random.randn"
] | [((1827, 1839), 'numpy.zeros', 'np.zeros', (['(50)'], {}), '(50)\n', (1835, 1839), True, 'import numpy as np\n'), ((2939, 2956), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (2953, 2956), True, 'import numpy as np\n'), ((3244, 3260), 'numpy.zeros', 'np.zeros', (['(n_y,)'], {}), '((n_y,))\n', (3252, 32... |
import numpy as np
from matplotlib import pyplot as plt
'''
Function for plotting training and validation curves.
'''
def learning_curves(history, multival=None, model_n=None, filepath=None, plot_from_epoch=0, plot_to_epoch=None):
n = len(history)
num_epochs = len(history[0]['loss'])
if plot_to_epoch is ... | [
"numpy.mean",
"numpy.reshape",
"matplotlib.pyplot.savefig",
"numpy.minimum",
"matplotlib.pyplot.ylabel",
"numpy.arange",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ioff",
"matplotlib.pyplot.close",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.std",
"matplotlib.pyplot.title",
"nump... | [((429, 454), 'numpy.zeros', 'np.zeros', (['(n, num_epochs)'], {}), '((n, num_epochs))\n', (437, 454), True, 'import numpy as np\n'), ((471, 496), 'numpy.zeros_like', 'np.zeros_like', (['train_loss'], {}), '(train_loss)\n', (484, 496), True, 'import numpy as np\n'), ((512, 537), 'numpy.zeros_like', 'np.zeros_like', (['... |
from core.utils.generic_helpers import get_current_financial_year
from data_lake.views.data_lake_view import DataLakeViewSet
from data_lake.views.utils import FigureFieldData
from forecast.models import FinancialPeriod, BudgetMonthlyFigure
class BudgetActualViewSet(
DataLakeViewSet, FigureFieldData
):
filen... | [
"forecast.models.BudgetMonthlyFigure.objects.exclude",
"data_lake.views.utils.FigureFieldData.chart_of_account_titles.copy",
"forecast.models.FinancialPeriod.financial_period_info.actual_period_code_list",
"core.utils.generic_helpers.get_current_financial_year"
] | [((486, 532), 'data_lake.views.utils.FigureFieldData.chart_of_account_titles.copy', 'FigureFieldData.chart_of_account_titles.copy', ([], {}), '()\n', (530, 532), False, 'from data_lake.views.utils import FigureFieldData\n'), ((1454, 1482), 'core.utils.generic_helpers.get_current_financial_year', 'get_current_financial_... |
# Copyright 2019 Google 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 to in writing, ... | [
"subprocess.check_output",
"os.path.dirname",
"os.path.join",
"os.getenv"
] | [((1227, 1276), 'subprocess.check_output', 'subprocess.check_output', (['"""pip freeze"""'], {'shell': '(True)'}), "('pip freeze', shell=True)\n", (1250, 1276), False, 'import subprocess\n'), ((2033, 2066), 'os.getenv', 'os.getenv', (['"""TEST_BOT_ENVIRONMENT"""'], {}), "('TEST_BOT_ENVIRONMENT')\n", (2042, 2066), False... |
from PySide2.QtWidgets import (
QApplication,
QSystemTrayIcon,
QMainWindow,
QTextEdit,
QMenu,
QAction,
)
from PySide2.QtGui import QIcon
import sys
app = QApplication(sys.argv)
app.setQuitOnLastWindowClosed(False)
# Create the icon
icon = QIcon("animal-penguin.png")
# C... | [
"PySide2.QtWidgets.QTextEdit",
"PySide2.QtGui.QIcon",
"PySide2.QtWidgets.QApplication",
"PySide2.QtWidgets.QSystemTrayIcon",
"PySide2.QtWidgets.QAction"
] | [((194, 216), 'PySide2.QtWidgets.QApplication', 'QApplication', (['sys.argv'], {}), '(sys.argv)\n', (206, 216), False, 'from PySide2.QtWidgets import QApplication, QSystemTrayIcon, QMainWindow, QTextEdit, QMenu, QAction\n'), ((284, 311), 'PySide2.QtGui.QIcon', 'QIcon', (['"""animal-penguin.png"""'], {}), "('animal-peng... |