code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import requests
HUB_LOCATION = 'http://hub.wattbike.com/ranking/getSessionRows?sessionId='
class HubClient:
def __init__(self, location=None):
self.location = location if location else HUB_LOCATION
def _validate_session_id(self, session_id):
# TODO: add regex validation of session_id
... | [
"requests.HTTPError",
"requests.get"
] | [((471, 496), 'requests.get', 'requests.get', (['session_url'], {}), '(session_url)\n', (483, 496), False, 'import requests\n'), ((551, 600), 'requests.HTTPError', 'requests.HTTPError', (['"""Response status code != 200"""'], {}), "('Response status code != 200')\n", (569, 600), False, 'import requests\n')] |
#!/usr/bin/env python
"""
Copyright (c) 2018 <NAME> GmbH
All rights reserved.
This source code is licensed under the BSD-3-Clause license found in the
LICENSE file in the root directory of this source tree.
@author: <NAME>
"""
from geometry_msgs.msg import TransformStamped
from roadmap_planner_tools.planner_input_ma... | [
"geometry_msgs.msg.TransformStamped",
"roadmap_planning_common_msgs.msg.StringList",
"rospy_message_converter.json_message_converter.convert_json_to_ros_message",
"roadmap_planning_common_msgs.msg.OrderedVisitingConstraint",
"roadmap_planner_tools.planner_input_manager.PlannerInputManager"
] | [((4221, 4242), 'roadmap_planner_tools.planner_input_manager.PlannerInputManager', 'PlannerInputManager', ([], {}), '()\n', (4240, 4242), False, 'from roadmap_planner_tools.planner_input_manager import PlannerInputManager\n'), ((4256, 4274), 'geometry_msgs.msg.TransformStamped', 'TransformStamped', ([], {}), '()\n', (4... |
import re
def find_key(keyString):
k = PyKeyboard()
key_to_press = None
highest = 0
for each in dir(k):
if each.endswith("_key"):
if similar(keyString + "_key" ,each) > highest:
highest = similar(keyString + "_key" ,each)
key_to_press = getattr(k,each)... | [
"re.match",
"re.finditer"
] | [((1784, 1810), 're.finditer', 're.finditer', (['regex', 'string'], {}), '(regex, string)\n', (1795, 1810), False, 'import re\n'), ((1329, 1360), 're.match', 're.match', (['regex', 'working_string'], {}), '(regex, working_string)\n', (1337, 1360), False, 'import re\n')] |
# Exercícios Numpy-27
# *******************
import numpy as np
Z=np.arange((10),dtype=int)
print(Z**Z)
print(Z)
print(2<<Z>>2)
print()
print(Z <- Z)
print()
print(1j*Z)
print()
print(Z/1/1)
print()
#print(Z<Z>Z) | [
"numpy.arange"
] | [((66, 90), 'numpy.arange', 'np.arange', (['(10)'], {'dtype': 'int'}), '(10, dtype=int)\n', (75, 90), True, 'import numpy as np\n')] |
import copy
from .coco import CocoDataset
def build_dataset(cfg, mode):
dataset_cfg = copy.deepcopy(cfg)
if dataset_cfg['name'] == 'coco':
dataset_cfg.pop('name')
return CocoDataset(mode=mode, **dataset_cfg)
| [
"copy.deepcopy"
] | [((92, 110), 'copy.deepcopy', 'copy.deepcopy', (['cfg'], {}), '(cfg)\n', (105, 110), False, 'import copy\n')] |
#!/bin/python
"""
straintables' main pipeline script;
"""
import os
import argparse
import shutil
import straintables
import subprocess
from Bio.Align.Applications import ClustalOmegaCommandline
from straintables.logo import logo
from straintables.Executable import primerFinder, detectMutations,\
compareHea... | [
"argparse.ArgumentParser",
"straintables.Executable.primerFinder.parse_arguments",
"Bio.Align.Applications.ClustalOmegaCommandline",
"subprocess.run",
"shutil.which",
"os.path.join",
"straintables.OutputFile.MatchedRegions",
"straintables.DrawGraphics.drawTree.Execute",
"os.path.splitext",
"strain... | [((979, 1008), 'straintables.Executable.primerFinder.Execute', 'primerFinder.Execute', (['options'], {}), '(options)\n', (999, 1008), False, 'from straintables.Executable import primerFinder, detectMutations, compareHeatmap, matrixAnalysis\n'), ((1197, 1300), 'Bio.Align.Applications.ClustalOmegaCommandline', 'ClustalOm... |
# -*- coding: utf-8 -*-
# @Time : 2019-08-02 18:31
# @Author : <NAME>
# @Email : <EMAIL>
import os
import cv2
import glob
import shutil
from multiprocessing import Pool
from concurrent.futures import ProcessPoolExecutor
from functools import partial
from tqdm import tqdm
import numpy as np
import subprocess
de... | [
"cv2.VideoWriter",
"numpy.zeros",
"functools.partial",
"multiprocessing.Pool",
"numpy.concatenate",
"cv2.VideoWriter_fourcc",
"os.cpu_count",
"os.system",
"cv2.resize",
"concurrent.futures.ProcessPoolExecutor",
"cv2.imread",
"shutil.copy"
] | [((574, 602), 'cv2.imread', 'cv2.imread', (['img_path_list[0]'], {}), '(img_path_list[0])\n', (584, 602), False, 'import cv2\n'), ((719, 750), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', (["*'XVID'"], {}), "(*'XVID')\n", (741, 750), False, 'import cv2\n'), ((770, 826), 'cv2.VideoWriter', 'cv2.VideoWriter', (['t... |
"""
Podcats is a podcast feed generator and a server.
It generates RSS feeds for podcast episodes from local audio files and,
optionally, exposes the feed and as well as the episode file via
a built-in web server so that they can be imported into iTunes
or another podcast client.
"""
import os
import re
import time
i... | [
"xml.sax.saxutils.quoteattr",
"flask.Flask",
"mimetypes.guess_type",
"os.walk",
"mutagen.File",
"os.listdir",
"argparse.ArgumentParser",
"humanize.naturalsize",
"os.path.split",
"os.path.getsize",
"time.strptime",
"os.path.splitext",
"urllib.pathname2url",
"os.path.dirname",
"os.path.get... | [((9147, 9249), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': "('Podcats: podcast feed generator and server <%s>.' % __url__)"}), "(description=\n 'Podcats: podcast feed generator and server <%s>.' % __url__)\n", (9170, 9249), False, 'import argparse\n'), ((1029, 1054), 'os.path.dirname'... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.graphics.tsaplots as sgt
from statsmodels.tsa.arima_model import ARMA
from scipy.stats.distributions import chi2
import statsmodels.tsa.stattools as sts
# ------------------------
# load data
# ----------
raw_csv_data = pd.rea... | [
"matplotlib.pyplot.title",
"pandas.read_csv",
"statsmodels.graphics.tsaplots.plot_pacf",
"statsmodels.tsa.arima_model.ARMA",
"scipy.stats.distributions.chi2.sf",
"statsmodels.graphics.tsaplots.plot_acf",
"pandas.to_datetime",
"matplotlib.pyplot.show"
] | [((314, 350), 'pandas.read_csv', 'pd.read_csv', (['"""../data/Index2018.csv"""'], {}), "('../data/Index2018.csv')\n", (325, 350), True, 'import pandas as pd\n'), ((433, 476), 'pandas.to_datetime', 'pd.to_datetime', (['df_comp.date'], {'dayfirst': '(True)'}), '(df_comp.date, dayfirst=True)\n', (447, 476), True, 'import ... |
##############################################################################
#
# Copyright (c) 2001 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... | [
"Products.PageTemplates.ZopePageTemplate.Src",
"re.compile",
"six.text_type",
"Products.PageTemplates.utils.encodingFromXMLPreamble",
"AccessControl.class_init.InitializeClass",
"App.special_dtml.DTMLFile",
"AccessControl.SecurityManagement.getSecurityManager",
"Products.PageTemplates.utils.charsetFro... | [((1761, 1831), 're.compile', 're.compile', (['b\'^\\\\s*<\\\\?xml\\\\s+(?:[^>]*?encoding=["\\\\\\\']([^"\\\\\\\'>]+))?\''], {}), '(b\'^\\\\s*<\\\\?xml\\\\s+(?:[^>]*?encoding=["\\\\\\\']([^"\\\\\\\'>]+))?\')\n', (1771, 1831), False, 'import re\n'), ((1844, 1914), 're.compile', 're.compile', (['"""charset.*?=.*?(?P<char... |
#!/usr/bin/env python
# Standard imports
import pandas as pd
import numpy as np
# Pytorch
import torch
from torch import nn
# Using sklearn's LASSO implementation
from sklearn.linear_model import Lasso
# Local Files
from models.model_interface import CryptoModel
class LASSO(CryptoModel):
"""Wrapper around the ... | [
"numpy.vstack",
"sklearn.linear_model.Lasso",
"numpy.isin"
] | [((658, 719), 'sklearn.linear_model.Lasso', 'Lasso', ([], {'alpha': 'alpha', 'fit_intercept': '(True)', 'warm_start': 'warm_start'}), '(alpha=alpha, fit_intercept=True, warm_start=warm_start)\n', (663, 719), False, 'from sklearn.linear_model import Lasso\n'), ((1555, 1567), 'numpy.vstack', 'np.vstack', (['X'], {}), '(X... |
from django import forms
from apps.app_gestor_usuarios.models import db_usuarios, db_manage_contacts
class signupForm(forms.ModelForm):
class Meta:
model = db_usuarios
fields = [
'name',
'last',
'email',
'password',
]
labels = {
... | [
"django.forms.URLInput",
"django.forms.PasswordInput",
"django.forms.EmailInput",
"django.forms.TextInput"
] | [((486, 534), 'django.forms.TextInput', 'forms.TextInput', ([], {'attrs': "{'class': 'form-control'}"}), "(attrs={'class': 'form-control'})\n", (501, 534), False, 'from django import forms\n'), ((555, 603), 'django.forms.TextInput', 'forms.TextInput', ([], {'attrs': "{'class': 'form-control'}"}), "(attrs={'class': 'for... |
from .item import Item
from .entry import Entry
from copy import copy
class Record(object):
"""
A Record, the tuple of an entry and it's item
Records are useful for representing the latest entry for a
field value.
Records are serialised as the merged entry and item
"""
def __init__(self,... | [
"copy.copy"
] | [((499, 524), 'copy.copy', 'copy', (['self.item.primitive'], {}), '(self.item.primitive)\n', (503, 524), False, 'from copy import copy\n'), ((791, 806), 'copy.copy', 'copy', (['primitive'], {}), '(primitive)\n', (795, 806), False, 'from copy import copy\n')] |
"""
pyexcel_matplotlib
~~~~~~~~~~~~~~~~~~~
chart drawing plugin for pyexcel
:copyright: (c) 2016-2017 by Onni Software Ltd.
:license: New BSD License, see LICENSE for further details
"""
from pyexcel.plugins import PyexcelPluginChain
PyexcelPluginChain(__name__).add_a_renderer(
relative_plug... | [
"pyexcel.plugins.PyexcelPluginChain"
] | [((258, 286), 'pyexcel.plugins.PyexcelPluginChain', 'PyexcelPluginChain', (['__name__'], {}), '(__name__)\n', (276, 286), False, 'from pyexcel.plugins import PyexcelPluginChain\n')] |
"""
Django settings for petstore project.
Generated by 'django-admin startproject' using Django 2.2.10.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
... | [
"os.path.join",
"os.environ.get",
"os.path.abspath",
"os.getenv"
] | [((5533, 5578), 'os.environ.get', 'os.environ.get', (['"""STRIPE_TEST_PUBLISHABLE_KEY"""'], {}), "('STRIPE_TEST_PUBLISHABLE_KEY')\n", (5547, 5578), False, 'import os\n'), ((5604, 5644), 'os.environ.get', 'os.environ.get', (['"""STRIPE_TEST_SECRET_KEY"""'], {}), "('STRIPE_TEST_SECRET_KEY')\n", (5618, 5644), False, 'impo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# From /opt/recon-ng/recon/mixins/threads.py
from Queue import Queue, Empty
import threading
import time
import logging
logging.basicConfig(level=logging.INFO, format="[+] %(message)s")
logger = logging.getLogger("mutilthreads")
class ThreadingMixin(object):
def _... | [
"logging.basicConfig",
"logging.getLogger",
"time.sleep",
"threading.Event",
"threading.Thread",
"Queue.Queue"
] | [((170, 235), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""[+] %(message)s"""'}), "(level=logging.INFO, format='[+] %(message)s')\n", (189, 235), False, 'import logging\n'), ((245, 278), 'logging.getLogger', 'logging.getLogger', (['"""mutilthreads"""'], {}), "('mutilthreads... |
from BusquedasSem import *
import seaborn as sns
def main():
df = pd.read_csv('./client0-sort.csv')
df_abstract = df['Abstract']
l = df_abstract.size
abstracts = df_abstract.values
PCA_score = np.zeros((l, l))
abstracts_aux = preprocessing_abstracts_PCA(abstracts)
for i in range(l):
... | [
"seaborn.plt.show",
"seaborn.set",
"seaborn.heatmap"
] | [((651, 660), 'seaborn.set', 'sns.set', ([], {}), '()\n', (658, 660), True, 'import seaborn as sns\n'), ((665, 687), 'seaborn.heatmap', 'sns.heatmap', (['PCA_score'], {}), '(PCA_score)\n', (676, 687), True, 'import seaborn as sns\n'), ((692, 706), 'seaborn.plt.show', 'sns.plt.show', ([], {}), '()\n', (704, 706), True, ... |
from pathlib import Path
from typing import Any, Generator, Optional, Tuple
from cv2 import CAP_PROP_BUFFERSIZE, VideoCapture
from numpy import ndarray
from zoloto.marker_type import MarkerType
from .base import BaseCamera
from .mixins import IterableCameraMixin, VideoCaptureMixin, ViewableCameraMixin
from .utils im... | [
"cv2.VideoCapture"
] | [((654, 677), 'cv2.VideoCapture', 'VideoCapture', (['camera_id'], {}), '(camera_id)\n', (666, 677), False, 'from cv2 import CAP_PROP_BUFFERSIZE, VideoCapture\n'), ((1901, 1924), 'cv2.VideoCapture', 'VideoCapture', (['camera_id'], {}), '(camera_id)\n', (1913, 1924), False, 'from cv2 import CAP_PROP_BUFFERSIZE, VideoCapt... |
from prefixdate import parse_parts
from opensanctions import helpers as h
from opensanctions.util import remove_namespace
def parse_address(context, el):
country = el.get("countryDescription")
if country == "UNKNOWN":
country = None
# context.log.info("Addrr", el=el)
return h.make_address(
... | [
"opensanctions.helpers.apply_address",
"opensanctions.helpers.make_sanction",
"opensanctions.util.remove_namespace"
] | [((1084, 1116), 'opensanctions.helpers.make_sanction', 'h.make_sanction', (['context', 'entity'], {}), '(context, entity)\n', (1099, 1116), True, 'from opensanctions import helpers as h\n'), ((4808, 4829), 'opensanctions.util.remove_namespace', 'remove_namespace', (['doc'], {}), '(doc)\n', (4824, 4829), False, 'from op... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: <NAME>
@license: Apache Licence
@file: prepare_training_data.py
@time: 2019/12/19
@contact: <EMAIL>
将conll的v4_gold_conll文件格式转成模型训练所需的jsonlines数据格式
"""
import argparse
import json
import logging
import os
import re
import sys
from collections import defaultdict... | [
"logging.basicConfig",
"logging.getLogger",
"logging.StreamHandler",
"argparse.ArgumentParser",
"os.path.join",
"re.match",
"bert.tokenization.FullTokenizer",
"tensorflow.train.Features",
"logging.FileHandler",
"collections.defaultdict",
"json.dump"
] | [((471, 532), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Process some integers."""'}), "(description='Process some integers.')\n", (494, 532), False, 'import argparse\n'), ((1090, 1231), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'handlers': 'handler... |
"""
Utilities for making plots
"""
from warnings import warn
import matplotlib.pyplot as plt
from matplotlib.projections import register_projection
from matplotlib.animation import ArtistAnimation
from .parse import Delay, Pulse, PulseSeq
def subplots(*args, **kwargs):
"""
Wrapper around matplotlib.pyplot.s... | [
"matplotlib.pyplot.subplot_mosaic",
"matplotlib.projections.register_projection",
"matplotlib.animation.ArtistAnimation",
"warnings.warn",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((424, 457), 'matplotlib.projections.register_projection', 'register_projection', (['PulseProgram'], {}), '(PulseProgram)\n', (443, 457), False, 'from matplotlib.projections import register_projection\n'), ((836, 865), 'matplotlib.pyplot.subplots', 'plt.subplots', (['*args'], {}), '(*args, **kwargs)\n', (848, 865), Tr... |
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
class CartPage:
def __init__(self, driver):
self.driver = driver
self.wait = WebDriverWait(driver, 10)
def del_from_cart_butto... | [
"selenium.webdriver.support.wait.WebDriverWait",
"selenium.webdriver.support.expected_conditions.presence_of_element_located",
"selenium.webdriver.support.expected_conditions.staleness_of"
] | [((266, 291), 'selenium.webdriver.support.wait.WebDriverWait', 'WebDriverWait', (['driver', '(10)'], {}), '(driver, 10)\n', (279, 291), False, 'from selenium.webdriver.support.wait import WebDriverWait\n'), ((896, 963), 'selenium.webdriver.support.expected_conditions.presence_of_element_located', 'EC.presence_of_elemen... |
import time,pyb
uart = pyb. UART(3,9600, bits=8, parity=None, stop=1)
while(True):
time.sleep_ms(100)
size = uart.any()
if (size > 0):
string = uart.read(size)
data = int(string[-1])
print('Data: %3d' % (data))
| [
"pyb.UART",
"time.sleep_ms"
] | [((24, 70), 'pyb.UART', 'pyb.UART', (['(3)', '(9600)'], {'bits': '(8)', 'parity': 'None', 'stop': '(1)'}), '(3, 9600, bits=8, parity=None, stop=1)\n', (32, 70), False, 'import time, pyb\n'), ((89, 107), 'time.sleep_ms', 'time.sleep_ms', (['(100)'], {}), '(100)\n', (102, 107), False, 'import time, pyb\n')] |
from faker import Faker
import random
import parameters
from utils import chance_choose, chance
from uri_generator import gen_path, uri_extensions, gen_uri_useable
# TODO: Continue to expand this list with the proper formats for other application
# layer protocols (e.g. FTP, SSH, SMTP...)
protocols = ['HTTP/1.0', 'H... | [
"utils.chance",
"random.choice",
"uri_generator.gen_uri_useable",
"faker.Faker",
"uri_generator.gen_path",
"random.randint"
] | [((1152, 1179), 'random.choice', 'random.choice', (['path_options'], {}), '(path_options)\n', (1165, 1179), False, 'import random\n'), ((1295, 1344), 'utils.chance', 'chance', (["parameters.frequency['empty_querystring']"], {}), "(parameters.frequency['empty_querystring'])\n", (1301, 1344), False, 'from utils import ch... |
"""Test evaluation functionality."""
from moda.evaluators import f_beta
from moda.evaluators.metrics import calculate_metrics_with_shift, _join_metrics
def test_f_beta1():
precision = 0.6
recall = 1.0
beta = 1
f = f_beta(precision, recall, beta)
assert (f > 0.74) and (f < 0.76)
def test_f_beta3(... | [
"moda.evaluators.metrics._join_metrics",
"moda.evaluators.f_beta",
"moda.evaluators.metrics.calculate_metrics_with_shift"
] | [((232, 263), 'moda.evaluators.f_beta', 'f_beta', (['precision', 'recall', 'beta'], {}), '(precision, recall, beta)\n', (238, 263), False, 'from moda.evaluators import f_beta\n'), ((381, 412), 'moda.evaluators.f_beta', 'f_beta', (['precision', 'recall', 'beta'], {}), '(precision, recall, beta)\n', (387, 412), False, 'f... |
from django.db import models,transaction
from contact.models import Customer
from product.models import Stock
from django.urls import reverse
from django.db.models import Sum
# Create your models here.
class Approval(models.Model):
created_at = models.DateTimeField(auto_now_add = True,
editable = F... | [
"django.db.models.Sum",
"django.db.models.IntegerField",
"django.db.models.ForeignKey",
"django.db.transaction.atomic",
"django.db.models.BooleanField",
"django.urls.reverse",
"django.db.models.DateTimeField",
"django.db.models.DecimalField",
"django.db.models.CharField"
] | [((250, 305), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'editable': '(False)'}), '(auto_now_add=True, editable=False)\n', (270, 305), False, 'from django.db import models, transaction\n'), ((343, 394), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_... |
from pdf2image import convert_from_path, convert_from_bytes
from pdf2image.exceptions import (
PDFInfoNotInstalledError,
PDFPageCountError,
PDFSyntaxError
)
images = convert_from_path('.\git_cheat_sheet.pdf')
| [
"pdf2image.convert_from_path"
] | [((178, 221), 'pdf2image.convert_from_path', 'convert_from_path', (['""".\\\\git_cheat_sheet.pdf"""'], {}), "('.\\\\git_cheat_sheet.pdf')\n", (195, 221), False, 'from pdf2image import convert_from_path, convert_from_bytes\n')] |
from googleapiclient.discovery import build
from uuid import uuid4
from google.auth.transport.requests import Request
from pathlib import Path
from google_auth_oauthlib.flow import InstalledAppFlow
from typing import Dict, List
from pickle import load, dump
class CreateMeet:
def __init__(self, attendees: Dict[str,... | [
"pickle.dump",
"pathlib.Path",
"google.auth.transport.requests.Request",
"pickle.load",
"uuid.uuid4",
"googleapiclient.discovery.build",
"google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file"
] | [((2013, 2061), 'googleapiclient.discovery.build', 'build', (['"""calendar"""', '"""v3"""'], {'credentials': 'credentials'}), "('calendar', 'v3', credentials=credentials)\n", (2018, 2061), False, 'from googleapiclient.discovery import build\n'), ((1322, 1344), 'pathlib.Path', 'Path', (['"""./token.pickle"""'], {}), "('... |
import librosa
import numpy as np
import audio
from hparams import hparams
"""
This helps implement a user interface for a vocoder.
Currently this is Griffin-Lim but can be extended to different vocoders.
Required elements for the vocoder UI are:
self.sample_rate
self.source_action
self.vocode_action
"""
class Voice... | [
"audio.inv_mel_spectrogram",
"audio.melspectrogram"
] | [((925, 959), 'audio.melspectrogram', 'audio.melspectrogram', (['wav', 'hparams'], {}), '(wav, hparams)\n', (945, 959), False, 'import audio\n'), ((977, 1029), 'audio.inv_mel_spectrogram', 'audio.inv_mel_spectrogram', (['self.source_spec', 'hparams'], {}), '(self.source_spec, hparams)\n', (1002, 1029), False, 'import a... |
# -*- coding: utf-8 -*-
import pytest
from src.replace_lcsh import replace_term, lcsh_fields, normalize_subfields
# def test_flip_impacted_fields(fake_bib):
# pass
@pytest.mark.parametrize(
"arg,expectation",
[
(1, ["a", "local term", "x", "subX1", "x", "subX2", "z", "subZ."]),
(3, ["a... | [
"pytest.mark.parametrize",
"src.replace_lcsh.lcsh_fields",
"src.replace_lcsh.normalize_subfields",
"src.replace_lcsh.replace_term"
] | [((175, 505), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""arg,expectation"""', "[(1, ['a', 'local term', 'x', 'subX1', 'x', 'subX2', 'z', 'subZ.']), (3, [\n 'a', 'subA', 'x', 'local term', 'x', 'subX2', 'z', 'subZ.']), (5, ['a',\n 'subA', 'x', 'subX1', 'x', 'local term', 'z', 'subZ.']), (7, ['a',\... |
from just_bin_it.exceptions import KafkaException
class SpyProducer:
def __init__(self, brokers=None):
self.messages = []
def publish_message(self, topic, message):
self.messages.append((topic, message))
class StubProducerThatThrows:
def publish_message(self, topic, message):
ra... | [
"just_bin_it.exceptions.KafkaException"
] | [((324, 358), 'just_bin_it.exceptions.KafkaException', 'KafkaException', (['"""Some Kafka error"""'], {}), "('Some Kafka error')\n", (338, 358), False, 'from just_bin_it.exceptions import KafkaException\n')] |
import requests
import re
import json
import datetime
import os
DATE_FORMAT = '%Y-%m-%d'
DATA_PATH = 'rupodcast_lengths.json'
def extract_hms(g):
return float(g[0] or 0) * 60 + float(g[1]) + float(g[2]) / 60
def extract_rss(dur):
g = dur.split(':')
while len(g) < 3:
g = [0] + g
return floa... | [
"os.path.exists",
"re.compile",
"datetime.datetime.strptime",
"requests.get",
"datetime.datetime.now",
"datetime.date",
"json.load",
"datetime.date.today",
"json.dump"
] | [((2647, 2697), 'requests.get', 'requests.get', (['"""https://russiancast.club/data.json"""'], {}), "('https://russiancast.club/data.json')\n", (2659, 2697), False, 'import requests\n'), ((5212, 5233), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (5231, 5233), False, 'import datetime\n'), ((2754, 277... |
from django.conf.urls import patterns, include, url
from . import views
urlpatterns = [
url(r'^$', views.rate_list, name='list'),
url(r'^(?P<pk>\d+)/$', views.rate_as_field, name='as_field'),
url(r'^suggestions/$', views.suggestions, name='suggestions'),
url(r'^create/$', views.create_rate, name='creat... | [
"django.conf.urls.url"
] | [((93, 132), 'django.conf.urls.url', 'url', (['"""^$"""', 'views.rate_list'], {'name': '"""list"""'}), "('^$', views.rate_list, name='list')\n", (96, 132), False, 'from django.conf.urls import patterns, include, url\n'), ((139, 199), 'django.conf.urls.url', 'url', (['"""^(?P<pk>\\\\d+)/$"""', 'views.rate_as_field'], {'... |
# importing libraries
import numpy as np
import pandas as pd
import random
import torch
def set_seeds(seed=1234):
"""[Set seeds for reproducibility.]
Keyword Arguments:
seed {int} -- [The seed value] (default: {1234})
"""
np.random.seed(seed)
random.seed(seed)
torch.manual_seed(seed)
... | [
"torch.manual_seed",
"random.seed",
"torch.cuda.is_available",
"numpy.random.seed",
"torch.cuda.manual_seed"
] | [((247, 267), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (261, 267), True, 'import numpy as np\n'), ((272, 289), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (283, 289), False, 'import random\n'), ((294, 317), 'torch.manual_seed', 'torch.manual_seed', (['seed'], {}), '(seed)\n', (31... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_in_serializers
-------------------
Tests of the fields cooperation in the serializer interfaces for serialization, de-serialization,
and validation.
"""
# Django settings:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = __name__
from django.conf.global_sett... | [
"rest_framework.serializers.EmailField",
"rest_framework.compat.six.iterkeys"
] | [((618, 642), 'rest_framework.serializers.EmailField', 'serializers.EmailField', ([], {}), '()\n', (640, 642), False, 'from rest_framework import serializers\n'), ((1842, 1866), 'rest_framework.serializers.EmailField', 'serializers.EmailField', ([], {}), '()\n', (1864, 1866), False, 'from rest_framework import serializ... |
### Copyright 2014, MTA SZTAKI, www.sztaki.hu
###
### Licensed under the Apache License, Version 2.0 (the "License");
### you may not use this file except in compliance with the License.
### You may obtain a copy of the License at
###
### http://www.apache.org/licenses/LICENSE-2.0
###
### Unless required by applicab... | [
"logging.getLogger",
"occo.util.factory.register"
] | [((850, 882), 'logging.getLogger', 'logging.getLogger', (['"""occo.upkeep"""'], {}), "('occo.upkeep')\n", (867, 882), False, 'import logging\n'), ((893, 930), 'logging.getLogger', 'logging.getLogger', (['"""occo.data.upkeep"""'], {}), "('occo.data.upkeep')\n", (910, 930), False, 'import logging\n'), ((1124, 1156), 'occ... |
#!/usr/bin/env python3
import sys, re
for line in iter(sys.stdin.readline, ''):
if re.search('agent ', line):
print(line.strip())
| [
"re.search"
] | [((89, 114), 're.search', 're.search', (['"""agent """', 'line'], {}), "('agent ', line)\n", (98, 114), False, 'import sys, re\n')] |
from haptyc import *
from base64 import b64encode, b64decode
import json
class TestLogic(Transform):
#
# test_h1: Decodes base64, fuzzes using random_insert, Re-encodes base64
# Number of tests: 50
#
@ApplyIteration(50)
def test_h1(self, data, state):
data = b64decode(data)
... | [
"base64.b64encode",
"json.dumps",
"base64.b64decode",
"json.loads"
] | [((304, 319), 'base64.b64decode', 'b64decode', (['data'], {}), '(data)\n', (313, 319), False, 'from base64 import b64encode, b64decode\n'), ((382, 397), 'base64.b64encode', 'b64encode', (['data'], {}), '(data)\n', (391, 397), False, 'from base64 import b64encode, b64decode\n'), ((797, 813), 'json.loads', 'json.loads', ... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from pathlib import Path
app = Flask(__name__)
BASE_DIR = Path(__file__).resolve().parent
DB_PATH = str(BASE_DIR / "one_to_many.sqlite")
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + DB_PATH
app.config["SQLALCHEMY_COMMIT_ON_SUBMIT"] = True
app... | [
"flask_sqlalchemy.SQLAlchemy",
"pathlib.Path",
"flask.Flask"
] | [((97, 112), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (102, 112), False, 'from flask import Flask\n'), ((376, 391), 'flask_sqlalchemy.SQLAlchemy', 'SQLAlchemy', (['app'], {}), '(app)\n', (386, 391), False, 'from flask_sqlalchemy import SQLAlchemy\n'), ((125, 139), 'pathlib.Path', 'Path', (['__file__'... |
import pandas as pd
import sys
from os import system
sys.path.append('../final_project/')
sys.path.append('../')
def readNames(inputFile='new_poi_names.txt'):
'''
A function to read names data from a file create by a data cache
Returns:
Returns a data frame that contains data from 'poi_names.txt'
... | [
"sys.path.append",
"pandas.read_csv"
] | [((53, 89), 'sys.path.append', 'sys.path.append', (['"""../final_project/"""'], {}), "('../final_project/')\n", (68, 89), False, 'import sys\n'), ((90, 112), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (105, 112), False, 'import sys\n'), ((405, 494), 'pandas.read_csv', 'pd.read_csv', (['inpu... |
# Copyright 2015 Open Source Robotics Foundation, Inc.
#
# 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... | [
"os.path.dirname",
"launch.legacy.output_handler.FileOutput",
"tempfile.NamedTemporaryFile"
] | [((914, 971), 'tempfile.NamedTemporaryFile', 'NamedTemporaryFile', ([], {'mode': '"""w"""', 'prefix': '"""foo_"""', 'delete': '(False)'}), "(mode='w', prefix='foo_', delete=False)\n", (932, 971), False, 'from tempfile import NamedTemporaryFile\n'), ((862, 887), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), ... |
# Copyright 1999-2021 Alibaba Group Holding Ltd.
#
# 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 a... | [
"sklearn.decomposition.PCA",
"numpy.testing.assert_allclose",
"sklearn.linear_model.LogisticRegression",
"pytest.raises",
"sklearn.ensemble.GradientBoostingClassifier",
"sklearn.linear_model.LinearRegression",
"sklearn.datasets.make_classification"
] | [((974, 1009), 'sklearn.datasets.make_classification', 'make_classification', ([], {'n_samples': '(1000)'}), '(n_samples=1000)\n', (993, 1009), False, 'from sklearn.datasets import make_classification\n'), ((1651, 1686), 'sklearn.datasets.make_classification', 'make_classification', ([], {'n_samples': '(1000)'}), '(n_s... |
import cx_Freeze
import sys
base = None
if sys.platform == 'win32':
base = "Win32GUI"
executables = [cx_Freeze.Executable("Speech_Recognizer.py", base=base, icon = "icon.ico")]
cx_Freeze.setup(
name = "Speech Recognizer",
author = "<NAME>",
options = {"build_exe":{"packages":["tkinter",... | [
"cx_Freeze.Executable",
"cx_Freeze.setup"
] | [((195, 590), 'cx_Freeze.setup', 'cx_Freeze.setup', ([], {'name': '"""Speech Recognizer"""', 'author': '"""<NAME>"""', 'options': "{'build_exe': {'packages': ['tkinter', 'speech_recognition', 'threading',\n 'time'], 'include_files': ['icon.ico', 'wait.ico', 'mic.ico', 'save.ico']}}", 'version': '"""1.0"""', 'descrip... |
#!/usr/bin/env python
from setuptools import setup
LONG_DESCRIPTION = \
'''The program extracts regions of interest from Fasta or Genome Feature Format (GFF) genomes.
This is done given a set of seed sequences given as nucleotide strings in a multi-line fasta file.
The program can output fasta and GFF outputs or re... | [
"setuptools.setup"
] | [((512, 1390), 'setuptools.setup', 'setup', ([], {'name': '"""Magphi"""', 'version': '"""0.1.6"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'packages': "['Magphi']", 'package_dir': "{'Magphi': 'Magphi'}", 'entry_points': "{'console_scripts': ['Magphi = Magphi.__main__:main']}", 'url': '"""https://git... |
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
class Generator:
def __init__(self, learning_rate=1e-4, num_blocks=6):
self.learning_rate = learning_rate
self.num_blocks = num_blocks
def pelu(self, x):
with tf.variable_scope(x.op.name + '_activation', initializer=tf.c... | [
"tensorflow.depth_to_space",
"tensorflow.variable_scope",
"tensorflow.shape",
"tensorflow.nn.relu",
"tensorflow.image.resize_bicubic",
"tensorflow.multiply",
"tensorflow.concat",
"tensorflow.nn.sigmoid",
"tensorflow.layers.conv2d",
"tensorflow.constant_initializer",
"tensorflow.reduce_mean",
"... | [((976, 1007), 'tensorflow.identity', 'tf.identity', (['x'], {'name': '"""identity"""'}), "(x, name='identity')\n", (987, 1007), True, 'import tensorflow as tf\n'), ((1066, 1155), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', (['x'], {'kernel_size': '(1)', 'filters': '(f // reduction)', 'strides': '(1)', 'padding': '... |
import nltk
from .base import BaseTokenizer
from typing import (
Tuple,
Iterator,
)
__all__ = ['NLTKTokenizer']
class NLTKTokenizer(BaseTokenizer):
"""NLTK-based Treebank tokenizer.
Args:
sentencizer (str): Name of sentencizer for text.
chunker (str): Phrase chunker where 'noun' us... | [
"nltk.pos_tag",
"nltk.RegexpParser",
"nltk.corpus.stopwords.words"
] | [((3525, 3564), 'nltk.RegexpParser', 'nltk.RegexpParser', (['"""NP: {<ADJ>*<NOUN>}"""'], {}), "('NP: {<ADJ>*<NOUN>}')\n", (3542, 3564), False, 'import nltk\n'), ((2674, 2711), 'nltk.corpus.stopwords.words', 'nltk.corpus.stopwords.words', (['language'], {}), '(language)\n', (2701, 2711), False, 'import nltk\n'), ((5066,... |
from vcs import vtk_ui
from vcs.colorpicker import ColorPicker
from vcs.vtk_ui import behaviors
from vcs.VCS_validation_functions import checkMarker
import vtk
import vcs.vcs2vtk
from . import priority
import sys
class MarkerEditor(
behaviors.ClickableMixin, behaviors.DraggableMixin, priority.PriorityEditor):... | [
"vtk.vtkTextProperty",
"vcs.vtk_ui.Label",
"vcs.vtk_ui.Handle",
"vcs.vtk_ui.manager.get_manager",
"vcs.colorpicker.ColorPicker",
"vcs.VCS_validation_functions.checkMarker",
"vcs.vtk_ui.toolbar.Toolbar"
] | [((1214, 1271), 'vcs.vtk_ui.toolbar.Toolbar', 'vtk_ui.toolbar.Toolbar', (['self.interactor', '"""Marker Options"""'], {}), "(self.interactor, 'Marker Options')\n", (1236, 1271), False, 'from vcs import vtk_ui\n'), ((2440, 2461), 'vtk.vtkTextProperty', 'vtk.vtkTextProperty', ([], {}), '()\n', (2459, 2461), False, 'impor... |
from functools import wraps
from typing import Any, Callable, TypeVar, cast
from grpc import Call, RpcError
from grpc.aio import AioRpcError
from .exceptions import AioRequestError, RequestError
from .logging import get_metadata_from_aio_error, get_metadata_from_call, log_error
TFunc = TypeVar("TFunc", bound=Callabl... | [
"typing.cast",
"functools.wraps",
"typing.TypeVar"
] | [((290, 332), 'typing.TypeVar', 'TypeVar', (['"""TFunc"""'], {'bound': 'Callable[..., Any]'}), "('TFunc', bound=Callable[..., Any])\n", (297, 332), False, 'from typing import Any, Callable, TypeVar, cast\n'), ((422, 433), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (427, 433), False, 'from functools import ... |
import torch
import torch.nn as nn
from torchvision import transforms
from torch.utils.data import DataLoader, TensorDataset, Dataset
from torch.utils.data.sampler import SubsetRandomSampler
from torch import optim
import pandas as pd
import sys
sys.path.append('./proto')
import trainer_pb2
import trainer_pb2_grpc
impo... | [
"torch.nn.ReLU",
"torch.nn.Dropout",
"torch.nn.CrossEntropyLoss",
"pandas.read_csv",
"torchvision.transforms.ToPILImage",
"base64.b64encode",
"io.BytesIO",
"time.sleep",
"torch.from_numpy",
"torch.cuda.is_available",
"sys.path.append",
"ipfshttpclient.connect",
"argparse.ArgumentParser",
"... | [((246, 272), 'sys.path.append', 'sys.path.append', (['"""./proto"""'], {}), "('./proto')\n", (261, 272), False, 'import sys\n'), ((528, 540), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (538, 540), False, 'import io\n'), ((545, 570), 'torch.save', 'torch.save', (['model', 'buffer'], {}), '(model, buffer)\n', (555, 5... |
from django.shortcuts import render
from django.http import HttpResponse
from django.template.loader import get_template
from .models import Poll
from time import timezone
from datetime import date
# Create your views here.
def index(request):
myTemplate = get_template('./index.html')
print(myTemplate)
r... | [
"django.shortcuts.render",
"django.http.HttpResponse",
"datetime.date.today",
"django.template.loader.get_template"
] | [((264, 292), 'django.template.loader.get_template', 'get_template', (['"""./index.html"""'], {}), "('./index.html')\n", (276, 292), False, 'from django.template.loader import get_template\n'), ((326, 353), 'django.shortcuts.render', 'render', (['request', 'myTemplate'], {}), '(request, myTemplate)\n', (332, 353), Fals... |
#!/usr/bin/python
# Copyright 2021 Northern.tech AS
#
# 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 ap... | [
"time.sleep",
"subprocess.check_call"
] | [((2490, 2528), 'subprocess.check_call', 'subprocess.check_call', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (2511, 2528), False, 'import subprocess\n'), ((3585, 3623), 'subprocess.check_call', 'subprocess.check_call', (['cmd'], {'shell': '(True)'}), '(cmd, shell=True)\n', (3606, 3623), False, 'import subpr... |
from invoke import task
@task
def no_docstring():
pass
@task
def one_line():
"""foo
"""
@task
def two_lines():
"""foo
bar
"""
@task
def leading_whitespace():
"""
foo
"""
@task(aliases=('a', 'b'))
def with_aliases():
"""foo
"""
| [
"invoke.task"
] | [((212, 236), 'invoke.task', 'task', ([], {'aliases': "('a', 'b')"}), "(aliases=('a', 'b'))\n", (216, 236), False, 'from invoke import task\n')] |
from subprocess import PIPE
from subprocess import Popen
def run(command):
assert (isinstance(command, list)), "Command must be a list"
p = Popen(command, stdout=PIPE, stderr=PIPE)
s, e = p.communicate()
return s.decode('utf-8'), e.decode('utf-8'), p.returncode
| [
"subprocess.Popen"
] | [((150, 190), 'subprocess.Popen', 'Popen', (['command'], {'stdout': 'PIPE', 'stderr': 'PIPE'}), '(command, stdout=PIPE, stderr=PIPE)\n', (155, 190), False, 'from subprocess import Popen\n')] |
import tensorflow as tf
from tensorflow.keras.layers import Layer
from debugprint import print_debug
from .utils import get_mask_from_lengths
class ParrotLoss():
def __init__(self, hparams):
super(ParrotLoss, self).__init__()
self.hidden_dim = hparams.encoder_embedding_dim
self.mel_hidden_... | [
"tensorflow.keras.backend.flatten",
"tensorflow.transpose",
"tensorflow.math.log",
"tensorflow.reduce_sum",
"tensorflow.norm",
"tensorflow.nn.softmax",
"tensorflow.cast",
"tensorflow.eye",
"tensorflow.nn.sigmoid",
"tensorflow.keras.backend.cast",
"tensorflow.zeros_like",
"tensorflow.convert_to... | [((1187, 1256), 'debugprint.print_debug', 'print_debug', (["('spk adv loss type: ' + self.speaker_adversial_loss_type)"], {}), "('spk adv loss type: ' + self.speaker_adversial_loss_type)\n", (1198, 1256), False, 'from debugprint import print_debug\n'), ((1866, 1918), 'tensorflow.cast', 'tf.cast', (['(contrast_mask1 & c... |
import datetime
import json
import os
import random
import re
from urllib.parse import quote
import lxml
import pafy
import requests
import youtube_dl
from bs4 import BeautifulSoup
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.http import (Http404, HttpResponse, H... | [
"django.shortcuts.render",
"django.http.HttpResponseRedirect",
"json.loads",
"django.http.JsonResponse",
"django.http.HttpResponse",
"os.path.join",
"utils.ytscrapper.getYtUrl",
"requests.get",
"bs4.BeautifulSoup",
"pafy.new",
"django.shortcuts.redirect",
"django.shortcuts.reverse",
"re.sub"... | [((679, 708), 'django.shortcuts.render', 'render', (['request', '"""index.html"""'], {}), "(request, 'index.html')\n", (685, 708), False, 'from django.shortcuts import redirect, render, reverse\n'), ((742, 771), 'django.shortcuts.render', 'render', (['request', '"""about.html"""'], {}), "(request, 'about.html')\n", (74... |
from spotdl import handle
from spotdl import const
from spotdl import downloader
import os
import sys
const.args = handle.get_arguments(to_group=True)
track = downloader.Downloader(raw_song=const.args.song[0])
track_title = track.refine_songname(track.content.title)
track_filename = track_title + const.args.output_... | [
"os.path.join",
"spotdl.handle.get_arguments",
"spotdl.downloader.Downloader"
] | [((117, 152), 'spotdl.handle.get_arguments', 'handle.get_arguments', ([], {'to_group': '(True)'}), '(to_group=True)\n', (137, 152), False, 'from spotdl import handle\n'), ((162, 212), 'spotdl.downloader.Downloader', 'downloader.Downloader', ([], {'raw_song': 'const.args.song[0]'}), '(raw_song=const.args.song[0])\n', (1... |
"""Tests for the cursor module."""
from __future__ import absolute_import
from . import common
from bearfield import cursor, Document, Field, Query
class TestCursor(common.TestCase):
"""Test the Cursor class."""
class Document(Document):
class Meta:
connection = 'test'
index = Fie... | [
"bearfield.Field",
"bearfield.Query"
] | [((317, 327), 'bearfield.Field', 'Field', (['int'], {}), '(int)\n', (322, 327), False, 'from bearfield import cursor, Document, Field, Query\n'), ((343, 353), 'bearfield.Field', 'Field', (['str'], {}), '(str)\n', (348, 353), False, 'from bearfield import cursor, Document, Field, Query\n'), ((973, 992), 'bearfield.Query... |
from typing import List, Union
import numpy as np
from .Figure import Figure
def create_position_pdf_plot(*, start_time_sec: np.float32, sampling_frequency: np.float32, pdf: np.ndarray, label: str):
# Nt = pdf.shape[0]
# Np = pdf.shape[1]
A = pdf
B = A / np.reshape(np.repeat(np.max(A, axis=1), A.shape... | [
"numpy.max"
] | [((294, 311), 'numpy.max', 'np.max', (['A'], {'axis': '(1)'}), '(A, axis=1)\n', (300, 311), True, 'import numpy as np\n')] |
# Connect files
from configs import *
# Arrays
items = []
selectedItems = []
# Interface arrays
buttons = []
surfaces = []
# Getting item
def getItemById(ident):
for item in items:
if item.id == ident:
return item
# Removing item
def removeItem(item):
items.remove(item)
# Removing items
def removeItems():
... | [
"templates.Worker"
] | [((859, 889), 'templates.Worker', 'Worker', (['counter', 'x', 'y', 'faction'], {}), '(counter, x, y, faction)\n', (865, 889), False, 'from templates import Worker\n')] |
import click
import pathlib
import os
from kneejerk.image_server import score_images_in_dir
from kneejerk.data.saver import persist_scores, persist_metadata
from kneejerk.data.transfer import segment_data_from_csv, transfer_normalized_image_data
from kneejerk.data.utils import _get_classes, _get_max_image_dim, _ensure... | [
"os.listdir",
"pathlib.Path",
"click.group",
"click.option",
"os.path.join",
"click.echo",
"kneejerk.data.utils._get_classes",
"kneejerk.data.utils._get_max_image_dim",
"kneejerk.image_server.score_images_in_dir",
"kneejerk.data.saver.persist_metadata",
"kneejerk.data.saver.persist_scores",
"k... | [((336, 349), 'click.group', 'click.group', ([], {}), '()\n', (347, 349), False, 'import click\n'), ((474, 552), 'click.option', 'click.option', (['"""--input_dir"""', '"""-i"""'], {'help': '"""Location of the images."""', 'default': '"""."""'}), "('--input_dir', '-i', help='Location of the images.', default='.')\n", (... |
import sys, os, shutil, binascii, urllib.request, zipfile, ctypes, math, glob
# Must be in game root folder.
if not os.path.isfile('Ace7Game.exe'):
wait = input('Ace7Game.exe not found in this folder. Press any key to close...')
sys.exit(0)
# Get resolution from OS.
u32 = ctypes.windll.user32
u32.SetProcessDP... | [
"os.path.exists",
"os.listdir",
"zipfile.ZipFile",
"shutil.copy2",
"binascii.a2b_hex",
"os.path.isfile",
"shutil.copytree",
"os.path.isdir",
"os.mkdir",
"sys.exit",
"glob.glob"
] | [((2031, 2051), 'glob.glob', 'glob.glob', (['tdm_regex'], {}), '(tdm_regex)\n', (2040, 2051), False, 'import sys, os, shutil, binascii, urllib.request, zipfile, ctypes, math, glob\n'), ((2268, 2297), 'zipfile.ZipFile', 'zipfile.ZipFile', (['tdm_zip', '"""r"""'], {}), "(tdm_zip, 'r')\n", (2283, 2297), False, 'import sys... |
# Tkinter is Python's de-facto standard GUI (Graphical User Interface) package.
import tkinter as tk
import keras as kr
import numpy as np
import matplotlib.pyplot as plt
import math
import sklearn.preprocessing as pre
import gzip
import PIL
from PIL import Image, ImageDraw
import os.path
width = 280
height = 280
ce... | [
"sklearn.preprocessing.LabelBinarizer",
"PIL.Image.open",
"keras.models.load_model",
"gzip.open",
"PIL.Image.new",
"tkinter.Button",
"keras.models.Sequential",
"keras.utils.to_categorical",
"tkinter.Canvas",
"PIL.ImageDraw.Draw",
"tkinter.Tk",
"keras.models.save_model",
"tkinter.Label",
"k... | [((4411, 4433), 'keras.models.Sequential', 'kr.models.Sequential', ([], {}), '()\n', (4431, 4433), True, 'import keras as kr\n'), ((4488, 4532), 'PIL.Image.new', 'PIL.Image.new', (['"""RGB"""', '(width, height)', 'black'], {}), "('RGB', (width, height), black)\n", (4501, 4532), False, 'import PIL\n'), ((4540, 4562), 'P... |
# -*- coding: utf-8 -*-
"""
Summarise Sound Scattering Layers (SSLs)
@author: <NAME>
"""
## import packages
import matplotlib.pyplot as plt
import gzip
import pickle
import numpy as np
from pyechoplot.plotting import plot_pseudo_SSL, save_png_plot, plot_Sv
## import pyechometrics modules
from pyechometrics.metrics i... | [
"matplotlib.pyplot.ylabel",
"gzip.open",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.plot",
"pyechometrics.metrics.stats",
"pickle.load",
"pyechometrics.metrics.nasc",
"pyechometrics.metrics.dims",
"pyechoplot.plotting.plot_Sv",
"matplotlib.pyplot.figure",
"numpy.zeros",
"pyechoplot.plottin... | [((703, 716), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (713, 716), True, 'import matplotlib.pyplot as plt\n'), ((717, 733), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(211)'], {}), '(211)\n', (728, 733), True, 'import matplotlib.pyplot as plt\n'), ((734, 747), 'pyechoplot.plotting.plot_Sv',... |
# ------------------------------------------------------------------------------
# CodeHawk Binary Analyzer
# Author: <NAME>
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2016-2020 Kestrel Technology LLC
# Copyright (c) 2020 <NAME>
# Copy... | [
"chb.util.DotGraph.DotGraph"
] | [((3205, 3224), 'chb.util.DotGraph.DotGraph', 'DotGraph', (['graphname'], {}), '(graphname)\n', (3213, 3224), False, 'from chb.util.DotGraph import DotGraph\n')] |
from locust import (
constant,
)
from locust.env import Environment, LoadTestShape
from locust.user import (
User,
task,
)
from locust.user.task import TaskSet
from .testcases import LocustTestCase
from .fake_module1_for_env_test import MyUserWithSameName as MyUserWithSameName1
from .fake_module2_for_env_te... | [
"locust.constant",
"locust.env.Environment",
"locust.user.task"
] | [((748, 792), 'locust.env.Environment', 'Environment', ([], {'user_classes': '[MyUser1, MyUser2]'}), '(user_classes=[MyUser1, MyUser2])\n', (759, 792), False, 'from locust.env import Environment, LoadTestShape\n'), ((1928, 1963), 'locust.env.Environment', 'Environment', ([], {'user_classes': '[MyUser1]'}), '(user_class... |
import csv
from io import BytesIO
import pandas as pd
from urllib.request import urlopen
from zipfile import ZipFile
def fetch_geds(url, subset=None):
'''
Fetches the geds dataset from Canada's Open Data Portal
Args:
url:
A string containing the url to the Canada Open Data Portal web ... | [
"pandas.DataFrame",
"csv.reader",
"urllib.request.urlopen"
] | [((813, 825), 'urllib.request.urlopen', 'urlopen', (['url'], {}), '(url)\n', (820, 825), False, 'from urllib.request import urlopen\n'), ((1748, 1789), 'pandas.DataFrame', 'pd.DataFrame', (['lines[1:]'], {'columns': 'lines[0]'}), '(lines[1:], columns=lines[0])\n', (1760, 1789), True, 'import pandas as pd\n'), ((1496, 1... |
import os
from tqdm import tqdm
from joblib import Parallel, delayed
try:
import seaborn as sns
except:
pass
import numpy as np
import cv2
from lost_ds.util import get_fs
from lost_ds.geometry.lost_geom import LOSTGeometries
from lost_ds.functional.api import remove_empty
def get_fontscale(fontscale, thic... | [
"seaborn.color_palette",
"numpy.where",
"tqdm.tqdm",
"lost_ds.util.get_fs",
"joblib.Parallel",
"numpy.zeros",
"numpy.array",
"lost_ds.geometry.lost_geom.LOSTGeometries",
"os.path.basename",
"joblib.delayed",
"lost_ds.functional.api.remove_empty"
] | [((1871, 1900), 'lost_ds.functional.api.remove_empty', 'remove_empty', (['df', '"""anno_data"""'], {}), "(df, 'anno_data')\n", (1883, 1900), False, 'from lost_ds.functional.api import remove_empty\n'), ((3667, 3685), 'lost_ds.util.get_fs', 'get_fs', (['filesystem'], {}), '(filesystem)\n', (3673, 3685), False, 'from los... |
from collections import deque
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor
from PyQt5.QtWidgets import QGraphicsRectItem
from cadnano.gui.palette import getNoPen
from cadnano.proxies.cnenum import StrandType
from .pathextras import PreXoverItem
class PreXoverManager(QGraphicsRectItem):
"""Summary
... | [
"cadnano.gui.palette.getNoPen",
"collections.deque",
"PyQt5.QtGui.QColor.fromHsvF"
] | [((1494, 1501), 'collections.deque', 'deque', ([], {}), '()\n', (1499, 1501), False, 'from collections import deque\n'), ((1095, 1105), 'cadnano.gui.palette.getNoPen', 'getNoPen', ([], {}), '()\n', (1103, 1105), False, 'from cadnano.gui.palette import getNoPen\n'), ((2532, 2573), 'PyQt5.QtGui.QColor.fromHsvF', 'QColor.... |
'''
decorators - decorators to help with flask applications
'''
# standard
from datetime import timedelta
from functools import update_wrapper
# pypi
from flask import make_response, request, current_app
def crossdomain(origin=None, methods=None, headers=None,
max_age=21600, attach_to_all=True,
... | [
"flask.current_app.make_default_options_response",
"functools.update_wrapper"
] | [((1797, 1840), 'flask.current_app.make_default_options_response', 'current_app.make_default_options_response', ([], {}), '()\n', (1838, 1840), False, 'from flask import make_response, request, current_app\n'), ((2640, 2675), 'functools.update_wrapper', 'update_wrapper', (['wrapped_function', 'f'], {}), '(wrapped_funct... |
def secondarybase64_layer5(nearing_the_end_script):
import base64
print("Secondary base64 encrypting")
joe = (nearing_the_end_script)
spliting = joe.encode('utf-8')
spliting = base64.b64encode(spliting)
spliting = spliting.decode('utf-8')
split_strings = []
n = int((len(spliting))/20)
for index in r... | [
"base64.b64encode"
] | [((187, 213), 'base64.b64encode', 'base64.b64encode', (['spliting'], {}), '(spliting)\n', (203, 213), False, 'import base64\n')] |
from flask_wtf import FlaskForm
from wtforms import PasswordField, SubmitField, StringField
from wtforms.validators import DataRequired, Length
class InstagramLoginForm(FlaskForm):
username = StringField('Instagram Username', validators=[DataRequired(),
... | [
"wtforms.validators.Length",
"wtforms.validators.DataRequired",
"wtforms.SubmitField"
] | [((430, 449), 'wtforms.SubmitField', 'SubmitField', (['"""Save"""'], {}), "('Save')\n", (441, 449), False, 'from wtforms import PasswordField, SubmitField, StringField\n'), ((244, 258), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (256, 258), False, 'from wtforms.validators import DataRequired, ... |
# NEEDS FIXING
# -*- coding: UTF-8 -*-
#######################################################################
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @tantrumdev wrote this file. As long as you retain this notice you
# can do whate... | [
"resources.lib.modules.cleantitle.geturl",
"urlparse.urljoin",
"urlparse.parse_qs",
"resources.lib.modules.client.request",
"re.compile",
"resources.lib.modules.directstream.googlepass",
"urllib.urlencode",
"resources.lib.modules.directstream.googletag",
"re.findall",
"resources.lib.modules.client... | [((4768, 4796), 'resources.lib.modules.directstream.googlepass', 'directstream.googlepass', (['url'], {}), '(url)\n', (4791, 4796), False, 'from resources.lib.modules import directstream\n'), ((1221, 1242), 'urllib.urlencode', 'urllib.urlencode', (['url'], {}), '(url)\n', (1237, 1242), False, 'import re, urllib, urlpar... |
import pytest
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
@pytest.mark.parametrize('name', [
('nodejs'),
])
def test_packages_are_installed(host, name):
package = host.package(name)... | [
"pytest.mark.parametrize"
] | [((192, 235), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""name"""', "['nodejs']"], {}), "('name', ['nodejs'])\n", (215, 235), False, 'import pytest\n'), ((356, 512), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""path,user,group"""', "[('/usr/bin/node', 'root', 'root'), ('/usr/bin/ncu', 'ro... |
"""
created by <NAME> at 1/8/19
"""
import os
import pandas as pd
def export_to_bed(gtf,intermediate_file_dir, lincRNA):
if lincRNA:
lincRNAIDs = pd.read_csv(os.path.join(intermediate_file_dir, 'intersect_total.txt'), names=['ids'], sep='\t')
exons = gtf[(gtf.feature == 'exon') & (gtf.seqname != '... | [
"os.path.isfile",
"gtfparse.read_gtf",
"os.path.join"
] | [((901, 948), 'os.path.join', 'os.path.join', (['intermediate_file_dir', '"""exon.bed"""'], {}), "(intermediate_file_dir, 'exon.bed')\n", (913, 948), False, 'import os\n'), ((1042, 1065), 'os.path.isfile', 'os.path.isfile', (['gtf_tsv'], {}), '(gtf_tsv)\n', (1056, 1065), False, 'import os\n'), ((1126, 1151), 'gtfparse.... |
import glob
import numpy as np
import os
import pandas as pd
import yaml
from dask_image.imread import imread
from dlclabel import misc
from itertools import groupby
from napari.layers import Shapes
from napari.plugins._builtins import napari_write_shapes
from napari.types import LayerData
from skimage.io import imsave... | [
"pandas.MultiIndex.from_frame",
"dlclabel.misc.DLCHeader",
"os.fspath",
"os.listdir",
"skimage.util.img_as_ubyte",
"os.path.split",
"numpy.issubdtype",
"napari.layers.Shapes",
"os.path.isdir",
"numpy.empty",
"pandas.DataFrame",
"pandas.read_hdf",
"glob.glob",
"os.path.splitext",
"os.path... | [((3236, 3270), 'dlclabel.misc.DLCHeader.from_config', 'misc.DLCHeader.from_config', (['config'], {}), '(config)\n', (3262, 3270), False, 'from dlclabel import misc\n'), ((4235, 4254), 'glob.glob', 'glob.glob', (['filename'], {}), '(filename)\n', (4244, 4254), False, 'import glob\n'), ((5697, 5747), 'pandas.DataFrame',... |
#!/usr/bin/env python2
# coding=utf-8
"""
The default per-repository configuration
"""
import sys
import json
import string
from os.path import exists, dirname
from gitver.defines import CFGFILE
from termcolors import term, bold
default_config_text = """{
# automatically generated configuration file
#
# ... | [
"os.path.exists",
"json.loads",
"string.split",
"os.path.dirname",
"termcolors.bold",
"sys.exit"
] | [((2214, 2238), 'string.split', 'string.split', (['text', '"""\n"""'], {}), "(text, '\\n')\n", (2226, 2238), False, 'import string\n'), ((2649, 2664), 'os.path.exists', 'exists', (['CFGFILE'], {}), '(CFGFILE)\n', (2655, 2664), False, 'from os.path import exists, dirname\n'), ((2684, 2700), 'os.path.dirname', 'dirname',... |
from random import randint
import re; import json
class Passenger:
def __init__(self, passengerId, passengerName, email, password, address, contact):
self.passengerId = passengerId
self.passengerName = passengerName
self.email = email
self.password = password
self.address = ... | [
"json.dumps",
"re.match",
"random.randint"
] | [((899, 939), 're.match', 're.match', (['regex', 'self.passengerObj.email'], {}), '(regex, self.passengerObj.email)\n', (907, 939), False, 'import re\n'), ((1764, 1821), 'json.dumps', 'json.dumps', (['[p.__dict__ for p in passengerList]'], {'indent': '(4)'}), '([p.__dict__ for p in passengerList], indent=4)\n', (1774, ... |
import torch
from torch.distributions import Uniform
from rl_sandbox.constants import CPU
class UniformPrior:
def __init__(self, low, high, device=torch.device(CPU)):
self.device = device
self.dist = Uniform(low=low, high=high)
def sample(self, num_samples):
return self.dist.rsample... | [
"torch.distributions.Uniform",
"torch.device"
] | [((155, 172), 'torch.device', 'torch.device', (['CPU'], {}), '(CPU)\n', (167, 172), False, 'import torch\n'), ((224, 251), 'torch.distributions.Uniform', 'Uniform', ([], {'low': 'low', 'high': 'high'}), '(low=low, high=high)\n', (231, 251), False, 'from torch.distributions import Uniform\n')] |
import tweepy
import csv
class dealWithTwitter:
def __init__(self):
self.access_token = ""
self.access_token_secret = ""
self.consumer_key = ""
self.consumer_secret = ""
self.api = ""
def loadTokens(self):
tokens = []
with open('pwd.txt') as pwd_file:
... | [
"tweepy.API",
"csv.writer",
"tweepy.OAuthHandler"
] | [((762, 822), 'tweepy.OAuthHandler', 'tweepy.OAuthHandler', (['self.consumer_key', 'self.consumer_secret'], {}), '(self.consumer_key, self.consumer_secret)\n', (781, 822), False, 'import tweepy\n'), ((909, 925), 'tweepy.API', 'tweepy.API', (['auth'], {}), '(auth)\n', (919, 925), False, 'import tweepy\n'), ((2171, 2184)... |
# TODO:
# - allow inheritance from GDScript class
# - overload native method ?
import pytest
from godot.bindings import ResourceLoader, GDScript, PluginScript
def test_native_method(node):
original_name = node.get_name()
try:
node.set_name("foo")
name = node.get_name()
ass... | [
"pytest.mark.xfail",
"pytest.mark.parametrize",
"godot.bindings.ResourceLoader.load"
] | [((1218, 1289), 'pytest.mark.xfail', 'pytest.mark.xfail', ([], {'reason': '"""default value seems to be only set in .tscn"""'}), "(reason='default value seems to be only set in .tscn')\n", (1235, 1289), False, 'import pytest\n'), ((2036, 2154), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""path,expected_t... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
"tvm.var",
"tvm.ir_pass.CanonicalSimplify",
"tvm.ir_builder.create",
"tvm.thread_axis"
] | [((832, 855), 'tvm.ir_builder.create', 'tvm.ir_builder.create', ([], {}), '()\n', (853, 855), False, 'import tvm\n'), ((944, 956), 'tvm.var', 'tvm.var', (['"""n"""'], {}), "('n')\n", (951, 956), False, 'import tvm\n'), ((1116, 1151), 'tvm.ir_pass.CanonicalSimplify', 'tvm.ir_pass.CanonicalSimplify', (['body'], {}), '(bo... |
"""The Worker class, which manages running policy evaluations."""
import datetime
import grpc
import gym
import os
from google.protobuf import empty_pb2
from proto.neuroevolution_pb2 import Evaluation, Individual
from proto.neuroevolution_pb2_grpc import NeuroStub
from worker.policy import Policy
ENVIRONMENT = os.ge... | [
"proto.neuroevolution_pb2.Individual",
"worker.policy.Policy",
"os.getenv",
"grpc.insecure_channel",
"datetime.datetime.now",
"google.protobuf.empty_pb2.Empty",
"gym.make"
] | [((315, 353), 'os.getenv', 'os.getenv', (['"""ENVIRONMENT"""', '"""Venture-v4"""'], {}), "('ENVIRONMENT', 'Venture-v4')\n", (324, 353), False, 'import os\n'), ((408, 438), 'os.getenv', 'os.getenv', (['"""HOST_PORT"""', '"""8080"""'], {}), "('HOST_PORT', '8080')\n", (417, 438), False, 'import os\n'), ((465, 504), 'os.ge... |
#!/usr/bin/python3
import json
import pprint
import sys
import os
import numpy as np
import traceback
import random
import argparse
import json
import tensorflow
import keras
from keras import optimizers
from keras.models import Sequential
from keras.models import load_model
from keras.layers import Conv2D, MaxPooling... | [
"keras.preprocessing.image.img_to_array",
"keras.layers.Conv2D",
"keras.callbacks.History",
"keras.layers.Activation",
"sys.exit",
"keras.layers.Dense",
"tensorflow.set_random_seed",
"keras.optimizers.Adadelta",
"os.path.exists",
"os.listdir",
"argparse.ArgumentParser",
"json.dumps",
"numpy.... | [((609, 627), 'numpy.random.seed', 'np.random.seed', (['(44)'], {}), '(44)\n', (623, 627), True, 'import numpy as np\n'), ((628, 643), 'random.seed', 'random.seed', (['(22)'], {}), '(22)\n', (639, 643), False, 'import random\n'), ((644, 674), 'tensorflow.set_random_seed', 'tensorflow.set_random_seed', (['(11)'], {}), '... |
from dataclasses import dataclass, field
from typing import List
from xml.etree.ElementTree import QName
__NAMESPACE__ = "http://schemas.microsoft.com/2003/10/Serialization/"
@dataclass
class Array:
class Meta:
namespace = "http://schemas.microsoft.com/2003/10/Serialization/"
item: List[object] = fi... | [
"xml.etree.ElementTree.QName",
"dataclasses.field"
] | [((318, 430), 'dataclasses.field', 'field', ([], {'default_factory': 'list', 'metadata': "{'name': 'Item', 'type': 'Element', 'namespace': '', 'nillable': True}"}), "(default_factory=list, metadata={'name': 'Item', 'type': 'Element',\n 'namespace': '', 'nillable': True})\n", (323, 430), False, 'from dataclasses impo... |
from __future__ import print_function
try:
import h5py
WITH_H5PY = True
except ImportError:
WITH_H5PY = False
try:
import zarr
WITH_ZARR = True
from .io import IoZarr
except ImportError:
WITH_ZARR = False
try:
import z5py
WITH_Z5PY = True
from .io import IoN5
except ImportError:
... | [
"toolz.pipe",
"re.compile",
"numpy.array",
"numpy.arange",
"os.path.exists",
"os.listdir",
"z5py.File",
"os.mkdir",
"json.loads",
"dask.delayed",
"random.shuffle",
"dask.compute",
"os.path.splitext",
"h5py.File",
"zarr.open",
"concurrent.futures.ThreadPoolExecutor",
"os.path.join",
... | [((592, 631), 'numpy.arange', 'np.arange', (['(0)', 'shape[0]', 'output_shape[0]'], {}), '(0, shape[0], output_shape[0])\n', (601, 631), True, 'import numpy as np\n'), ((968, 1007), 'numpy.arange', 'np.arange', (['(0)', 'shape[0]', 'output_shape[0]'], {}), '(0, shape[0], output_shape[0])\n', (977, 1007), True, 'import ... |
"""
Add the taxonomy to the patric metadata file
"""
import os
import sys
import argparse
from taxon import get_taxonomy_db, get_taxonomy
c = get_taxonomy_db()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Append taxonomy to the patric metadata file. This adds it at column 67")
par... | [
"taxon.get_taxonomy_db",
"argparse.ArgumentParser",
"taxon.get_taxonomy"
] | [((144, 161), 'taxon.get_taxonomy_db', 'get_taxonomy_db', ([], {}), '()\n', (159, 161), False, 'from taxon import get_taxonomy_db, get_taxonomy\n'), ((203, 317), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Append taxonomy to the patric metadata file. This adds it at column 67"""'}), "... |
"""
Writing actual code might be hard to understand for new-learners. Pseudocode is a tool
for writing algorithms without knowing how to code. This module contains classes and
methods for parsing pseudocode to AST and then evaluating it.
Example:
If you installed this module with pip you can run pseudocode from fi... | [
"pseudo.utils.append",
"pseudo.lexer.Lexer",
"gc.collect"
] | [((1001, 1018), 'pseudo.lexer.Lexer', 'Lexer', (['text_input'], {}), '(text_input)\n', (1006, 1018), False, 'from pseudo.lexer import Lexer\n'), ((1272, 1284), 'gc.collect', 'gc.collect', ([], {}), '()\n', (1282, 1284), False, 'import gc\n'), ((1230, 1253), 'pseudo.utils.append', 'append', (['instructions', 'x'], {}), ... |
import random
import os
import logging
import pickle
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
# import faiss
################################################################################
# General-... | [
"logging.getLogger",
"logging.StreamHandler",
"numpy.nanmean",
"logging.FileHandler",
"numpy.random.seed",
"numpy.bincount",
"torch.cuda.manual_seed_all",
"torch.manual_seed",
"pickle.dump",
"logging.Formatter",
"torch.stack",
"os.path.join",
"torch.nn.DataParallel",
"random.seed",
"nump... | [((539, 558), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (556, 558), False, 'import logging\n'), ((637, 666), 'logging.FileHandler', 'logging.FileHandler', (['log_path'], {}), '(log_path)\n', (656, 666), False, 'import logging\n'), ((841, 864), 'logging.StreamHandler', 'logging.StreamHandler', ([], {})... |
import feedparser
def read_rss_feed(feed_url):
feed = feedparser.parse(feed_url)
return [trim_entry(entry) for entry in feed.entries]
def trim_entry(entry):
return {
'date': "{}/{}/{}".format(entry.published_parsed.tm_year, entry.published_parsed.tm_mon, entry.published_parsed.tm_mday),
't... | [
"feedparser.parse"
] | [((59, 85), 'feedparser.parse', 'feedparser.parse', (['feed_url'], {}), '(feed_url)\n', (75, 85), False, 'import feedparser\n')] |
import asyncio
import datetime
import json
import logging
import os
import sys
import typing
from pathlib import Path
from typing import Any, Dict, Optional, Tuple
import discord
import toml
from discord.ext.commands import BadArgument
from pydantic import BaseModel
from pydantic import BaseSettings as PydanticBaseSet... | [
"logging.getLogger",
"pydantic.types.conint",
"pathlib.Path",
"discord.Colour.green",
"discord.Colour.red",
"os.getcwd",
"os.path.dirname",
"toml.load",
"discord.Colour.blurple",
"discord.Colour.blue"
] | [((462, 489), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (479, 489), False, 'import logging\n'), ((4295, 4314), 'pydantic.types.conint', 'conint', ([], {'ge': '(0)', 'le': '(50)'}), '(ge=0, le=50)\n', (4301, 4314), False, 'from pydantic.types import conint\n'), ((651, 676), 'os.path.d... |
# Copyright 2016, 2017 California Institute of Technology
# Users must agree to abide by the restrictions listed in the
# file "LegalStuff.txt" in the PROPER library directory.
#
# PROPER developed at Jet Propulsion Laboratory/California Inst. Technology
# Original IDL version by <NAME>
# Python translation... | [
"numpy.sqrt",
"math.cos",
"numpy.array",
"proper.prop_cubic_conv",
"proper.prop_get_sampling",
"numpy.arange",
"proper.prop_get_beamradius",
"proper.prop_get_gridsize",
"scipy.signal.fftconvolve",
"numpy.dot",
"numpy.vstack",
"numpy.meshgrid",
"numpy.tile",
"numpy.ones",
"proper.prop_fit... | [((592, 624), 'os.path.dirname', 'os.path.dirname', (['proper.__file__'], {}), '(proper.__file__)\n', (607, 624), False, 'import os\n'), ((4461, 4489), 'proper.prop_get_gridsize', 'proper.prop_get_gridsize', (['wf'], {}), '(wf)\n', (4485, 4489), False, 'import proper\n'), ((4504, 4532), 'proper.prop_get_sampling', 'pro... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... | [
"numpy.array",
"numpy.random.randint",
"numpy.random.randn",
"numpy.zeros"
] | [((866, 892), 'numpy.random.randn', 'np.random.randn', (['*img_size'], {}), '(*img_size)\n', (881, 892), True, 'import numpy as np\n'), ((910, 943), 'numpy.random.randint', 'np.random.randint', (['(0)', 'num_classes'], {}), '(0, num_classes)\n', (927, 943), True, 'import numpy as np\n'), ((1053, 1083), 'numpy.zeros', '... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016, 2017, 2018, 2019 Sqreen. All rights reserved.
# Please refer to our terms for more information:
#
# https://www.sqreen.io/terms.html
#
import logging
import traceback
from datetime import datetime
from ..runtime_storage import runtime
from ..utils import is_string
LO... | [
"logging.getLogger",
"traceback.format_stack",
"datetime.datetime.utcnow"
] | [((327, 354), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (344, 354), False, 'import logging\n'), ((973, 990), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (988, 990), False, 'from datetime import datetime\n'), ((2949, 2973), 'traceback.format_stack', 'traceback.for... |
import json
import pickle
import re
from copy import copy, deepcopy
from functools import lru_cache
from json import JSONDecodeError
from os import system, walk, sep
from abc import ABC, abstractmethod
from pathlib import Path
import time
from subprocess import check_output
from tempfile import NamedTemporaryFile
from ... | [
"data_vault.parsing.split_variables",
"os.sep.join",
"data_vault.parsing.unquote",
"copy.deepcopy",
"datetime.datetime.today",
"datetime.timedelta",
"copy.copy",
"os.walk",
"pathlib.Path",
"re.finditer",
"tempfile.NamedTemporaryFile",
"warnings.warn",
"data_vault.VaultMagics",
"subprocess.... | [((5937, 5951), 'copy.copy', 'copy', (['notebook'], {}), '(notebook)\n', (5941, 5951), False, 'from copy import copy, deepcopy\n'), ((13683, 13694), 'functools.lru_cache', 'lru_cache', ([], {}), '()\n', (13692, 13694), False, 'from functools import lru_cache\n'), ((20806, 20854), 'subprocess.check_output', 'check_outpu... |
import math
from stable_baselines_model_based_rl.wrapper.step_handler import StepRewardDoneHandler
class ContinuousMountainCarStepHandler(StepRewardDoneHandler):
goal_position = 0.45
goal_velocity = 0
def get_done(self, step: int) -> bool:
s = self.observation.to_value_list()
... | [
"math.pow"
] | [((731, 753), 'math.pow', 'math.pow', (['action[0]', '(2)'], {}), '(action[0], 2)\n', (739, 753), False, 'import math\n')] |
#!/usr/bin/env python3
import os
import sys
import json
from datetime import datetime
from submitty_utils import dateutils
def generatePossibleDatabases():
current = dateutils.get_current_semester()
pre = 'submitty_' + current + '_'
path = "/var/local/submitty/courses/" + current
return [pre + name for name in ... | [
"os.listdir",
"submitty_utils.dateutils.get_current_semester",
"os.path.join",
"datetime.datetime.now",
"os.path.isdir",
"sys.exit"
] | [((171, 203), 'submitty_utils.dateutils.get_current_semester', 'dateutils.get_current_semester', ([], {}), '()\n', (201, 203), False, 'from submitty_utils import dateutils\n'), ((596, 606), 'sys.exit', 'sys.exit', ([], {}), '()\n', (604, 606), False, 'import sys\n'), ((1933, 1943), 'sys.exit', 'sys.exit', ([], {}), '()... |
# Copyright (c) 2017, IGLU consortium
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and... | [
"logging.basicConfig",
"multiprocessing.Process",
"panda3d.core.LVector3f",
"numpy.min",
"time.sleep",
"numpy.max",
"os.path.realpath",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.close",
"home_platform.env.BasicEnvironment",
"unittest.main",
"matplotlib.pyplo... | [((4506, 4545), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.WARN'}), '(level=logging.WARN)\n', (4525, 4545), False, 'import logging\n'), ((4550, 4572), 'numpy.seterr', 'np.seterr', ([], {'all': '"""raise"""'}), "(all='raise')\n", (4559, 4572), True, 'import numpy as np\n'), ((4577, 4592), 'uni... |
#!/usr/bin/env python
"""
_selfupdate_
Util command for updating the cirrus install itself
Supports getting a spefified branch or tag, or defaults to
looking up the latest release and using that instead.
"""
import sys
import argparse
import arrow
import os
import requests
import inspect
import contextlib
from cirru... | [
"inspect.getsourcefile",
"cirrus.configuration.load_configuration",
"cirrus.environment.virtualenv_home",
"argparse.ArgumentParser",
"cirrus.git_tools.update_to_branch",
"requests.get",
"os.getcwd",
"cirrus.logger.get_logger",
"os.path.dirname",
"cirrus.environment.is_anaconda",
"arrow.get",
"... | [((644, 656), 'cirrus.logger.get_logger', 'get_logger', ([], {}), '()\n', (654, 656), False, 'from cirrus.logger import get_logger\n'), ((787, 798), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (796, 798), False, 'import os\n'), ((1060, 1163), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"... |
from base_bot import log
def atoi(text):
return int(text) if text.isdigit() else text
def bool_to_emoticon(value):
return value and "✅" or "❌"
# https://stackoverflow.com/questions/7204805/how-to-merge-dictionaries-of-dictionaries
# merges b into a
def merge(a, b, path=None):
if path is None: path = [... | [
"base_bot.log.debug"
] | [((1108, 1209), 'base_bot.log.debug', 'log.debug', (['f"""[{guild}][{message.channel}][{message.author.display_name}] {message.content}"""'], {}), "(\n f'[{guild}][{message.channel}][{message.author.display_name}] {message.content}'\n )\n", (1117, 1209), False, 'from base_bot import log\n')] |
from jsgf import parse_grammar_string
def main(args):
# Parse input grammar file.
with open(args.input_file_path, "r") as fp:
text = fp.read()
print("\ninput grammar: ")
print(text)
grammar = parse_grammar_string(text)
# Print it.
print("\noutput grammar: ")
text = ... | [
"jsgf.parse_grammar_string",
"argparse.ArgumentParser"
] | [((588, 652), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""expand JSGF grammar tags."""'}), "(description='expand JSGF grammar tags.')\n", (611, 652), False, 'import argparse\n'), ((233, 259), 'jsgf.parse_grammar_string', 'parse_grammar_string', (['text'], {}), '(text)\n', (253, 259), ... |