code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from typing import List, Dict, Union
from .item import Item
from .coordinates import Coordinates
from copy import deepcopy
class Shop:
def __init__(self, name: str = "", owner: List = [], items: List = [], coords: Coordinates = Coordinates(), post: str = None, id: int = -1):
super().__init__()
self.id = id
... | [
"copy.deepcopy"
] | [((508, 527), 'copy.deepcopy', 'deepcopy', (['self.name'], {}), '(self.name)\n', (516, 527), False, 'from copy import deepcopy\n'), ((578, 599), 'copy.deepcopy', 'deepcopy', (['self.coords'], {}), '(self.coords)\n', (586, 599), False, 'from copy import deepcopy\n'), ((615, 634), 'copy.deepcopy', 'deepcopy', (['self.pos... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 15 20:25:53 2015
@author: Wasit
"""
import numpy as np
import pandas as pd
df = pd.read_csv('cs401.csv',delimiter=",",parse_dates=True,
infer_datetime_format=True,dayfirst=False,encoding='utf8')
myheader=list(df.columns.values)
advisors={'name':[]}
for... | [
"pandas.DataFrame",
"pandas.ExcelWriter",
"pandas.read_csv"
] | [((128, 250), 'pandas.read_csv', 'pd.read_csv', (['"""cs401.csv"""'], {'delimiter': '""","""', 'parse_dates': '(True)', 'infer_datetime_format': '(True)', 'dayfirst': '(False)', 'encoding': '"""utf8"""'}), "('cs401.csv', delimiter=',', parse_dates=True,\n infer_datetime_format=True, dayfirst=False, encoding='utf8')\... |
from sicpythontask.PythonTaskInfo import PythonTaskInfo
from sicpythontask.PythonTask import PythonTask
from sicpythontask.InputPort import InputPort
from sicpythontask.OutputPort import OutputPort
from sicpythontask.data.Int32 import Int32
from sicpythontask.data.Control import Control
@PythonTaskInfo(generator=True)... | [
"sicpythontask.data.Int32.Int32",
"sicpythontask.InputPort.InputPort",
"sicpythontask.OutputPort.OutputPort",
"sicpythontask.PythonTaskInfo.PythonTaskInfo"
] | [((290, 320), 'sicpythontask.PythonTaskInfo.PythonTaskInfo', 'PythonTaskInfo', ([], {'generator': '(True)'}), '(generator=True)\n', (304, 320), False, 'from sicpythontask.PythonTaskInfo import PythonTaskInfo\n'), ((418, 456), 'sicpythontask.InputPort.InputPort', 'InputPort', ([], {'name': '"""in1"""', 'data_type': 'Int... |
from django.urls import path
from . import views
app_name = 'service_app'
urlpatterns = [
path('', views.index, name='index'),
path('title/', views.get_by_title, name='title'),
path('filter/', views.get_filtered_films, name='filter'),
path('vote/', views.vote_for_film, name='vote'),
path('insert/'... | [
"django.urls.path"
] | [((95, 130), 'django.urls.path', 'path', (['""""""', 'views.index'], {'name': '"""index"""'}), "('', views.index, name='index')\n", (99, 130), False, 'from django.urls import path\n'), ((136, 184), 'django.urls.path', 'path', (['"""title/"""', 'views.get_by_title'], {'name': '"""title"""'}), "('title/', views.get_by_ti... |
'''My CMA=ES
'''
import numpy as np
import matplotlib.pyplot as plt
mean = [0, 0]
cov = [[1, 0], [0, 100]]
x, y = np.random.multivariate_normal(mean, cov, 5000).T
plt.plot(x, y, 'x')
plt.axis('equal')
plt.show()
| [
"numpy.random.multivariate_normal",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show"
] | [((165, 184), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""x"""'], {}), "(x, y, 'x')\n", (173, 184), True, 'import matplotlib.pyplot as plt\n'), ((185, 202), 'matplotlib.pyplot.axis', 'plt.axis', (['"""equal"""'], {}), "('equal')\n", (193, 202), True, 'import matplotlib.pyplot as plt\n'), ((203, 213), 'matplot... |
import os
"""Application configuration"""
class Config(object):
"""Base config class"""
DEBUG = True
SECRET = os.getenv("SECRET_KEY")
class DevelopmentConfig(Config):
"""Development configurations"""
DEBUG = True
class TestingConfig(Config):
"""Testing configurations"""
DEBUG = True
... | [
"os.getenv"
] | [((125, 148), 'os.getenv', 'os.getenv', (['"""SECRET_KEY"""'], {}), "('SECRET_KEY')\n", (134, 148), False, 'import os\n')] |
"""empty message
Revision ID: 09d3732eef24
Revises: <PASSWORD>
Create Date: 2020-03-12 15:13:32.832239
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '09d3732eef24'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
# ### ... | [
"sqlalchemy.ForeignKeyConstraint",
"alembic.op.drop_table",
"sqlalchemy.PrimaryKeyConstraint",
"sqlalchemy.Numeric",
"sqlalchemy.Integer",
"sqlalchemy.String"
] | [((1134, 1155), 'alembic.op.drop_table', 'op.drop_table', (['"""task"""'], {}), "('task')\n", (1147, 1155), False, 'from alembic import op\n'), ((917, 966), 'sqlalchemy.ForeignKeyConstraint', 'sa.ForeignKeyConstraint', (["['user_id']", "['user.id']"], {}), "(['user_id'], ['user.id'])\n", (940, 966), True, 'import sqlal... |
"""
Enums used in AHB and condition expressions.
"""
from enum import Enum, unique
from typing import Dict, Literal, Union
from marshmallow import Schema, fields, post_dump, post_load, pre_load
@unique
class ModalMark(str, Enum):
"""
A modal mark describes if information are obligatory or not. The German ter... | [
"marshmallow.fields.String"
] | [((3935, 3950), 'marshmallow.fields.String', 'fields.String', ([], {}), '()\n', (3948, 3950), False, 'from marshmallow import Schema, fields, post_dump, post_load, pre_load\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-16 17:12
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ranking', '0002_auto_20170316_1706'),
]
operations = [
migrations.RenameFie... | [
"django.db.models.FloatField",
"django.db.migrations.RenameField"
] | [((300, 388), 'django.db.migrations.RenameField', 'migrations.RenameField', ([], {'model_name': '"""testscores"""', 'old_name': '"""score"""', 'new_name': '"""below"""'}), "(model_name='testscores', old_name='score', new_name=\n 'below')\n", (322, 388), False, 'from django.db import migrations, models\n'), ((546, 57... |
from flask import Flask, render_template
import data_
app = Flask(__name__)
@app.route('/search')
def search():
videos = data_.get_results_from_keyword(keyword = 'film theory')
return render_template('search.html', videos = videos)
if __name__ == '__main__':
app.run()
| [
"flask.render_template",
"data_.get_results_from_keyword",
"flask.Flask"
] | [((62, 77), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (67, 77), False, 'from flask import Flask, render_template\n'), ((128, 181), 'data_.get_results_from_keyword', 'data_.get_results_from_keyword', ([], {'keyword': '"""film theory"""'}), "(keyword='film theory')\n", (158, 181), False, 'import data_\n... |
import hr
import employees
import productivity
'''
The program creates three employee objects, one for each of the derived classes.
Then, it creates the payroll system and passes a list of the employees to its .calculate_payroll() method,
which calculates the payroll for each employee and prints the results.
... | [
"employees.SalesPerson",
"employees.FactoryWorker",
"employees.Manager",
"hr.PayrollSystem",
"productivity.ProductivitySystem",
"employees.Secretary"
] | [((543, 579), 'employees.Manager', 'employees.Manager', (['(1)', '"""<NAME>"""', '(3000)'], {}), "(1, '<NAME>', 3000)\n", (560, 579), False, 'import employees\n'), ((593, 631), 'employees.Secretary', 'employees.Secretary', (['(2)', '"""<NAME>"""', '(1500)'], {}), "(2, '<NAME>', 1500)\n", (612, 631), False, 'import empl... |
import io
import unittest
from unittest.mock import patch
from kattis import k_trip2007
###############################################################################
class SampleInput(unittest.TestCase):
'''Problem statement sample inputs and outputs'''
def test_sample_input(self):
'''Run and asser... | [
"unittest.main",
"io.StringIO",
"kattis.k_trip2007.main",
"unittest.mock.patch"
] | [((1296, 1311), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1309, 1311), False, 'import unittest\n'), ((992, 1037), 'unittest.mock.patch', 'patch', (['"""sys.stdout"""'], {'new_callable': 'io.StringIO'}), "('sys.stdout', new_callable=io.StringIO)\n", (997, 1037), False, 'from unittest.mock import patch\n'), ((... |
from django.db import models
# Create your models here.
class PolicyCreation(models.Model):
policyname= models.CharField(max_length=100)
description= models.TextField()
def __str__(self):
return self.policyname | [
"django.db.models.TextField",
"django.db.models.CharField"
] | [((109, 141), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (125, 141), False, 'from django.db import models\n'), ((159, 177), 'django.db.models.TextField', 'models.TextField', ([], {}), '()\n', (175, 177), False, 'from django.db import models\n')] |
import json
import requests
BASE_URL = "http://127.0.0.1:5000/"
def test__query_data():
response = requests.get(BASE_URL + "query-data?name=hmtmcse.com&age=7")
response_data = response.json()
assert response.status_code == 200, "Should be 200"
assert response_data["name"] == "hmtmcse.com"
asser... | [
"json.dumps",
"requests.post",
"requests.get"
] | [((107, 167), 'requests.get', 'requests.get', (["(BASE_URL + 'query-data?name=hmtmcse.com&age=7')"], {}), "(BASE_URL + 'query-data?name=hmtmcse.com&age=7')\n", (119, 167), False, 'import requests\n'), ((401, 471), 'requests.get', 'requests.get', (["(BASE_URL + 'get-query-data-value?name=hmtmcse.com&age=7')"], {}), "(BA... |
#!/usr/bin/env python3
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
# coding=utf8
import unittest
from unittest.mock import Mock
import jool_exporter
# Turn off logging for unit tests - Comment out to enable
jool_exporter.LOG = Mock()
... | [
"unittest.main",
"jool_exporter._handle_debug",
"unittest.mock.Mock",
"jool_exporter.JoolCollector"
] | [((312, 318), 'unittest.mock.Mock', 'Mock', ([], {}), '()\n', (316, 318), False, 'from unittest.mock import Mock\n'), ((577, 592), 'unittest.main', 'unittest.main', ([], {}), '()\n', (590, 592), False, 'import unittest\n'), ((411, 440), 'jool_exporter.JoolCollector', 'jool_exporter.JoolCollector', ([], {}), '()\n', (43... |
#!/usr/bin/env python3
import re
from collections import deque
players, points = re.search('(\\d+) players; last marble is worth (\\d+) points', input()).groups()
players = [0]*int(players)
points = int(points)*100
marbles = deque([0])
cur = 0
for i in range(1, points+1):
if i%23 == 0:
marbles.rotate(7)... | [
"collections.deque"
] | [((229, 239), 'collections.deque', 'deque', (['[0]'], {}), '([0])\n', (234, 239), False, 'from collections import deque\n')] |
from setuptools import setup, find_packages
import codecs
# import os
import pathlib
# The directory containing this file
# here = os.path.abspath(os.path.dirname(__file__))
HERE = pathlib.Path(__file__).parent
# The text of the README file
# with codecs.open(os.path.join(here, "README.md"), encoding="utf-8") as f... | [
"setuptools.find_packages",
"pathlib.Path"
] | [((185, 207), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (197, 207), False, 'import pathlib\n'), ((993, 1008), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (1006, 1008), False, 'from setuptools import setup, find_packages\n')] |
from assetregister import AssetRegister
ar = AssetRegister()
ar.add_all_assets()
ar.export_token_info()
ar.blocktimes.update()
ar.blocktimes.save()
for sym, adr in ar.token_lookup.items():
print(f"calculating price history for {sym}")
ar.calculate_price_history_in_eth(sym)
ar.save_price_history(sym)
| [
"assetregister.AssetRegister"
] | [((46, 61), 'assetregister.AssetRegister', 'AssetRegister', ([], {}), '()\n', (59, 61), False, 'from assetregister import AssetRegister\n')] |
import os
import re
import shutil
import sys
import pandas as pd
import pdfminer.settings
from nltk.corpus import stopwords
pdfminer.settings.STRICT = False
import pdfminer.high_level
import pdfminer.layout
from pdfminer.image import ImageWriter
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.f... | [
"os.path.exists",
"os.listdir",
"nltk.corpus.stopwords.words",
"sklearn.feature_extraction.text.CountVectorizer",
"pdfminer.image.ImageWriter",
"sklearn.feature_extraction.text.TfidfVectorizer",
"os.mkdir",
"shutil.rmtree",
"re.sub"
] | [((378, 404), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (393, 404), False, 'from nltk.corpus import stopwords\n'), ((504, 523), 'os.path.exists', 'os.path.exists', (['dir'], {}), '(dir)\n', (518, 523), False, 'import os\n'), ((548, 561), 'os.mkdir', 'os.mkdir', (['dir']... |
from distutils.log import error
from os import access
from typing import Any, Dict
import aiohttp
import async_timeout
import asyncio
import logging
import socket
from datetime import datetime
import re
import time
from ..errors import APIError, AuthError, SessionError, ApiConnectionError
TIMEOUT=10
HEADERS = {"Conte... | [
"logging.getLogger",
"async_timeout.timeout",
"datetime.datetime.fromisoformat",
"re.sub",
"time.time"
] | [((392, 422), 'logging.getLogger', 'logging.getLogger', (['__package__'], {}), '(__package__)\n', (409, 422), False, 'import logging\n'), ((947, 982), 're.sub', 're.sub', (['"""Z$"""', '"""+00:00"""', 'date_string'], {}), "('Z$', '+00:00', date_string)\n", (953, 982), False, 'import re\n'), ((1078, 1113), 'datetime.dat... |
import ast
import sys
import inspect
import codegen
import astpretty
def func1():
return 1
agent_func = """
@flamegpu_device_function
def helper(x: numpy.int16) -> int :
return x**2
@flamegpu_agent_function
def pred_output_location(message_in: MessageBruteForce, message_out: MessageBruteForce):
... | [
"ast.parse",
"codegen.codegen"
] | [((1088, 1109), 'ast.parse', 'ast.parse', (['agent_func'], {}), '(agent_func)\n', (1097, 1109), False, 'import ast\n'), ((1191, 1212), 'codegen.codegen', 'codegen.codegen', (['tree'], {}), '(tree)\n', (1206, 1212), False, 'import codegen\n')] |
import unittest
from octosignblockchain.signature import Signature
from .web3_mock import Web3
class TestSignature(unittest.TestCase):
def test_instance(self):
signature = Signature('Janko', 'ax3', '0x123')
self.assertEqual(signature.name, 'Janko')
self.assertEqual(signature.hash, 'ax3')
... | [
"octosignblockchain.signature.Signature",
"octosignblockchain.signature.Signature.from_serialized"
] | [((186, 220), 'octosignblockchain.signature.Signature', 'Signature', (['"""Janko"""', '"""ax3"""', '"""0x123"""'], {}), "('Janko', 'ax3', '0x123')\n", (195, 220), False, 'from octosignblockchain.signature import Signature\n'), ((524, 558), 'octosignblockchain.signature.Signature', 'Signature', (['"""Janko"""', '"""ax3"... |
# Solution of;
# Project Euler Problem 218: Perfect right-angled triangles
# https://projecteuler.net/problem=218
#
# Consider the right angled triangle with sides a=7, b=24 and c=25. The area
# of this triangle is 84, which is divisible by the perfect numbers 6 and 28.
# Moreover it is a primitive right angled tria... | [
"timed.caller"
] | [((931, 965), 'timed.caller', 'timed.caller', (['dummy', 'n', 'i', 'prob_id'], {}), '(dummy, n, i, prob_id)\n', (943, 965), False, 'import timed\n')] |
import visuals
import matplotlib.pyplot as plt
import vice
import sys
def plot_sr_fe_tracks(ax):
plot_track(ax, "../../simulations/sudden_5Gyr_5e9Msun", "sr", "crimson", '-')
plot_track(ax, "../../simulations/sudden_5Gyr_5e9Msun", "fe", "black", ':')
plot_track(ax, "../../simulations/sudden_5Gyr_5e9Msun_riaexp", "... | [
"matplotlib.pyplot.savefig",
"vice.output",
"matplotlib.pyplot.clf",
"visuals.mpl_loc",
"matplotlib.pyplot.tight_layout",
"visuals.subplots",
"visuals.colors"
] | [((675, 692), 'vice.output', 'vice.output', (['name'], {}), '(name)\n', (686, 692), False, 'import vice\n'), ((1367, 1389), 'visuals.subplots', 'visuals.subplots', (['(1)', '(1)'], {}), '(1, 1)\n', (1383, 1389), False, 'import visuals\n'), ((1512, 1530), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '... |
# -*- coding: utf-8 -*-
"""
.. invisible:
_ _ _____ _ _____ _____
| | | | ___| | | ___/ ___|
| | | | |__ | | | |__ \ `--.
| | | | __|| | | __| `--. \
\ \_/ / |___| |___| |___/\__/ /
\___/\____/\_____|____/\____/
Created on May 19, 2014
Unit test for convolutional layer forwa... | [
"veles.znicz.tests.functional.StandardTest.main",
"veles.znicz.gd_conv.GradientDescentConv",
"veles.znicz.conv.Conv",
"veles.znicz.evaluator.EvaluatorSoftmax",
"veles.znicz.normalization.LRNormalizerForward",
"veles.znicz.gd.GDSoftmax",
"veles.znicz.all2all.All2AllSoftmax",
"numpy.greater",
"veles.z... | [((33981, 34000), 'veles.znicz.tests.functional.StandardTest.main', 'StandardTest.main', ([], {}), '()\n', (33998, 34000), False, 'from veles.znicz.tests.functional import StandardTest\n'), ((4639, 4686), 'os.path.join', 'os.path.join', (['self.data_dir_path', 'data_filename'], {}), '(self.data_dir_path, data_filename)... |
from curses import COLOR_CYAN
from os import wait
import string
from manim import *
from manim.utils import tex
import numpy as np
import math
import textwrap
import random
from solarized import *
from tqdm import tqdm
# Use our fork of manim_rubikscube!
from manim_rubikscube import *
# Temne pozadi, ale zakomentovat... | [
"numpy.insert",
"random.choice",
"random.randint",
"random.setstate",
"math.sqrt",
"random.seed",
"random.getstate",
"math.cos",
"numpy.array",
"math.sin",
"math.atan"
] | [((387, 401), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (398, 401), False, 'import random\n'), ((1479, 1496), 'random.getstate', 'random.getstate', ([], {}), '()\n', (1494, 1496), False, 'import random\n'), ((3101, 3118), 'random.getstate', 'random.getstate', ([], {}), '()\n', (3116, 3118), False, 'import r... |
import requests
import polyline
import json
import os
class Writer:
def __init__(self):
self.features = []
def query(self, src, dest, custom_label = None):
request_url = 'https://maps.googleapis.com/maps/api/directions/json?origin="{0}"&destination="{1}"&key={2}'.format(src, dest, os.environ["... | [
"json.dump",
"polyline.decode",
"requests.get"
] | [((362, 387), 'requests.get', 'requests.get', (['request_url'], {}), '(request_url)\n', (374, 387), False, 'import requests\n'), ((512, 534), 'polyline.decode', 'polyline.decode', (['route'], {}), '(route)\n', (527, 534), False, 'import polyline\n'), ((1358, 1381), 'json.dump', 'json.dump', (['geojson', 'out'], {}), '(... |
import os
import numpy as np
import nilearn as nl
import nilearn.plotting
from math import floor
import numpy as np
import torch
import torch.utils.data as data
from torch import Tensor
from typing import Optional
def load_scenes(path: str) -> list:
with open(path, "r") as f:
result = []
for line ... | [
"os.listdir",
"math.floor",
"nilearn.image.load_img",
"os.path.join",
"numpy.concatenate",
"numpy.transpose"
] | [((1030, 1049), 'math.floor', 'floor', (['num_examples'], {}), '(num_examples)\n', (1035, 1049), False, 'from math import floor\n'), ((3255, 3313), 'os.path.join', 'os.path.join', (['root', '"""stimuli"""', '"""annotations"""', '"""scenes.csv"""'], {}), "(root, 'stimuli', 'annotations', 'scenes.csv')\n", (3267, 3313), ... |
import json
import errno
config = {
'first_file_filesize' : '1024',
'second_file_filesize' : '128'
}
def write_config():
with open('config.json', 'w') as config_file:
json.dump(config, config_file)
def read_config():
try:
config_file = open('config.json', 'r')
config = json... | [
"json.load",
"json.dump"
] | [((192, 222), 'json.dump', 'json.dump', (['config', 'config_file'], {}), '(config, config_file)\n', (201, 222), False, 'import json\n'), ((316, 338), 'json.load', 'json.load', (['config_file'], {}), '(config_file)\n', (325, 338), False, 'import json\n')] |
# -*- coding: utf-8 -*-
import numpy as np
import tensorflow as tf
import warnings
import skimage.segmentation
from patchwork._augment import SINGLE_AUG_FUNC
SEG_AUG_FUNCTIONS = ["flip_left_right", "flip_up_down", "rot90", "shear", "zoom_scale", "center_zoom_scale"]
def _get_segments(img, mean_scale=1000, num_samp... | [
"numpy.sqrt",
"tensorflow.reshape",
"tensorflow.image.resize",
"numpy.random.choice",
"tensorflow.reduce_sum",
"numpy.stack",
"numpy.zeros",
"tensorflow.reduce_mean",
"numpy.random.uniform",
"warnings.warn",
"tensorflow.expand_dims",
"tensorflow.cast",
"numpy.arange"
] | [((1088, 1141), 'numpy.random.uniform', 'np.random.uniform', (['(0.5 * mean_scale)', '(1.5 * mean_scale)'], {}), '(0.5 * mean_scale, 1.5 * mean_scale)\n', (1105, 1141), True, 'import numpy as np\n'), ((1424, 1450), 'numpy.arange', 'np.arange', (['(max_segment + 1)'], {}), '(max_segment + 1)\n', (1433, 1450), True, 'imp... |
from enum import IntEnum
from deprecated import deprecated # type: ignore
class OperationMode(IntEnum):
AUTO = 1
COOLING = 2
HEATING = 3
FAN = 4
DRY = 5
@classmethod
def _missing_(cls, value):
return OperationMode.AUTO
class Speed(IntEnum):
AUTO = 0
SPEED_1 = 1
SPEE... | [
"deprecated.deprecated"
] | [((4037, 4089), 'deprecated.deprecated', 'deprecated', (['"""Use the machine_state property instead"""'], {}), "('Use the machine_state property instead')\n", (4047, 4089), False, 'from deprecated import deprecated\n')] |
# pylint: disable=missing-function-docstring,redefined-outer-name,
# pylint: disable=protected-access,missing-module-docstring
import pytest
from singly_linkedlist.singly_linkedlist import Node, \
SinglyLinkedList, SinglyLinkedListException, SinglyLinkedListIndexError, \
SinglyLinkedListEmptyError
# return an... | [
"singly_linkedlist.singly_linkedlist.SinglyLinkedList",
"singly_linkedlist.singly_linkedlist.Node",
"pytest.raises"
] | [((389, 407), 'singly_linkedlist.singly_linkedlist.SinglyLinkedList', 'SinglyLinkedList', ([], {}), '()\n', (405, 407), False, 'from singly_linkedlist.singly_linkedlist import Node, SinglyLinkedList, SinglyLinkedListException, SinglyLinkedListIndexError, SinglyLinkedListEmptyError\n'), ((443, 452), 'singly_linkedlist.s... |
"""
This file contains methods that describe a Tensorflow model.
It can be used as template for a completely new model and is imported
in the training script
"""
import logging
import tensorflow as tf
# Give the model a descriptive name
NAME = 'two_fully_connected'
# The size of the input layer
INPUT_SIZE = 1083
# T... | [
"tensorflow.variable_scope",
"tensorflow.Variable",
"tensorflow.contrib.layers.xavier_initializer",
"tensorflow.truncated_normal_initializer",
"tensorflow.nn.dropout",
"tensorflow.matmul",
"tensorflow.train.exponential_decay",
"tensorflow.constant_initializer",
"tensorflow.train.AdamOptimizer",
"t... | [((511, 562), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {'name': '"""global_step"""', 'trainable': '(False)'}), "(0, name='global_step', trainable=False)\n", (522, 562), True, 'import tensorflow as tf\n'), ((583, 661), 'tensorflow.train.exponential_decay', 'tf.train.exponential_decay', (['initial', 'global_step',... |
"""
FID evaluation function used by misalignments.py
"""
import os
import shutil
import numpy as np
import torch
from pytorch_fid import fid_score
from generate_samples import save_individuals_v2
def fid_eval(generator,
real_data,
directory,
inception_net,
noise):
... | [
"os.path.exists",
"generate_samples.save_individuals_v2",
"numpy.savez",
"os.makedirs",
"pytorch_fid.fid_score.calculate_frechet_distance",
"os.path.join",
"pytorch_fid.fid_score.compute_statistics_of_path",
"torch.device"
] | [((1798, 1840), 'os.path.join', 'os.path.join', (['directory', '"""samples_for_fid"""'], {}), "(directory, 'samples_for_fid')\n", (1810, 1840), False, 'import os\n'), ((1848, 1881), 'os.path.exists', 'os.path.exists', (['fake_samples_path'], {}), '(fake_samples_path)\n', (1862, 1881), False, 'import os\n'), ((1942, 197... |
import os
import scicopia.arangodoc as arangodoc
from scicopia.utils.arangodb import connect, select_db
def connection(col):
# use a config to a test database
config = arangodoc.read_config()
arangoconn = connect(config)
db = select_db(config, arangoconn, create=True)
if db.hasCollection(col):
... | [
"scicopia.arangodoc.zstd_open",
"scicopia.arangodoc.locate_files",
"scicopia.utils.arangodb.connect",
"scicopia.utils.arangodb.select_db",
"scicopia.arangodoc.pdfsave",
"scicopia.arangodoc.read_config",
"scicopia.arangodoc.import_file",
"scicopia.arangodoc.create_id"
] | [((180, 203), 'scicopia.arangodoc.read_config', 'arangodoc.read_config', ([], {}), '()\n', (201, 203), True, 'import scicopia.arangodoc as arangodoc\n'), ((221, 236), 'scicopia.utils.arangodb.connect', 'connect', (['config'], {}), '(config)\n', (228, 236), False, 'from scicopia.utils.arangodb import connect, select_db\... |
#!/usr/bin/env python
import sys
from os import path, mkdir
import shutil
from glob import glob
import subprocess
import random
def write_script_header(cluster, script, event_id, walltime, working_folder):
if cluster == "nersc":
script.write(
"""#!/bin/bash -l
#SBATCH -p shared
#SBATCH -n 1
#SBATCH -J UrQ... | [
"subprocess.Popen",
"os.path.join",
"os.mkdir",
"shutil.copy",
"os.path.abspath",
"glob.glob"
] | [((18359, 18404), 'glob.glob', 'glob', (["('%s/particle_list_*.dat' % input_folder)"], {}), "('%s/particle_list_*.dat' % input_folder)\n", (18363, 18404), False, 'from glob import glob\n'), ((20112, 20157), 'glob.glob', 'glob', (["('%s/particle_list_*.dat' % input_folder)"], {}), "('%s/particle_list_*.dat' % input_fold... |
import unittest
from unittest import mock
from fate_of_dice.common.dice import Dice
class TestDice(unittest.TestCase):
def test_value(self):
value: int = 20
dice = Dice(value)
self.assertEqual(dice.value, value)
self.assertEqual(int(dice), value)
self.assertEqual(str(dic... | [
"unittest.main",
"fate_of_dice.common.dice.Dice",
"unittest.mock.patch",
"fate_of_dice.common.dice.Dice.roll"
] | [((754, 807), 'unittest.mock.patch', 'mock.patch', (['"""fate_of_dice.common.dice.dice.randrange"""'], {}), "('fate_of_dice.common.dice.dice.randrange')\n", (764, 807), False, 'from unittest import mock\n'), ((1162, 1177), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1175, 1177), False, 'import unittest\n'), ((... |
import http
import connexion
import connexion_buzz
class MyException(connexion_buzz.ConnexionBuzz):
status_code = http.HTTPStatus.BAD_REQUEST
def index():
raise MyException("basic test")
app = connexion.FlaskApp(__name__, specification_dir="openapi/")
app.app.register_error_handler(
connexion_buzz.C... | [
"connexion_buzz.ConnexionBuzz.build_error_handler",
"connexion.FlaskApp"
] | [((209, 267), 'connexion.FlaskApp', 'connexion.FlaskApp', (['__name__'], {'specification_dir': '"""openapi/"""'}), "(__name__, specification_dir='openapi/')\n", (227, 267), False, 'import connexion\n'), ((334, 384), 'connexion_buzz.ConnexionBuzz.build_error_handler', 'connexion_buzz.ConnexionBuzz.build_error_handler', ... |
import numpy as np
import matplotlib.pyplot as plt
import csv
causes = ['OUTRAS', 'COVID', 'INSUFICIENCIA_RESPIRATORIA', 'PNEUMONIA', 'SEPTICEMIA', 'SRAG', 'INDETERMINADA']
for i in range(len(causes)):
vars()[causes[i]] = 0
firstRow = 1
with open('obitos-2020.csv', newline='') as csvfile:
originalfile = csv... | [
"numpy.array",
"csv.reader",
"matplotlib.pyplot.rcdefaults",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((1340, 1356), 'matplotlib.pyplot.rcdefaults', 'plt.rcdefaults', ([], {}), '()\n', (1354, 1356), True, 'import matplotlib.pyplot as plt\n'), ((1367, 1381), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1379, 1381), True, 'import matplotlib.pyplot as plt\n'), ((1518, 1528), 'matplotlib.pyplot.show', ... |
#!/usr/bin/sudo python
from scapy.all import *
from scapy.layers.inet import TCP, IP
from filter import TrafficFilter, CallBackFilter
src = '192.168.1.63'
dst = '192.168.1.94'
verbose = True
def log(data: str):
if verbose:
print(data)
def throttle_data_from_destination(pkt: Packet):
ip, tcp = pk... | [
"scapy.layers.inet.IP",
"filter.CallBackFilter",
"filter.TrafficFilter"
] | [((1986, 2017), 'filter.TrafficFilter', 'TrafficFilter', ([], {'src': 'src', 'dst': 'dst'}), '(src=src, dst=dst)\n', (1999, 2017), False, 'from filter import TrafficFilter, CallBackFilter\n'), ((2027, 2071), 'filter.CallBackFilter', 'CallBackFilter', (['tf'], {'callback': 'custom_callback'}), '(tf, callback=custom_call... |
from keras.layers import Activation, Conv2D, Dense, Flatten, MaxPooling2D
from keras.models import Sequential
from keras.optimizers import Adam
from keras.preprocessing.image import ImageDataGenerator
from numpy import ndarray
from typing import NamedTuple, List
from image.frame import SpongeFrame
from image.diglet.sp... | [
"image.diglet.specifications.get_attr_epochs",
"keras.layers.Conv2D",
"image.diglet.specifications.get_color_dim",
"keras.layers.Flatten",
"keras.layers.MaxPooling2D",
"image.diglet.specifications.get_attr_lr",
"keras.preprocessing.image.ImageDataGenerator",
"keras.models.Sequential",
"image.diglet.... | [((891, 903), 'keras.models.Sequential', 'Sequential', ([], {}), '()\n', (901, 903), False, 'from keras.models import Sequential\n'), ((1134, 1193), 'keras.layers.Conv2D', 'Conv2D', (['(64)', '(3, 3)'], {'padding': '"""same"""', 'input_shape': 'input_shape'}), "(64, (3, 3), padding='same', input_shape=input_shape)\n", ... |
from logging import getLogger
from models import StationDocument
from models.models import Station
logger = getLogger(__name__)
class Syncer:
@staticmethod
def sync_stations():
attrs_to_sync = ('location', 'station_name', 'station_height', 'latitude', 'longitude')
logger.info('Syncing stati... | [
"logging.getLogger",
"models.StationDocument.objects"
] | [((110, 129), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (119, 129), False, 'from logging import getLogger\n'), ((406, 431), 'models.StationDocument.objects', 'StationDocument.objects', ([], {}), '()\n', (429, 431), False, 'from models import StationDocument\n')] |
import argparse
from pathlib import Path
import os
import sys
import importlib
import logging
from p4z3 import Z3Reg, P4Package, z3
import p4z3.util as util
sys.setrecursionlimit(15000)
FILE_DIR = os.path.dirname(os.path.abspath(__file__))
log = logging.getLogger(__name__)
# We maintain a list of passes that causes... | [
"logging.getLogger",
"sys.setrecursionlimit",
"logging.basicConfig",
"p4z3.util.check_dir",
"logging.StreamHandler",
"p4z3.Z3Reg",
"argparse.ArgumentParser",
"pathlib.Path",
"p4z3.z3.Goal",
"logging.Formatter",
"p4z3.util.copy_file",
"importlib.machinery.PathFinder",
"p4z3.z3.tactics",
"p4... | [((157, 185), 'sys.setrecursionlimit', 'sys.setrecursionlimit', (['(15000)'], {}), '(15000)\n', (178, 185), False, 'import sys\n'), ((248, 275), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (265, 275), False, 'import logging\n'), ((215, 240), 'os.path.abspath', 'os.path.abspath', (['__f... |
"""
This module contains small scripts for managing the database entries for NorLyst application.
"""
import sys
from os.path import realpath
from datetime import datetime
from nordb.core.usernameUtilities import log2nordb
from nordb.database.nordicSearch import searchSameEvents
from nordb.nordic.nordicEvent import No... | [
"nordb.core.nordic.createStringMainHeader",
"datetime.datetime.datetime.now",
"datetime.datetime.strptime",
"nordb.core.usernameUtilities.log2nordb",
"datetime.datetime.now",
"nordb.nordic.nordicEvent.NordicEvent",
"nordb.database.nordicSearch.searchSameEvents",
"sys.exit",
"datetime.datetime.timede... | [((1821, 1835), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1833, 1835), False, 'from datetime import datetime\n'), ((1938, 1949), 'nordb.core.usernameUtilities.log2nordb', 'log2nordb', ([], {}), '()\n', (1947, 1949), False, 'from nordb.core.usernameUtilities import log2nordb\n'), ((2524, 2535), 'sys.ex... |
"""
Copyright (C) 2019 <NAME>, ETH Zurich
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distri... | [
"keras.optimizers.Adam",
"keras.initializers.zeros",
"numpy.prod",
"keras.initializers.he_normal",
"keras.layers.Lambda",
"keras.regularizers.L1L2",
"keras.layers.Input",
"keras.optimizers.SGD",
"functools.partial",
"keras.layers.concatenate",
"keras.models.Model",
"keras.layers.dot",
"keras... | [((4213, 4290), 'keras.models.Model', 'Model', ([], {'inputs': '[input_layer]', 'outputs': '[topmost_hidden_state, auxiliary_output]'}), '(inputs=[input_layer], outputs=[topmost_hidden_state, auxiliary_output])\n', (4218, 4290), False, 'from keras.models import Model\n'), ((15669, 15703), 'keras.layers.concatenate', 'c... |
"""Cement core hooks module."""
import operator
from ..core import backend, exc
from ..utils.misc import minimal_logger
LOG = minimal_logger(__name__)
def define(name):
"""
Define a hook namespace that plugins can register hooks in.
:param name: The name of the hook, stored as hooks['name']
:raises... | [
"operator.itemgetter"
] | [((2941, 2963), 'operator.itemgetter', 'operator.itemgetter', (['(0)'], {}), '(0)\n', (2960, 2963), False, 'import operator\n')] |
from django.views.generic.list import ListView
from django.views.generic import DetailView
from django.shortcuts import render
from django.core.paginator import Paginator
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django import forms
from django.core.cache import ca... | [
"django.shortcuts.render",
"django.http.HttpResponseRedirect",
"markdown.markdown",
"django.core.paginator.Paginator",
"django.shortcuts.get_object_or_404",
"comment_app.form.CommentForm",
"datetime.datetime.now",
"django.forms.Textarea",
"django.core.cache.cache.set",
"django.core.cache.cache.get... | [((590, 611), 'django.core.paginator.Paginator', 'Paginator', (['all', 'limit'], {}), '(all, limit)\n', (599, 611), False, 'from django.core.paginator import Paginator\n'), ((690, 739), 'django.shortcuts.render', 'render', (['request', '"""message.html"""', "{'all': loadded}"], {}), "(request, 'message.html', {'all': l... |
# Copyright (c) 2013, deepak and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
test_records = frappe.get_test_records('Flat Payment Schedule')
class TestFlatPaymentSchedule(unittest.TestCase):
pass
| [
"frappe.get_test_records"
] | [((151, 199), 'frappe.get_test_records', 'frappe.get_test_records', (['"""Flat Payment Schedule"""'], {}), "('Flat Payment Schedule')\n", (174, 199), False, 'import frappe\n')] |
#!/usr/bin/env python3
"""
Solves day 14 tasks of AoC 2020.
https://adventofcode.com/2020/day/14
"""
import argparse
import gzip
from os.path import dirname, realpath
from io import StringIO
from typing import List, Tuple, Set, Dict, IO, Iterator, cast
from pathlib import Path
from dataclasses import dataclass
from r... | [
"collections.deque",
"argparse.ArgumentParser",
"gzip.open",
"pathlib.Path",
"os.path.realpath",
"re.findall",
"io.StringIO"
] | [((2773, 2786), 'collections.deque', 'deque', (['[addr]'], {}), '([addr])\n', (2778, 2786), False, 'from collections import deque\n'), ((4590, 4615), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (4613, 4615), False, 'import argparse\n'), ((4734, 4756), 'pathlib.Path', 'Path', (['args.GZIPED_F... |
# coding: utf8
__author__ = 'Lev'
import datetime
from resources import GENDERS
class User:
def __init__(self, user_id, full_name, birth_date, gender, reg_date):
if not isinstance(user_id, int):
raise ValueError('user constructor error: bad user id')
if not full_name:
... | [
"resources.GENDERS.values",
"datetime.datetime.fromtimestamp"
] | [((678, 694), 'resources.GENDERS.values', 'GENDERS.values', ([], {}), '()\n', (692, 694), False, 'from resources import GENDERS\n'), ((452, 495), 'datetime.datetime.fromtimestamp', 'datetime.datetime.fromtimestamp', (['birth_date'], {}), '(birth_date)\n', (483, 495), False, 'import datetime\n'), ((827, 868), 'datetime.... |
from sklearn.model_selection import GridSearchCV
def cross_validate(new_pipeline_funct, hyperparams_grid, X_train, y_train, name, n_folds=4, verbose=True):
"""
Return the best hyperparameters.
"""
print("Cross-Validation Grid Search for: '{}'...".format(name))
pipeline = new_pipeline_funct()
... | [
"sklearn.model_selection.GridSearchCV"
] | [((335, 492), 'sklearn.model_selection.GridSearchCV', 'GridSearchCV', (['pipeline', 'hyperparams_grid'], {'iid': '(True)', 'cv': 'n_folds', 'return_train_score': '(False)', 'verbose': '(False)', 'scoring': '"""accuracy"""', 'n_jobs': '(4)', 'pre_dispatch': '(8)'}), "(pipeline, hyperparams_grid, iid=True, cv=n_folds,\n ... |
import inspect
def get_required_args(f, d):
"""
:param f: function
:param d: dictionary of arguments
:return: dictionary of arguments, reduced to only the ones required by
function
"""
args = inspect.getargspec(f)[0]
if args[0] == 'self':
args = args[1:]
return {k: d[k] for ... | [
"inspect.getargspec"
] | [((221, 242), 'inspect.getargspec', 'inspect.getargspec', (['f'], {}), '(f)\n', (239, 242), False, 'import inspect\n')] |
import tensorflow as tf
import numpy as np
def clip_by_value_with_gradient(x, l=-1., u=1.):
clip_up = tf.cast(x > u, tf.float32)
clip_low = tf.cast(x < l, tf.float32)
# if the difference between x and l or u is smaller than the precision,
# the following may cause the result to be 0 or 2*u
return x... | [
"tensorflow.nn.conv2d",
"tensorflow.shape",
"tensorflow.variable_scope",
"tensorflow.get_variable",
"numpy.sqrt",
"tensorflow.placeholder",
"tensorflow.nn.rnn_cell.LSTMStateTuple",
"tensorflow.add",
"tensorflow.nn.rnn_cell.LSTMCell",
"tensorflow.truncated_normal_initializer",
"tensorflow.nn.dyna... | [((107, 133), 'tensorflow.cast', 'tf.cast', (['(x > u)', 'tf.float32'], {}), '(x > u, tf.float32)\n', (114, 133), True, 'import tensorflow as tf\n'), ((149, 175), 'tensorflow.cast', 'tf.cast', (['(x < l)', 'tf.float32'], {}), '(x < l, tf.float32)\n', (156, 175), True, 'import tensorflow as tf\n'), ((504, 546), 'tensorf... |
import discord
from discord.ext import commands
from datetime import datetime
import time
#It infuriates me that this module has to be imported; I can't find a way to handle lengths of audio files natively in discord.py, so this was the only implementation I could find that didn't involve manually checking the lengths... | [
"mutagen.mp3.MP3",
"discord.FFmpegPCMAudio",
"datetime.datetime.now",
"discord.ext.commands.command"
] | [((1225, 1252), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""dc"""'}), "(name='dc')\n", (1241, 1252), False, 'from discord.ext import commands\n'), ((2922, 2953), 'discord.ext.commands.command', 'commands.command', ([], {'name': '"""shutup"""'}), "(name='shutup')\n", (2938, 2953), False, 'from ... |
from conta_corrente import ContaCorrente
from class_cliente import Cliente
contas = []
def menu():
print()
print('Banco A - Gestão de Contas')
print('1- Criar Conta; 2- Depositar; 3- Levantar; 4- Consultar; 5-Consultar conta; 6- Eliminar conta 9- Sair')
return int(input('Ação: '))
opcao = 0
while ... | [
"class_cliente.Cliente",
"conta_corrente.ContaCorrente"
] | [((558, 576), 'class_cliente.Cliente', 'Cliente', (['nome', 'NIF'], {}), '(nome, NIF)\n', (565, 576), False, 'from class_cliente import Cliente\n'), ((595, 642), 'conta_corrente.ContaCorrente', 'ContaCorrente', (['numero_de_conta', 'cliente1', 'saldo'], {}), '(numero_de_conta, cliente1, saldo)\n', (608, 642), False, 'f... |
import pytest
from stock_indicators import indicators
class TestVortex:
def test_standard(self, quotes):
results = indicators.get_vortex(quotes, 14)
assert 502 == len(results)
assert 488 == len(list(filter(lambda x: x.pvi is not None, results)))
r = results[13]
... | [
"pytest.raises",
"stock_indicators.indicators.get_vortex"
] | [((128, 161), 'stock_indicators.indicators.get_vortex', 'indicators.get_vortex', (['quotes', '(14)'], {}), '(quotes, 14)\n', (149, 161), False, 'from stock_indicators import indicators\n'), ((955, 992), 'stock_indicators.indicators.get_vortex', 'indicators.get_vortex', (['bad_quotes', '(20)'], {}), '(bad_quotes, 20)\n'... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-04 01:58
from __future__ import unicode_literals
from django.db import migrations, models
from qatrack.qa.models import BOOLEAN
from qatrack.qa.utils import get_bool_tols, get_internal_user
def create_bool_tolerances(apps, schema):
Tolerance = app... | [
"qatrack.qa.utils.get_internal_user",
"django.db.migrations.RunPython",
"qatrack.qa.utils.get_bool_tols",
"django.db.models.BooleanField"
] | [((398, 421), 'qatrack.qa.utils.get_internal_user', 'get_internal_user', (['User'], {}), '(User)\n', (415, 421), False, 'from qatrack.qa.utils import get_bool_tols, get_internal_user\n'), ((427, 457), 'qatrack.qa.utils.get_bool_tols', 'get_bool_tols', (['User', 'Tolerance'], {}), '(User, Tolerance)\n', (440, 457), Fals... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'design.ui'
#
# Created: Tue Jun 14 16:57:25 2016
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except Attribu... | [
"PyQt4.QtGui.QWidget",
"PyQt4.QtCore.QMetaObject.connectSlotsByName",
"PyQt4.QtGui.QLabel",
"PyQt4.QtGui.QApplication.translate",
"PyQt4.QtGui.QHBoxLayout"
] | [((481, 545), 'PyQt4.QtGui.QApplication.translate', 'QtGui.QApplication.translate', (['context', 'text', 'disambig', '_encoding'], {}), '(context, text, disambig, _encoding)\n', (509, 545), False, 'from PyQt4 import QtCore, QtGui\n'), ((872, 897), 'PyQt4.QtGui.QWidget', 'QtGui.QWidget', (['MainWindow'], {}), '(MainWind... |
import re
GOLD = "shiny gold"
def get_shiny_golds(filename="data/day7.dat"):
with open(filename) as fdata:
graph = {}
gold_parents = set()
for line in fdata:
line_split = line.replace("\n", "").split(" bags contain ")
leaves = line_split[1].split(", ") if line_sp... | [
"re.sub"
] | [((1410, 1432), 're.sub', 're.sub', (['""" (.*)"""', '""""""', 'l'], {}), "(' (.*)', '', l)\n", (1416, 1432), False, 'import re\n'), ((431, 459), 're.sub', 're.sub', (['""" (bags|bag)"""', '""""""', 'l'], {}), "(' (bags|bag)', '', l)\n", (437, 459), False, 'import re\n'), ((1194, 1222), 're.sub', 're.sub', (['""" (bags... |
import unittest
from sum_lists import Linked_List, Node, sum_lists_bwd, sum_lists_fwd
class Test_Case_Sum_Lists_Bwd_fwd(unittest.TestCase):
def test_sum_lists_bwd(self):
list_1 = Linked_List(None)
list_1.head = Node(7)
list_1.head.next = Node(1)
list_1.head.next.next = Node(6)
... | [
"sum_lists.Linked_List",
"sum_lists.sum_lists_fwd",
"sum_lists.Node",
"unittest.main",
"sum_lists.sum_lists_bwd"
] | [((1334, 1349), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1347, 1349), False, 'import unittest\n'), ((192, 209), 'sum_lists.Linked_List', 'Linked_List', (['None'], {}), '(None)\n', (203, 209), False, 'from sum_lists import Linked_List, Node, sum_lists_bwd, sum_lists_fwd\n'), ((232, 239), 'sum_lists.Node', 'N... |
import string
import pandas as pd
import numpy as np
MODEL_RUN_SCRIPT_PREFIX='''
from System import Array
import TIME.DataTypes.TimeStep as TimeStep
import TIME.DataTypes.TimeSeries as TimeSeries
import System.DateTime as DateTime
import ${namespace}.${klass} as ${klass}
import TIME.Tools.ModelRunner as ModelRunner
mo... | [
"pandas.DataFrame",
"numpy.array",
"string.Template"
] | [((455, 471), 'numpy.array', 'np.array', (['series'], {}), '(series)\n', (463, 471), True, 'import numpy as np\n'), ((1784, 1824), 'string.Template', 'string.Template', (['MODEL_RUN_SCRIPT_PREFIX'], {}), '(MODEL_RUN_SCRIPT_PREFIX)\n', (1799, 1824), False, 'import string\n'), ((2930, 2961), 'pandas.DataFrame', 'pd.DataF... |
import re
from collections import Counter
txtfile = "d4.txt"
examples1 = [
"aaaaa-bbb-z-y-x-123[abxyz]",
"a-b-c-d-e-f-g-h-987[abcde]",
"not-a-real-room-404[oarel]",
"totally-real-room-200[decoy]"
]
examples2 = ["qzmt-zixmtkozy-ivhz-343"]
def day_a(test=False):
if test:
inputs = examples1
else:
inputs = op... | [
"collections.Counter",
"re.match"
] | [((468, 487), 're.match', 're.match', (['patt', 'imp'], {}), '(patt, imp)\n', (476, 487), False, 'import re\n'), ((585, 601), 'collections.Counter', 'Counter', (['encname'], {}), '(encname)\n', (592, 601), False, 'from collections import Counter\n'), ((1057, 1076), 're.match', 're.match', (['patt', 'imp'], {}), '(patt,... |
import re
from os import environ
from github import Github
from github.GitRelease import GitRelease
GITHUB_REPOSITORY = environ.get("GITHUB_REPOSITORY", "awtkns/fastapi-crudrouter")
GITHUB_TOKEN = environ.get("GH_TOKEN") or environ.get("GITHUB_TOKEN")
GITHUB_URL = "https://github.com"
GITHUB_BRANCH = "master"
FILE_PA... | [
"re.sub",
"os.environ.get",
"github.Github"
] | [((122, 183), 'os.environ.get', 'environ.get', (['"""GITHUB_REPOSITORY"""', '"""awtkns/fastapi-crudrouter"""'], {}), "('GITHUB_REPOSITORY', 'awtkns/fastapi-crudrouter')\n", (133, 183), False, 'from os import environ\n'), ((404, 424), 'github.Github', 'Github', (['GITHUB_TOKEN'], {}), '(GITHUB_TOKEN)\n', (410, 424), Fal... |
#!/pygame_snake_oop/bin python
import pygame
from random import randint
from time import sleep
class Snake():
def __init__(self, screen_width, screen_height):
self.snake_ate = 0
self.snake_life = 'alive'
self.snake_direction = 'rigth'
self.snake_body = [[10, 30], [10, 20], [10, 10]]
self.snake_color = (... | [
"pygame.init",
"pygame.quit",
"pygame.event.get",
"pygame.display.set_mode",
"time.sleep",
"pygame.Rect",
"pygame.time.Clock",
"pygame.display.update",
"random.randint"
] | [((2576, 2611), 'random.randint', 'randint', (['(1)', '(self.screen_height / 10)'], {}), '(1, self.screen_height / 10)\n', (2583, 2611), False, 'from random import randint\n'), ((2628, 2662), 'random.randint', 'randint', (['(1)', '(self.screen_width / 10)'], {}), '(1, self.screen_width / 10)\n', (2635, 2662), False, 'f... |
# coding=utf-8
from unittest import TestCase
from click.testing import CliRunner
import mock
import yoda
from requests.models import Response
class TestChecksite(TestCase):
"""
Test for the following commands:
| Module: dev
| command: checksite
"""
def __init__(self, methodName=... | [
"requests.models.Response",
"mock.patch",
"click.testing.CliRunner"
] | [((400, 411), 'click.testing.CliRunner', 'CliRunner', ([], {}), '()\n', (409, 411), False, 'from click.testing import CliRunner\n'), ((462, 472), 'requests.models.Response', 'Response', ([], {}), '()\n', (470, 472), False, 'from requests.models import Response\n'), ((997, 1053), 'mock.patch', 'mock.patch', (['"""reques... |
# coding=utf-8
# this file colect all the needed data to applys Dupont model
# use the same pattern in the csv structure to works porperly with your data
import pandas as pd
def financial():
financial_data = pd.read_csv("financial_data.csv")
return(financial_data)
def ipca():
ipca = pd.read_csv("ipca.... | [
"pandas.read_csv"
] | [((217, 250), 'pandas.read_csv', 'pd.read_csv', (['"""financial_data.csv"""'], {}), "('financial_data.csv')\n", (228, 250), True, 'import pandas as pd\n'), ((302, 346), 'pandas.read_csv', 'pd.read_csv', (['"""ipca.csv"""'], {'index_col': '"""Mês/Ano"""'}), "('ipca.csv', index_col='Mês/Ano')\n", (313, 346), True, 'impor... |
# Code for CVPR'21 paper:
# [Title] - "CoLA: Weakly-Supervised Temporal Action Localization with Snippet Contrastive Learning"
# [Author] - <NAME>*, <NAME>, <NAME>, <NAME> and <NAME>
# [Github] - https://github.com/zhang-can/CoLA
import numpy as np
import os
from easydict import EasyDict as edict
cfg = edict()
cfg.... | [
"easydict.EasyDict",
"numpy.linspace",
"os.path.join",
"numpy.arange"
] | [((307, 314), 'easydict.EasyDict', 'edict', ([], {}), '()\n', (312, 314), True, 'from easydict import EasyDict as edict\n'), ((696, 723), 'numpy.arange', 'np.arange', (['(0.0)', '(0.25)', '(0.025)'], {}), '(0.0, 0.25, 0.025)\n', (705, 723), True, 'import numpy as np\n'), ((743, 771), 'numpy.arange', 'np.arange', (['(0.... |
import io
import sys
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import yaml
from scipy.optimize import curve_fit
from scipy.signal import savgol_filter
# if compact printing is required
np.set_printoptions(precision=2)
def friction_func(xdot, mass, mu, damping):
return np.sign(xdot) *... | [
"scipy.optimize.curve_fit",
"pandas.read_csv",
"numpy.set_printoptions",
"matplotlib.pyplot.plot",
"scipy.signal.savgol_filter",
"io.open",
"numpy.diff",
"matplotlib.pyplot.figure",
"numpy.sign",
"matplotlib.pyplot.title",
"pandas.Series.str",
"matplotlib.pyplot.show"
] | [((216, 248), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(2)'}), '(precision=2)\n', (235, 248), True, 'import numpy as np\n'), ((2998, 3051), 'pandas.read_csv', 'pd.read_csv', (["config['low_mass_file_1']"], {'delimiter': '""","""'}), "(config['low_mass_file_1'], delimiter=',')\n", (3009, 3051... |
""" Module for scheduling different tasks using package apscheduler. """
import requests
from apscheduler.schedulers.blocking import BlockingScheduler
class Dinger:
def __init__(self, api_url, msg, start_date, trigger='cron', hour='0-23', minute='0-59', second='0-59'):
self.api_url = api_url
self... | [
"apscheduler.schedulers.blocking.BlockingScheduler",
"requests.post"
] | [((353, 372), 'apscheduler.schedulers.blocking.BlockingScheduler', 'BlockingScheduler', ([], {}), '()\n', (370, 372), False, 'from apscheduler.schedulers.blocking import BlockingScheduler\n'), ((584, 626), 'requests.post', 'requests.post', (['self.api_url'], {'json': 'self.msg'}), '(self.api_url, json=self.msg)\n', (59... |
import socket
def nslookup_func(address):
result =""
try:
result_list = socket.gethostbyaddr(address)
result += result_list[0]
except:
result += "NO RESULTS FOUND"
return result | [
"socket.gethostbyaddr"
] | [((90, 119), 'socket.gethostbyaddr', 'socket.gethostbyaddr', (['address'], {}), '(address)\n', (110, 119), False, 'import socket\n')] |
from webpage import app
from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, FloatField, SubmitField, ValidationError
from wtforms.validators import DataRequired, NumberRange
import yfinance as yf
def validate_ticker(self, ticker):
ticker = yf.Ti... | [
"wtforms.validators.NumberRange",
"wtforms.ValidationError",
"wtforms.SubmitField",
"yfinance.Ticker",
"wtforms.validators.DataRequired"
] | [((315, 337), 'yfinance.Ticker', 'yf.Ticker', (['ticker.data'], {}), '(ticker.data)\n', (324, 337), True, 'import yfinance as yf\n'), ((1042, 1069), 'wtforms.SubmitField', 'SubmitField', ([], {'label': '"""Submit"""'}), "(label='Submit')\n", (1053, 1069), False, 'from wtforms import StringField, IntegerField, FloatFiel... |
# Copyright ClusterHQ Inc. See LICENSE file for details.
"""
Tests for :module:`admin.merge_pr`.
"""
import os
import subprocess
from hypothesis import given
from hypothesis.strategies import (
booleans,
dictionaries,
fixed_dictionaries,
just,
lists,
one_of,
sampled_from,
text,
)
... | [
"hypothesis.strategies.fixed_dictionaries",
"admin.merge_pr.pr_api_url_from_web_url",
"admin.merge_pr.format_status",
"pyrsistent.pmap",
"hypothesis.strategies.lists",
"hypothesis.strategies.sampled_from",
"admin.merge_pr.not_success",
"admin.merge_pr.url_path",
"hypothesis.strategies.booleans",
"... | [((652, 697), 'subprocess.check_output', 'subprocess.check_output', (['([SCRIPT_FILE] + args)'], {}), '([SCRIPT_FILE] + args)\n', (675, 697), False, 'import subprocess\n'), ((2890, 2914), 'hypothesis.strategies.fixed_dictionaries', 'fixed_dictionaries', (['base'], {}), '(base)\n', (2908, 2914), False, 'from hypothesis.... |
import numpy as np
import os, pickle
from tqdm import tqdm
def get_word_emb(word2coef_dict, word, default_value):
return word2coef_dict.get(word, default_value)
def get_phrase_emb(word2coef_dict, phrase, default_value):
words = phrase.split(' ')
embs = [ get_word_emb(word2coef_dict, word, default_value) fo... | [
"numpy.mean",
"pickle.dump",
"os.path.join",
"numpy.asarray",
"numpy.zeros"
] | [((349, 370), 'numpy.mean', 'np.mean', (['embs'], {'axis': '(0)'}), '(embs, axis=0)\n', (356, 370), True, 'import numpy as np\n'), ((534, 550), 'numpy.zeros', 'np.zeros', (['(300,)'], {}), '((300,))\n', (542, 550), True, 'import numpy as np\n'), ((999, 1029), 'pickle.dump', 'pickle.dump', (['word2coef_dict', 'f'], {}),... |
import re
from pathlib import Path
import torch
import pandas as pd
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
import sklearn.preprocessing
from sklearn.preprocessing import StandardScaler
from sklearn.feature_extraction.text import CountVectorizer
from nltk.corpus import stopword... | [
"nltk.corpus.stopwords.words",
"pandas.read_csv",
"pathlib.Path",
"sklearn.feature_extraction.text.CountVectorizer",
"sklearn.model_selection.train_test_split",
"libs.utils.load_pickle",
"sklearn.preprocessing.StandardScaler",
"torch.tensor",
"nltk.stem.porter.PorterStemmer",
"bs4.BeautifulSoup",
... | [((3006, 3022), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (3020, 3022), False, 'from sklearn.preprocessing import StandardScaler\n'), ((3911, 3934), 'pandas.read_csv', 'pd.read_csv', (['train_path'], {}), '(train_path)\n', (3922, 3934), True, 'import pandas as pd\n'), ((3950, 3972), 'p... |
import REGIR as gil
""" --------------------------------------------------------------------------------------------
2 reactions:
ESC -> EPI, differentiation
EPI -> NPC, differentiation
"""
class param:
Tend = 170
unit = 'h'
N_simulations = 20
timepoints = 100
def main():
pr... | [
"REGIR.Gillespie_simulation",
"REGIR.Reaction_channel"
] | [((907, 1037), 'REGIR.Reaction_channel', 'gil.Reaction_channel', (['param'], {'rate': 'r_diffAB', 'shape_param': 'alpha_diffAB', 'distribution': '"""Gamma"""', 'name': '"""Differentiation: ESC -> EPI"""'}), "(param, rate=r_diffAB, shape_param=alpha_diffAB,\n distribution='Gamma', name='Differentiation: ESC -> EPI')\... |
#!/usr/bin/python3
# Copyright 2018 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | [
"os.path.exists",
"os.listdir",
"random.shuffle",
"subprocess.Popen",
"os.path.join",
"io.open",
"os.mkdir",
"tflmlib.ProgressBar"
] | [((1147, 1204), 'os.path.join', 'os.path.join', (['config.bw_corpus', '"""BWUniqueSents_FirstPass"""'], {}), "(config.bw_corpus, 'BWUniqueSents_FirstPass')\n", (1159, 1204), False, 'import os\n'), ((1276, 1328), 'subprocess.Popen', 'Popen', (["['wc', '-l', fname]"], {'stdout': 'PIPE', 'stderr': 'PIPE'}), "(['wc', '-l',... |
import string
from utils.iter import remove_consecs
__all__ = ['snake_to_camel', 'camel_to_snake', 'to_all_caps', 'snake_to_capwords', 'snake_case', 'camel_to_capwords']
def snake_case(s: str) -> str:
"""Convert string into snake case.
Join punctuation (-, space, .) with underscore
Args:
string... | [
"doctest.testmod",
"utils.iter.remove_consecs"
] | [((4642, 4659), 'doctest.testmod', 'doctest.testmod', ([], {}), '()\n', (4657, 4659), False, 'import doctest\n'), ((640, 664), 'utils.iter.remove_consecs', 'remove_consecs', (['lst', '"""_"""'], {}), "(lst, '_')\n", (654, 664), False, 'from utils.iter import remove_consecs\n')] |
from pathlib import PurePath
from typing import Callable
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from labml import lab, experiment, monit, logger, tracker
from labml.configs import option
from labml.logger import Text
from labml_helpers.datasets.text import TextDataset, SequentialDa... | [
"labml.monit.iterate",
"torch.nn.CrossEntropyLoss",
"labml.experiment.start",
"labml_helpers.device.DeviceConfigs",
"labml.lab.get_data_path",
"labml.tracker.set_scalar",
"python_autocomplete.models.transformer.TransformerModel",
"labml.utils.cache.cache",
"labml_nn.optimizers.configs.OptimizerConfi... | [((2938, 2965), 'labml.configs.option', 'option', (['Configs.transformer'], {}), '(Configs.transformer)\n', (2944, 2965), False, 'from labml.configs import option\n'), ((3212, 3237), 'labml.configs.option', 'option', (['Configs.optimizer'], {}), '(Configs.optimizer)\n', (3218, 3237), False, 'from labml.configs import o... |
from __future__ import unicode_literals
import re
from django.core.exceptions import ImproperlyConfigured
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from wagtail.contrib.modeladmin.options import ModelAdmin as WagtailModelAdmin
from .actions import ( # noqa
... | [
"django.utils.encoding.force_text",
"django.utils.translation.ugettext_lazy",
"django.core.exceptions.ImproperlyConfigured",
"re.compile"
] | [((1056, 1090), 'django.utils.encoding.force_text', 'force_text', (['self.opts.verbose_name'], {}), '(self.opts.verbose_name)\n', (1066, 1090), False, 'from django.utils.encoding import force_text\n'), ((1124, 1165), 'django.utils.encoding.force_text', 'force_text', (['self.opts.verbose_name_plural'], {}), '(self.opts.... |
import tensorflow as tf
from tensorflow.keras.regularizers import l2
class ModelWrapper:
def __init__(self):
inputs = tf.keras.layers.Input(shape=(48, 48, 3))
x = tf.keras.layers.experimental.preprocessing.Rescaling(1./255)(inputs)
x = tf.keras.layers.Conv2D(64, 3, padding="same", kernel_re... | [
"tensorflow.keras.applications.VGG16",
"tensorflow.keras.layers.Input",
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"tensorflow.keras.layers.experimental.preprocessing.Rescaling",
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.preprocessing.image_data... | [((1432, 1550), 'tensorflow.keras.preprocessing.image_dataset_from_directory', 'tf.keras.preprocessing.image_dataset_from_directory', (['"""./data/train"""'], {'seed': '(123)', 'image_size': '(48, 48)', 'batch_size': '(32)'}), "('./data/train', seed=\n 123, image_size=(48, 48), batch_size=32)\n", (1483, 1550), True,... |
# Generated by Django 2.0.5 on 2018-07-28 09:15
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('auditlog', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='auditlog',
options={'permissions': (('view_... | [
"django.db.migrations.AlterModelOptions"
] | [((217, 335), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOptions', ([], {'name': '"""auditlog"""', 'options': "{'permissions': (('view_auditlog', 'Can view auditlog'),)}"}), "(name='auditlog', options={'permissions': ((\n 'view_auditlog', 'Can view auditlog'),)})\n", (245, 335), False, 'from dja... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 26 13:29:13 2017
@author: amirs
"""
# Artificial Neural Network
# Installing Theano
# pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git
# Installing Tensorflow
# Install Tensorflow from the website: https://www.tensorflow.org/versions/r0.12/get_sta... | [
"sklearn.preprocessing.LabelEncoder",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.preprocessing.Imputer",
"keras.utils.to_categorical",
"sklearn.preprocessing.StandardScaler",
"keras.models.Sequential",
"numpy.concatenate",
"keras.layers.Dense",
"sklearn.metrics.confusi... | [((554, 622), 'pandas.read_csv', 'pd.read_csv', (['"""features/Table_Step2_159Features-85Subs-5Levels-z.csv"""'], {}), "('features/Table_Step2_159Features-85Subs-5Levels-z.csv')\n", (565, 622), True, 'import pandas as pd\n'), ((709, 763), 'sklearn.preprocessing.Imputer', 'Imputer', ([], {'missing_values': '"""NaN"""', ... |
from __future__ import print_function
import sys
import os
import re
def getColumnNameAndType(s):
d = ''
index = 0
index2 = s.find(' ', index+1 )
s2 = s[index2 + 1:].strip()
index3 = s2.find(' ')
n = s[index:index2]
t = s2[:index3]
index_default = s.find(... | [
"re.split",
"os.listdir",
"re.search"
] | [((1559, 1575), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (1569, 1575), False, 'import os\n'), ((458, 482), 're.search', 're.search', (['"""[a-zA-Z]"""', 's'], {}), "('[a-zA-Z]', s)\n", (467, 482), False, 'import re\n'), ((4245, 4287), 're.split', 're.split', (['""",(?![0-9])"""', 'columnsAndTypesStr'], {... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from fairseq.tasks import register_task
from fairseq.tasks.joint_task import JointTrainingTask
logger = logging.getLogger(__... | [
"logging.getLogger",
"fairseq.tasks.register_task",
"fairseq.tasks.joint_task.JointTrainingTask.add_args"
] | [((300, 327), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (317, 327), False, 'import logging\n'), ((331, 363), 'fairseq.tasks.register_task', 'register_task', (['"""joint_task_mtst"""'], {}), "('joint_task_mtst')\n", (344, 363), False, 'from fairseq.tasks import register_task\n'), ((54... |
# MIT License
#
# Copyright (c) 2020 Gcom
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish... | [
"manager.basic.letter.NotifyLetter"
] | [((2615, 2662), 'manager.basic.letter.NotifyLetter', 'NotifyLetter', (['self.who', 'self.type', 'self.content'], {}), '(self.who, self.type, self.content)\n', (2627, 2662), False, 'from manager.basic.letter import NotifyLetter\n')] |
import chardet
import csv
from dateutil.parser import parse
def get_encoding(ds_path: str) -> str:
""" Returns the encoding of the file """
test_str = b''
number_of_lines_to_read = 500
count = 0
with open(ds_path, 'rb') as f:
line = f.readline()
while line and count < number_of_lin... | [
"csv.Sniffer",
"chardet.detect"
] | [((443, 467), 'chardet.detect', 'chardet.detect', (['test_str'], {}), '(test_str)\n', (457, 467), False, 'import chardet\n'), ((740, 753), 'csv.Sniffer', 'csv.Sniffer', ([], {}), '()\n', (751, 753), False, 'import csv\n')] |
import sys
import os.path
import logging
import asyncio
from ._requires import click
from .http import HTTPError
log = logging.getLogger(__name__)
class _VolumeBinds:
def visit(self, obj):
return obj.accept(self)
def visit_RO(self, _):
return 'ro'
def visit_RW(self, _):
retu... | [
"logging.getLogger",
"asyncio.get_running_loop"
] | [((123, 150), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (140, 150), False, 'import logging\n'), ((3673, 3699), 'asyncio.get_running_loop', 'asyncio.get_running_loop', ([], {}), '()\n', (3697, 3699), False, 'import asyncio\n')] |
"""
Simulate server load under a few scenarios.
Sample usage:
locust --host=http://staging.locuszoom.org
To run web UI, see: https://docs.locust.io/en/stable/quickstart.html#open-up-locust-s-web-interface
Eg, from local machine, visit: http://127.0.0.1:8089/
**PLEASE DO NOT RUN ROUTINE LOAD TESTING AGAIN... | [
"locust.task"
] | [((977, 984), 'locust.task', 'task', (['(1)'], {}), '(1)\n', (981, 984), False, 'from locust import HttpLocust, TaskSet, task\n'), ((1041, 1048), 'locust.task', 'task', (['(2)'], {}), '(2)\n', (1045, 1048), False, 'from locust import HttpLocust, TaskSet, task\n'), ((1260, 1267), 'locust.task', 'task', (['(2)'], {}), '(... |
from django.urls import path
from . import views
app_name = 'education'
urlpatterns = [
path('', views.education, name='education')
] | [
"django.urls.path"
] | [((94, 137), 'django.urls.path', 'path', (['""""""', 'views.education'], {'name': '"""education"""'}), "('', views.education, name='education')\n", (98, 137), False, 'from django.urls import path\n')] |
from utils import import_submodules
_registered_single_sampler = {}
_registered_multi_sampler = {}
def register_multi_sampler(name):
"""
A decorator with a parameter.
This decorator returns a function which the class is passed.
"""
name = name.lower()
def _register(sampler):
if name i... | [
"utils.import_submodules"
] | [((1786, 1815), 'utils.import_submodules', 'import_submodules', (['"""samplers"""'], {}), "('samplers')\n", (1803, 1815), False, 'from utils import import_submodules\n')] |
import re
# SSG Makefile to official product name mapping
CHROMIUM = 'Google Chromium Browser'
FEDORA = 'Fedora'
FIREFOX = 'Mozilla Firefox'
JRE = 'Java Runtime Environment'
RHEL = 'Red Hat Enterprise Linux'
WEBMIN = 'Webmin'
DEBIAN = 'Debian'
UBUNTU = 'Ubuntu'
RHEVM = 'Red Hat Enterprise Virtualization Manager'
EAP =... | [
"re.compile"
] | [((611, 647), 're.compile', 're.compile', (['"""([a-zA-Z\\\\-]+)([0-9]+)"""'], {}), "('([a-zA-Z\\\\-]+)([0-9]+)')\n", (621, 647), False, 'import re\n')] |
from datetime import datetime, timedelta, time
from flask import current_app
from app.extensions import db
from app.data_analysis.models import DailyOEE
from app.default.models import Activity, ActivityCode, ScheduledActivity, MachineGroup
from app.default.db_helpers import get_machine_activities, get_user_activities... | [
"app.default.db_helpers.get_machine_activities",
"flask.current_app.logger.warn",
"app.data_analysis.models.DailyOEE.query.filter_by",
"datetime.datetime.fromtimestamp",
"datetime.time",
"app.extensions.db.session.commit",
"app.default.models.ScheduledActivity.query.filter",
"app.default.db_helpers.ge... | [((2603, 2627), 'app.default.models.ActivityCode.query.all', 'ActivityCode.query.all', ([], {}), '()\n', (2625, 2627), False, 'from app.default.models import Activity, ActivityCode, ScheduledActivity, MachineGroup\n'), ((1654, 1756), 'app.default.db_helpers.get_user_activities', 'get_user_activities', ([], {'user_id': ... |
import numpy as np
import pandas as pd
import cvxopt as opt
from cvxopt import solvers #, blas
from matplotlib import pyplot as plt
plt.style.use('seaborn')
np.random.seed(9062020)
# Cargar y limpiar datos
df = pd.read_csv("stocks.csv", sep=",", engine="python")
#���Field 1 la columna tiene caracteres extranios
df.... | [
"numpy.sqrt",
"pandas.read_csv",
"matplotlib.pyplot.ylabel",
"numpy.log",
"numpy.array",
"numpy.random.binomial",
"numpy.where",
"numpy.random.random",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"numpy.asarray",
"matplotlib.pyplot.style.use",
"numpy.random.seed",
"matplotlib.pyp... | [((134, 158), 'matplotlib.pyplot.style.use', 'plt.style.use', (['"""seaborn"""'], {}), "('seaborn')\n", (147, 158), True, 'from matplotlib import pyplot as plt\n'), ((159, 182), 'numpy.random.seed', 'np.random.seed', (['(9062020)'], {}), '(9062020)\n', (173, 182), True, 'import numpy as np\n'), ((215, 266), 'pandas.rea... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["Parameter", "UnitVector", "Model"]
import numpy as np
import tensorflow as tf
def get_param_for_value(value, min_value, max_value):
if ((min_value is not None and np.any(value <= min_value)) or
(max_value is not Non... | [
"numpy.reshape",
"tensorflow.Variable",
"tensorflow.reduce_sum",
"numpy.size",
"numpy.log",
"tensorflow.get_default_session",
"numpy.any",
"tensorflow.gradients",
"tensorflow.sqrt",
"numpy.empty",
"tensorflow.name_scope",
"tensorflow.constant",
"tensorflow.square",
"numpy.shape",
"tensor... | [((568, 593), 'numpy.log', 'np.log', (['(value - min_value)'], {}), '(value - min_value)\n', (574, 593), True, 'import numpy as np\n'), ((642, 667), 'numpy.log', 'np.log', (['(max_value - value)'], {}), '(max_value - value)\n', (648, 667), True, 'import numpy as np\n'), ((4993, 5035), 'tensorflow.gradients', 'tf.gradie... |
from django.core.exceptions import ValidationError
from django.core.mail import send_mail
from django.forms import EmailField
from django.http import HttpResponse
from django.utils.html import strip_tags
from django.views.generic import TemplateView
from core.models import (About, Carousel, Contact, ContactEmail, Pack... | [
"core.models.Carousel.objects.filter",
"core.models.Testimonial.objects.filter",
"core.models.WebsiteConfig.objects.filter",
"core.models.Service.objects.filter",
"core.models.Social.objects.filter",
"core.models.ContactEmail.objects.filter",
"django.forms.EmailField",
"core.models.Contact.objects.fil... | [((3611, 3647), 'django.http.HttpResponse', 'HttpResponse', (['message'], {'status': 'status'}), '(message, status=status)\n', (3623, 3647), False, 'from django.http import HttpResponse\n'), ((1181, 1222), 'core.models.Product.objects.filter', 'Product.objects.filter', ([], {'is_published': '(True)'}), '(is_published=T... |
import cmath
import itertools
import math
import typing
import unittest.mock as mock
import hypothesis
import hypothesis.strategies as st
import pytest
import twelvefactor
# Generate all possible case permutations of the strings in TRUE_STRINGS
TRUE_STRINGS = [
v
for s in twelvefactor.Config.TRUE_STRINGS
... | [
"hypothesis.strategies.text",
"hypothesis.strategies.sampled_from",
"hypothesis.strategies.integers",
"hypothesis.strategies.floats",
"cmath.isnan",
"twelvefactor.Config",
"pytest.raises",
"hypothesis.strategies.booleans",
"hypothesis.strategies.complex_numbers",
"math.isnan"
] | [((602, 623), 'twelvefactor.Config', 'twelvefactor.Config', ([], {}), '()\n', (621, 623), False, 'import twelvefactor\n'), ((881, 902), 'twelvefactor.Config', 'twelvefactor.Config', ([], {}), '()\n', (900, 902), False, 'import twelvefactor\n'), ((1128, 1149), 'twelvefactor.Config', 'twelvefactor.Config', ([], {}), '()\... |
#!/usr/bin/env python3
"""
Extract content of different types of tag from an html or xml file matching
regular expressions and save the output to a file.
There are other methods but this can be used to use more powerful regex.
"""
import re
source_file = 'source.html'
destination_file = 'output.html'
f = open(source_f... | [
"re.compile"
] | [((364, 441), 're.compile', 're.compile', (['"""<a href="(.*?)".*?(?:title="(.*?)").*?>(.*?)</a>|<li>(.*?)</li>"""'], {}), '(\'<a href="(.*?)".*?(?:title="(.*?)").*?>(.*?)</a>|<li>(.*?)</li>\')\n', (374, 441), False, 'import re\n')] |
import math
def kld(P,Q):
assert len(P) == len(Q)
sum_dkl = 0
for i in range(0, len(P)):
if(P[i] != 0):
term_dkl = P[i]*math.log(P[i]/Q[i],2)
else :
term_dkl = 0
sum_dkl += term_dkl
return sum_dkl
| [
"math.log"
] | [((157, 181), 'math.log', 'math.log', (['(P[i] / Q[i])', '(2)'], {}), '(P[i] / Q[i], 2)\n', (165, 181), False, 'import math\n')] |
import asyncio
import time
import os
import datetime
import traceback
import shlex
import argparse
import logging
import discord
from discord.ext import commands
from i18n import Translator
from Utils import Logging, Utils, PermCheckers
from Utils.Converters import DiscordUser, Duration, RangedInt
from Utils.Constant... | [
"logging.getLogger",
"discord.ext.commands.has_permissions",
"Database.DBUtils.update",
"shlex.split",
"discord.ext.commands.group",
"discord.Object",
"i18n.Translator.translate",
"datetime.timedelta",
"discord.ext.commands.command",
"discord.ext.commands.MemberConverter",
"discord.ext.commands.... | [((575, 602), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (592, 602), False, 'import logging\n'), ((610, 630), 'Database.Connector.Database', 'Connector.Database', ([], {}), '()\n', (628, 630), False, 'from Database import Connector, DBUtils\n'), ((889, 910), 'discord.ext.commands.guil... |
# Last modified by: <NAME>
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | [
"argparse.ArgumentParser",
"tensorflow.keras.callbacks.LearningRateScheduler",
"tensorflow.contrib.saved_model.save_keras_model",
"os.path.join",
"tensorflow.logging.set_verbosity"
] | [((997, 1022), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1020, 1022), False, 'import argparse\n'), ((2588, 2708), 'tensorflow.keras.callbacks.LearningRateScheduler', 'tf.keras.callbacks.LearningRateScheduler', (['(lambda epoch: args.learning_rate + 0.02 * 0.5 ** (1 + epoch))'], {'verbose'... |