code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
#!/usr/bin/env python
import time
import unittest
def solution(array):
odd = set()
for x in array:
if x in odd:
odd.remove(x)
else:
odd.add(x)
return odd.pop()
class Tests(unittest.TestCase):
"""Tests for OddOccurrencesInArray solution"""
def test_from_ta... | [
"unittest.main"
] | [((473, 488), 'unittest.main', 'unittest.main', ([], {}), '()\n', (486, 488), False, 'import unittest\n')] |
from django.utils.translation import ugettext_lazy as _
import horizon
from horizon_telemetry import dashboard
class Control(horizon.Panel):
name = _("Control nodes")
slug = 'control'
permissions = ('openstack.roles.admin',)
dashboard.Telemetry.register(Control)
| [
"django.utils.translation.ugettext_lazy",
"horizon_telemetry.dashboard.Telemetry.register"
] | [((243, 280), 'horizon_telemetry.dashboard.Telemetry.register', 'dashboard.Telemetry.register', (['Control'], {}), '(Control)\n', (271, 280), False, 'from horizon_telemetry import dashboard\n'), ((156, 174), 'django.utils.translation.ugettext_lazy', '_', (['"""Control nodes"""'], {}), "('Control nodes')\n", (157, 174),... |
import numpy as np
import sklearn.dummy
import sklearn.linear_model
def eta_string(time_points, remaining_works):
return format_timedelta(eta(time_points, remaining_works))
def eta(time_points, remaining_works, regression_points_used=200):
"""Estimate the time remaining until completion of a task based on s... | [
"numpy.interp",
"numpy.asarray",
"numpy.expand_dims",
"numpy.isnan"
] | [((991, 1014), 'numpy.asarray', 'np.asarray', (['time_points'], {}), '(time_points)\n', (1001, 1014), True, 'import numpy as np\n'), ((1037, 1064), 'numpy.asarray', 'np.asarray', (['remaining_works'], {}), '(remaining_works)\n', (1047, 1064), True, 'import numpy as np\n'), ((2097, 2125), 'numpy.interp', 'np.interp', ([... |
import os
import pathlib
import textwrap
from .errors import ValidationError
from .validators import IsInstance
class UnboundField:
_configuration_field = True
creation_counter = 0
def __init__(self, field_class, *args, **kwargs):
UnboundField.creation_counter += 1
self.field_class = fie... | [
"os.linesep.join",
"pathlib.Path"
] | [((4445, 4469), 'pathlib.Path', 'pathlib.Path', (['self._data'], {}), '(self._data)\n', (4457, 4469), False, 'import pathlib\n'), ((2214, 2239), 'os.linesep.join', 'os.linesep.join', (['extended'], {}), '(extended)\n', (2229, 2239), False, 'import os\n')] |
############################
#### Crawl NTSB reports ####
############################
#import urllib.request -> use for python3
from urllib2 import urlopen
from bs4 import BeautifulSoup
import re
import pandas as pd
# define main function
def crawl_reportdata():
#################################################... | [
"bs4.BeautifulSoup",
"pandas.to_datetime",
"urllib2.urlopen"
] | [((379, 466), 'urllib2.urlopen', 'urlopen', (['"""https://www.ntsb.gov/investigations/AccidentReports/Pages/aviation.aspx"""'], {}), "(\n 'https://www.ntsb.gov/investigations/AccidentReports/Pages/aviation.aspx')\n", (386, 466), False, 'from urllib2 import urlopen\n'), ((473, 507), 'bs4.BeautifulSoup', 'BeautifulSou... |
import json
import tempfile
from pathlib import Path
import mock
import pytest
from dateutil.parser import parse as dateparser
from core.models import TweetStats, Wordcloud
from core.twitter import utils
from core.twitter.utils import TIMESERIES, SENTIMENT_TIMESERIES
def test_get_tweet_sentiment():
text = "I am... | [
"tempfile.NamedTemporaryFile",
"core.models.Wordcloud.objects.create",
"dateutil.parser.parse",
"core.twitter.utils.calculate_percentage",
"core.twitter.utils.get_timeseries_data",
"core.twitter.utils.clean_tweet",
"core.twitter.utils.get_tweet_sentiment",
"mock.patch",
"pytest.mark.django_db",
"c... | [((735, 768), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""tweets"""'], {}), "('tweets')\n", (758, 768), False, 'import pytest\n'), ((1359, 1429), 'mock.patch', 'mock.patch', (['"""core.models.TweetStats.get_all_time_sentiment_difference"""'], {}), "('core.models.TweetStats.get_all_time_sentiment_differe... |
import batoid
import numpy as np
from test_helpers import timer
@timer
def test_rSplit():
for i in range(100):
R = np.random.normal(0.7, 0.8)
conic = np.random.uniform(-2.0, 1.0)
ncoef = np.random.randint(0, 4)
coefs = [np.random.normal(0, 1e-10) for i in range(ncoef)]
asph... | [
"numpy.random.uniform",
"batoid.SimpleCoating",
"batoid.Asphere",
"batoid.ConstMedium",
"batoid.Air",
"numpy.random.randint",
"numpy.random.normal"
] | [((129, 155), 'numpy.random.normal', 'np.random.normal', (['(0.7)', '(0.8)'], {}), '(0.7, 0.8)\n', (145, 155), True, 'import numpy as np\n'), ((172, 200), 'numpy.random.uniform', 'np.random.uniform', (['(-2.0)', '(1.0)'], {}), '(-2.0, 1.0)\n', (189, 200), True, 'import numpy as np\n'), ((217, 240), 'numpy.random.randin... |
from argparse import ArgumentParser
from copy import deepcopy
import json
import random
import spacy
from rouge import Rouge
from tqdm import tqdm
import numpy as np
from collections import defaultdict
import functools
import operator
from gensim.models import Word2Vec
import streamlit as st
import requests
import bs4
... | [
"streamlit.text_input",
"argparse.ArgumentParser",
"random.shuffle",
"streamlit.title",
"collections.defaultdict",
"numpy.mean",
"streamlit.subheader",
"rouge.Rouge",
"spacy.load",
"random.seed",
"requests.get",
"re.sub",
"copy.deepcopy",
"tqdm.tqdm",
"bs4.BeautifulSoup",
"re.compile",... | [((338, 403), 'spacy.load', 'spacy.load', (['"""en_core_web_lg"""'], {'disable': "['tagger', 'ner', 'parser']"}), "('en_core_web_lg', disable=['tagger', 'ner', 'parser'])\n", (348, 403), False, 'import spacy\n'), ((2851, 2890), 'rouge.Rouge', 'Rouge', ([], {'metrics': "['rouge-1']", 'stats': "['f']"}), "(metrics=['roug... |
from phycas import P
from phycas.utilities.PhycasCommand import *
from phycas.commands.RandomTreeImpl import TreeSimulator
from phycas.probdist import Exponential
import copy
class RandomTree(PhycasCommand):
def __init__(self):
args = tuple(
PhycasCommand._getRNGOptions() +
... | [
"copy.deepcopy",
"phycas.probdist.Exponential",
"phycas.commands.RandomTreeImpl.TreeSimulator"
] | [((1715, 1734), 'copy.deepcopy', 'copy.deepcopy', (['self'], {}), '(self)\n', (1728, 1734), False, 'import copy\n'), ((1750, 1766), 'phycas.commands.RandomTreeImpl.TreeSimulator', 'TreeSimulator', (['c'], {}), '(c)\n', (1763, 1766), False, 'from phycas.commands.RandomTreeImpl import TreeSimulator\n'), ((648, 665), 'phy... |
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from pytorch_lightning import LightningModule, Trainer
from high_order_layers_torch.FunctionalConvolution impor... | [
"pytorch_lightning.Trainer",
"torch.utils.data.DataLoader",
"torch.argmax",
"pytorch_lightning.metrics.functional.accuracy",
"torch.cat",
"torch.nn.functional.cross_entropy",
"torch.nn.functional.nll_loss",
"torch.nn.Linear",
"torchvision.transforms.Normalize",
"torchvision.datasets.MNIST",
"tor... | [((3155, 3184), 'pytorch_lightning.Trainer', 'Trainer', ([], {'max_epochs': '(2)', 'gpus': '(1)'}), '(max_epochs=2, gpus=1)\n', (3162, 3184), False, 'from pytorch_lightning import LightningModule, Trainer\n'), ((672, 693), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (691, 693), True, 'im... |
import argparse
import os
import torch
import itertools
from game.Player import RandomPlayer
from ai.HeuristicPlayer import HeuristicPlayer1, HeuristicPlayer2
from ai.RLPlayer import RLPlayer
from ai.EAPlayer import EAPlayer
from game.Game import Game
import numpy as np
from tqdm import tqdm
def parse_args():
p... | [
"ai.EAPlayer.EAPlayer",
"os.mkdir",
"game.Player.RandomPlayer",
"ai.RLPlayer.RLPlayer",
"numpy.count_nonzero",
"argparse.ArgumentParser",
"game.Game.Game",
"numpy.savetxt",
"numpy.genfromtxt",
"itertools.combinations_with_replacement",
"ai.HeuristicPlayer.HeuristicPlayer2",
"torch.cuda.is_avai... | [((328, 353), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (351, 353), False, 'import argparse\n'), ((1301, 1341), 'game.Game.Game', 'Game', (['(2)', '(0)'], {'config_path': 'args.config_path'}), '(2, 0, config_path=args.config_path)\n', (1305, 1341), False, 'from game.Game import Game\n'), (... |
import sys
import re
import subprocess
import wikipedia
import logging
import peewee
from datetime import date
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen
from db.models import Definitions
class Searcher:
def local_news(self, city):
news_url = f"https://news.google.com/news/rss/head... | [
"wikipedia.page",
"db.models.Definitions.id.desc",
"urllib.request.urlopen",
"datetime.date.today",
"bs4.BeautifulSoup",
"re.sub",
"db.models.Definitions.select"
] | [((359, 376), 'urllib.request.urlopen', 'urlopen', (['news_url'], {}), '(news_url)\n', (366, 376), False, 'from urllib.request import urlopen\n'), ((441, 462), 'bs4.BeautifulSoup', 'soup', (['xml_page', '"""xml"""'], {}), "(xml_page, 'xml')\n", (445, 462), True, 'from bs4 import BeautifulSoup as soup\n'), ((874, 891), ... |
import turtle
#wn = turtle.Screen()
#wn.bgcolor("lightgreen") # Set the window background color
#wn.title("Hello, Tess!") # Set the window title
#tess = turtle.Turtle()
'''tess=turtle.Pen()
tess.color("blue") # Tell tess to change her color
tess.pensize(3) # Tell tess to set her pen ... | [
"turtle.pensize",
"turtle.end_fill",
"turtle.forward",
"turtle.begin_fill",
"turtle.exitonclick",
"turtle.left",
"turtle.color"
] | [((411, 430), 'turtle.begin_fill', 'turtle.begin_fill', ([], {}), '()\n', (428, 430), False, 'import turtle\n'), ((431, 451), 'turtle.color', 'turtle.color', (['"""blue"""'], {}), "('blue')\n", (443, 451), False, 'import turtle\n'), ((495, 512), 'turtle.pensize', 'turtle.pensize', (['(3)'], {}), '(3)\n', (509, 512), Fa... |
from discord.ext import commands
import aiohttp
import json
import discord
from lxml import etree
import os
import glob
class cpp(commands.Cog, name="C++"):
"""Commands made for C++
Don't abuse these.
"""
def __init__(self, bot):
self.bot = bot
def get_directory_files(self, query, direc... | [
"discord.utils.escape_markdown",
"discord.ext.commands.command",
"discord.Embed",
"os.path.isdir",
"glob.iglob"
] | [((1137, 1155), 'discord.ext.commands.command', 'commands.command', ([], {}), '()\n', (1153, 1155), False, 'from discord.ext import commands\n'), ((347, 375), 'glob.iglob', 'glob.iglob', (['f"""{directory}/*"""'], {}), "(f'{directory}/*')\n", (357, 375), False, 'import glob\n'), ((1415, 1430), 'discord.Embed', 'discord... |
import logging
from fastapi import APIRouter, Depends, HTTPException
from starlette import status
from api.dependencies.authentication import extract_auth_information
from api.dependencies.database import get_repository
from api.dependencies.workspaces import get_workspace_by_workspace_id_from_path
from api.dependenc... | [
"api.dependencies.authentication.get_access_service",
"models.schemas.workspace.WorkspaceIdInResponse",
"logging.error",
"fastapi.HTTPException",
"api.dependencies.authentication.extract_auth_information",
"api.dependencies.database.get_repository",
"models.schemas.workspace.WorkspaceInResponse",
"ser... | [((1067, 1092), 'fastapi.Depends', 'Depends', (['get_current_user'], {}), '(get_current_user)\n', (1074, 1092), False, 'from fastapi import APIRouter, Depends, HTTPException\n'), ((1291, 1311), 'api.dependencies.authentication.get_access_service', 'get_access_service', ([], {}), '()\n', (1309, 1311), False, 'from api.d... |
from django.db import models
import datetime as dt
# Create your models here.
class Category(models.Model):
CATEGORIES =(("Travel","Travel"),("Food","Food"),("Fashion","Fashion"),("Movies","Movies"))
image_category = models.CharField(max_length=40,choices=CATEGORIES,)
def save_category(self):
sel... | [
"django.db.models.TextField",
"django.db.models.CharField",
"django.db.models.ForeignKey",
"django.db.models.ImageField",
"django.db.models.DateTimeField"
] | [((227, 278), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(40)', 'choices': 'CATEGORIES'}), '(max_length=40, choices=CATEGORIES)\n', (243, 278), False, 'from django.db import models\n'), ((776, 826), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(40)', 'choices': 'LOC... |
from functools import reduce
from typing import Dict, List
from pathlib import Path
from nesim.devices.device import Device
from nesim.devices.cable import DuplexCableHead
class Hub(Device):
"""
Representa un Hub en la simulaciรณn.
Parameters
----------
name : str
Nombre del hub.
ports_... | [
"functools.reduce",
"pathlib.Path"
] | [((1014, 1024), 'pathlib.Path', 'Path', (['path'], {}), '(path)\n', (1018, 1024), False, 'from pathlib import Path\n'), ((1120, 1144), 'pathlib.Path', 'Path', (['f"""{self.name}.txt"""'], {}), "(f'{self.name}.txt')\n", (1124, 1144), False, 'from pathlib import Path\n'), ((3470, 3509), 'functools.reduce', 'reduce', (['(... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from kombu.exceptions import SerializerNotInstalled
from . import fernet_encode, fernet_decode
try:
try:
from msgpack import packb as pack, unpackb
unpack = lambda s: unpackb(s, encoding='utf-8')
except ImportErr... | [
"kombu.exceptions.SerializerNotInstalled",
"msgpack.unpackb"
] | [((271, 299), 'msgpack.unpackb', 'unpackb', (['s'], {'encoding': '"""utf-8"""'}), "(s, encoding='utf-8')\n", (278, 299), False, 'from msgpack import packb as pack, unpackb\n'), ((619, 718), 'kombu.exceptions.SerializerNotInstalled', 'SerializerNotInstalled', (['"""No decoder installed for msgpack. Please install the ms... |
from os import listdir
from os.path import isfile, join
from enot.packages.config.config import ConfigFile
from enot.packages.config.enot import EnotConfig
from enot.packages.config.erlang_mk import ErlangMkConfig
from enot.packages.config.rebar import RebarConfig
def read_project(path: str, url=None) -> ConfigFile:... | [
"enot.packages.config.rebar.RebarConfig",
"enot.packages.config.enot.EnotConfig.from_path",
"enot.packages.config.erlang_mk.ErlangMkConfig",
"os.path.join",
"os.listdir"
] | [((706, 719), 'os.listdir', 'listdir', (['path'], {}), '(path)\n', (713, 719), False, 'from os import listdir\n'), ((400, 435), 'enot.packages.config.enot.EnotConfig.from_path', 'EnotConfig.from_path', (['path'], {'url': 'url'}), '(path, url=url)\n', (420, 435), False, 'from enot.packages.config.enot import EnotConfig\... |
#!/usr/bin/env python
# coding=utf-8
from __future__ import unicode_literals
from pyecharts import Map
import json
import codecs
def test_map():
# map_0
value = [155, 10, 66, 78]
attr = ["็ฆๅปบ", "ๅฑฑไธ", "ๅไบฌ", "ไธๆตท"]
map = Map("ๅ
จๅฝๅฐๅพ็คบไพ", width=1200, height=600)
map.add("", attr, value, maptype='china')... | [
"codecs.open",
"pyecharts.Map",
"json.dumps"
] | [((237, 274), 'pyecharts.Map', 'Map', (['"""ๅ
จๅฝๅฐๅพ็คบไพ"""'], {'width': '(1200)', 'height': '(600)'}), "('ๅ
จๅฝๅฐๅพ็คบไพ', width=1200, height=600)\n", (240, 274), False, 'from pyecharts import Map\n'), ((480, 530), 'pyecharts.Map', 'Map', (['"""Map ็ปๅ VisualMap ็คบไพ"""'], {'width': '(1200)', 'height': '(600)'}), "('Map ็ปๅ VisualMap ็คบ... |
import sys
sys.path.append('../common')
from common.exit_codes import *
def test_exit_code():
assert ExitCode.bad_arg.value[0] == 2
assert ExitCode.exception.value[0] == 5
assert ExitCode.success.value[1] == 'success -- program completed normally'
| [
"sys.path.append"
] | [((11, 39), 'sys.path.append', 'sys.path.append', (['"""../common"""'], {}), "('../common')\n", (26, 39), False, 'import sys\n')] |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def morley(path):
"""Michelson Speed of Light Data
A classical data of... | [
"observations.util.maybe_download_and_extract",
"os.path.expanduser",
"os.path.join"
] | [((1830, 1854), 'os.path.expanduser', 'os.path.expanduser', (['path'], {}), '(path)\n', (1848, 1854), False, 'import os\n'), ((2001, 2086), 'observations.util.maybe_download_and_extract', 'maybe_download_and_extract', (['path', 'url'], {'save_file_name': '"""morley.csv"""', 'resume': '(False)'}), "(path, url, save_file... |
from dataclasses import dataclass
from itertools import cycle
from typing import Iterable, Iterator, cast
import parse
FORMAT = parse.compile("Player {player:d} starting position: {position:d}")
def read() -> Iterator[int]:
with open("d21/input.txt") as f:
for line in f:
yield cast(parse.Resu... | [
"itertools.cycle",
"parse.compile"
] | [((129, 195), 'parse.compile', 'parse.compile', (['"""Player {player:d} starting position: {position:d}"""'], {}), "('Player {player:d} starting position: {position:d}')\n", (142, 195), False, 'import parse\n'), ((1018, 1032), 'itertools.cycle', 'cycle', (['players'], {}), '(players)\n', (1023, 1032), False, 'from iter... |
"""Assignments API Version 1.0.
This API client was generated using a template. Make sure this code is valid before using it.
"""
import logging
from datetime import date, datetime
from .base import BaseCanvasAPI
from .base import BaseModel
class AssignmentsAPI(BaseCanvasAPI):
"""Assignments API Version 1.0."""
... | [
"logging.getLogger"
] | [((492, 537), 'logging.getLogger', 'logging.getLogger', (['"""py3canvas.AssignmentsAPI"""'], {}), "('py3canvas.AssignmentsAPI')\n", (509, 537), False, 'import logging\n'), ((79230, 79286), 'logging.getLogger', 'logging.getLogger', (['"""py3canvas.Externaltooltagattributes"""'], {}), "('py3canvas.Externaltooltagattribut... |
from ofptHeader import ofptHeader
from generateMatch import generateMatch
from os import urandom
from random import randint
from struct import Struct
def ofptPacketIn(maxLength):
payloadLength = randint(18 + 4 + 14, maxLength - 8)
bufferId = urandom(4)
totalLen = urandom(2)
reason = Struct('! B').pack(randint(0,... | [
"ofptHeader.ofptHeader",
"struct.Struct",
"generateMatch.generateMatch",
"random.randint",
"os.urandom"
] | [((198, 233), 'random.randint', 'randint', (['(18 + 4 + 14)', '(maxLength - 8)'], {}), '(18 + 4 + 14, maxLength - 8)\n', (205, 233), False, 'from random import randint\n'), ((247, 257), 'os.urandom', 'urandom', (['(4)'], {}), '(4)\n', (254, 257), False, 'from os import urandom\n'), ((270, 280), 'os.urandom', 'urandom',... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import math
def main():
n, k = map(int, input().split())
base = int(k * (k + 1) / 2)
if n < base:
print('-1')
return
closest = None
for i in range(base, int(math.sqrt(n))):
if n % i == 0:
closest = i
... | [
"math.sqrt"
] | [((252, 264), 'math.sqrt', 'math.sqrt', (['n'], {}), '(n)\n', (261, 264), False, 'import math\n'), ((384, 396), 'math.sqrt', 'math.sqrt', (['n'], {}), '(n)\n', (393, 396), False, 'import math\n')] |
"""
Copyright 2019 <NAME>.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distribut... | [
"gs_quant.api.gs.backtests.GsBacktestApi.get_results"
] | [((1108, 1154), 'gs_quant.api.gs.backtests.GsBacktestApi.get_results', 'GsBacktestApi.get_results', ([], {'backtest_id': 'self.id'}), '(backtest_id=self.id)\n', (1133, 1154), False, 'from gs_quant.api.gs.backtests import GsBacktestApi\n')] |
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import sys
import os
import pytest
from mock import patch
sys.path.insert(0, os.path.abspath('./'))
from feuersoftware import PublicAPI
TOKEN = '<KEY>'\
'<KEY>'\
'<KEY>'\
'<KEY>cZ4JstLj05y4r7jt81g4DYXz9gVYc'\
'UWk2pOkIZ9RPmu0s4LlaXHEK3TJl... | [
"os.path.abspath",
"feuersoftware.PublicAPI",
"mock.patch"
] | [((547, 589), 'mock.patch', 'patch', (['"""feuersoftware.logging.Logger.info"""'], {}), "('feuersoftware.logging.Logger.info')\n", (552, 589), False, 'from mock import patch\n'), ((591, 622), 'mock.patch', 'patch', (['"""feuersoftware.requests"""'], {}), "('feuersoftware.requests')\n", (596, 622), False, 'from mock imp... |
#!/usr/bin/env python3
# encoding: utf-8
"""deathgod.py -- the entry point for Death God
That is to say, this starts the game.
Public Members:
main
"""
import sys
import pygame
from deathgod.game import Game
def main():
"""This is Death God's main function."""
# create a new game object
game_obj = G... | [
"pygame.quit",
"deathgod.game.Game"
] | [((319, 325), 'deathgod.game.Game', 'Game', ([], {}), '()\n', (323, 325), False, 'from deathgod.game import Game\n'), ((389, 402), 'pygame.quit', 'pygame.quit', ([], {}), '()\n', (400, 402), False, 'import pygame\n')] |
import pytest
from torch import rand
from torchtyping import TensorType
from typeguard import typechecked
x = y = None
def test_single():
@typechecked
def func1(x: TensorType["x"], y: TensorType["x"]):
pass
@typechecked
def func2(x: TensorType["x"], y: TensorType["x"]) -> TensorType["x"]:
... | [
"pytest.raises",
"torch.rand"
] | [((948, 958), 'torch.rand', 'rand', (['(1,)'], {}), '((1,))\n', (952, 958), False, 'from torch import rand\n'), ((970, 977), 'torch.rand', 'rand', (['(2)'], {}), '(2)\n', (974, 977), False, 'from torch import rand\n'), ((979, 986), 'torch.rand', 'rand', (['(2)'], {}), '(2)\n', (983, 986), False, 'from torch import rand... |
import numpy as np
from sgp4.api import Satrec
from astropy.io import ascii
def minmaxloc(num_list):
return np.argmin(num_list), np.argmax(num_list)
np.set_printoptions(precision=2)
with open('hipparcos-tle.txt', 'r') as f:
st = f.read().split('\n')
jds = np.genfromtxt("hipparcos_tle_jd.txt", dtype=None)
N... | [
"numpy.set_printoptions",
"numpy.argmax",
"sgp4.api.Satrec.twoline2rv",
"numpy.savetxt",
"numpy.zeros",
"numpy.genfromtxt",
"numpy.argmin",
"numpy.where",
"numpy.modf",
"numpy.concatenate"
] | [((156, 188), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(2)'}), '(precision=2)\n', (175, 188), True, 'import numpy as np\n'), ((269, 318), 'numpy.genfromtxt', 'np.genfromtxt', (['"""hipparcos_tle_jd.txt"""'], {'dtype': 'None'}), "('hipparcos_tle_jd.txt', dtype=None)\n", (282, 318), True, 'imp... |
import random
import unittest
class TestTrader(unittest.TestCase):
def buildInformedTrader2(self, informedMaxQ, informedRunLength, informedTrades, prime1):
''' Informed trader id starts with 5
'''
informed = InformedTrader(5000, informedMaxQ)
numChoices = int(informe... | [
"random.choice"
] | [((549, 575), 'random.choice', 'random.choice', (['choiceRange'], {}), '(choiceRange)\n', (562, 575), False, 'import random\n')] |
'''
Theorem 1
this script is a brute-force verification that the scalar local Lipschitz
result is true
'''
import numpy as np
def relu(y):
return (y>0)*y
def lip(y0,y):
return np.abs(relu(y) - relu(y0))/np.abs(y-y0)
# setup
n_trials = 10**4
n_samps = 7
lip_anl = np.full(n_trials, np.nan)
lip_brute = np.full... | [
"numpy.full",
"numpy.random.uniform",
"numpy.abs",
"numpy.max",
"numpy.linalg.norm"
] | [((275, 300), 'numpy.full', 'np.full', (['n_trials', 'np.nan'], {}), '(n_trials, np.nan)\n', (282, 300), True, 'import numpy as np\n'), ((313, 338), 'numpy.full', 'np.full', (['n_trials', 'np.nan'], {}), '(n_trials, np.nan)\n', (320, 338), True, 'import numpy as np\n'), ((726, 750), 'numpy.linalg.norm', 'np.linalg.norm... |
"""
2016 Day 8
https://adventofcode.com/2016/day/8
"""
from typing import Callable, Sequence, Tuple
import re
import numpy as np
import aocd # type: ignore
def blank_screen() -> np.ndarray:
"""
Create an empty 50x6 array.
"""
return np.array([[0 for col in range(50)] for row in range(6)], int)
def... | [
"numpy.roll",
"numpy.rot90",
"aocd.get_data",
"re.compile"
] | [((935, 964), 'numpy.rot90', 'np.rot90', (['screen'], {'axes': '(1, 0)'}), '(screen, axes=(1, 0))\n', (943, 964), True, 'import numpy as np\n'), ((1032, 1061), 'numpy.rot90', 'np.rot90', (['rolled'], {'axes': '(0, 1)'}), '(rolled, axes=(0, 1))\n', (1040, 1061), True, 'import numpy as np\n'), ((2627, 2658), 'aocd.get_da... |
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
import numpy as np
import os
if __name__ == "__main__":
# Load trained model
model = keras.models.load_model("../paper_results/3d_optmock_6par/models/3D_21cmPIE_Net")
# Plot each of the 32 filters from the first convolutio... | [
"matplotlib.pyplot.tight_layout",
"tensorflow.keras.models.load_model",
"os.makedirs",
"matplotlib.pyplot.close",
"matplotlib.pyplot.yticks",
"numpy.mean",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.subplots"
] | [((179, 265), 'tensorflow.keras.models.load_model', 'keras.models.load_model', (['"""../paper_results/3d_optmock_6par/models/3D_21cmPIE_Net"""'], {}), "(\n '../paper_results/3d_optmock_6par/models/3D_21cmPIE_Net')\n", (202, 265), False, 'from tensorflow import keras\n'), ((532, 561), 'numpy.mean', 'np.mean', (['weig... |
"""Generate new images using a trained SinGAN."""
import torch
from src.singan import SinGAN
import argparse
from datetime import datetime
from skimage import io
import numpy as np
from skimage.color import lab2rgb
# Arguments
parser = argparse.ArgumentParser()
parser.add_argument('--device', type=str, default='cuda',... | [
"src.singan.SinGAN",
"argparse.ArgumentParser",
"skimage.io.imsave",
"skimage.color.lab2rgb",
"torch.device",
"datetime.datetime.now"
] | [((237, 262), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (260, 262), False, 'import argparse\n'), ((878, 921), 'src.singan.SinGAN', 'SinGAN', (['device', '(0.1)', '(0.1)', '(10)', '(1)', '(1)', '(1)', 'None'], {}), '(device, 0.1, 0.1, 10, 1, 1, 1, None)\n', (884, 921), False, 'from src.sing... |
from djangocms_frontend import models
from djangocms_frontend.helpers import get_related_object
from .base import SubcommandsCommand
class StaleReferences(SubcommandsCommand):
help = "Prints all stale references in the djangocms frontend plugins"
command_name = "stale_references"
def handle(self, *args,... | [
"djangocms_frontend.models.FrontendUIItem.objects.all",
"djangocms_frontend.helpers.get_related_object"
] | [((356, 391), 'djangocms_frontend.models.FrontendUIItem.objects.all', 'models.FrontendUIItem.objects.all', ([], {}), '()\n', (389, 391), False, 'from djangocms_frontend import models\n'), ((580, 619), 'djangocms_frontend.helpers.get_related_object', 'get_related_object', (['ui_item.config', 'key'], {}), '(ui_item.confi... |
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from timeit import timeit
from fft import direct_ft, recursive_ft, bitrev_ft
a = -np.pi
b = np.pi
N = 512
x = np.linspace(a, b, N)
def func(x, **kwds):
# note peaks for each mode
# return np.sum([np.sin(i*x) for i in (1., 2., 5., 10.... | [
"timeit.timeit",
"numpy.exp",
"fft.bitrev_ft",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"numpy.sqrt"
] | [((187, 207), 'numpy.linspace', 'np.linspace', (['a', 'b', 'N'], {}), '(a, b, N)\n', (198, 207), True, 'import numpy as np\n'), ((789, 801), 'fft.bitrev_ft', 'bitrev_ft', (['f'], {}), '(f)\n', (798, 801), False, 'from fft import direct_ft, recursive_ft, bitrev_ft\n'), ((823, 838), 'matplotlib.pyplot.subplots', 'plt.sub... |
import numpy as np
'''
# sort
# Syantax: numpy.sort(a, axis, kind, order)
a = np.array([[3,7],[9,1]])
print("sort default: ", np.sort(a))
print("sort axis = 0: ", np.sort(a, axis = 0))
# VIP sorting based on custom data type
dt = np.dtype([('name', 'S10'),('age', int)])
a = np.array([("raju",21),("anil... | [
"numpy.where",
"numpy.array",
"numpy.arange",
"numpy.mod"
] | [((948, 997), 'numpy.array', 'np.array', (['[[30, 40, 0], [0, 20, 10], [50, 0, 60]]'], {}), '([[30, 40, 0], [0, 20, 10], [50, 0, 60]])\n', (956, 997), True, 'import numpy as np\n'), ((997, 1013), 'numpy.where', 'np.where', (['(a > 30)'], {}), '(a > 30)\n', (1005, 1013), True, 'import numpy as np\n'), ((1173, 1187), 'nu... |
from typing import Any, Dict
from cyan.event import Event, EventInfo, Intent
class ReadyEventData:
_props: Dict[str, Any]
def __init__(self, props: Dict[str, Any]) -> None:
self._props = props
@property
def session(self) -> str:
return self._props["session_id"]
class ReadyEvent(Ev... | [
"cyan.event.EventInfo"
] | [((398, 432), 'cyan.event.EventInfo', 'EventInfo', (['"""READY"""', 'Intent.DEFAULT'], {}), "('READY', Intent.DEFAULT)\n", (407, 432), False, 'from cyan.event import Event, EventInfo, Intent\n')] |
import numpy as np
import torch as th
def train_ppo(model, optimizer,
obs, acs, advs, vtargs, old_ac_logps,
n_epochs=3, n_mbatch=1, loss='clip',
vfcoef=0.5, entcoef=0.01, kl_threshold=np.inf, **update_kwargs):
batch_size = obs.shape[0]
mbatch_size = int(batch_siz... | [
"numpy.random.permutation",
"torch.exp",
"torch.clamp",
"torch.max"
] | [((1868, 1899), 'torch.exp', 'th.exp', (['(ac_logps - old_ac_logps)'], {}), '(ac_logps - old_ac_logps)\n', (1874, 1899), True, 'import torch as th\n'), ((1927, 1977), 'torch.clamp', 'th.clamp', (['ac_logp_frac', '(1 - clip_eps)', '(1 + clip_eps)'], {}), '(ac_logp_frac, 1 - clip_eps, 1 + clip_eps)\n', (1935, 1977), True... |
# -*- coding: utf-8 -*-
import requests
import time
from fake_useragent import UserAgent
from hederres_const import const_headerrs, cconst_nacchalo_zagotov
from bs4 import BeautifulSoup
#from moduls__db import get_bd__books, get_bd__Authors
from sqlalchemy import Column, Integer, String, ForeignKey, create_engin... | [
"bs4.BeautifulSoup",
"requests.post",
"random.randint",
"requests.get"
] | [((956, 990), 'bs4.BeautifulSoup', 'BeautifulSoup', (['html', '"""html.parser"""'], {}), "(html, 'html.parser')\n", (969, 990), False, 'from bs4 import BeautifulSoup\n'), ((1313, 1347), 'bs4.BeautifulSoup', 'BeautifulSoup', (['html', '"""html.parser"""'], {}), "(html, 'html.parser')\n", (1326, 1347), False, 'from bs4 i... |
import torch
from collections import namedtuple
import monet.lm_ops as lm_ops
import numpy as np
from monet.graph import *
from checkmate.checkmate_solver import *
from monet.solver_info import *
from monet.pipelined_solver_info import *
from models.unet import UNet
ScheduleType = namedtuple('ScheduleType', 'recomput... | [
"torch.cuda.synchronize",
"torch.nn.AdaptiveAvgPool2d",
"torch.ones",
"torch.cuda.Event",
"argparse.ArgumentParser",
"torch.cuda.max_memory_allocated",
"torch.nn.Flatten",
"torch.randn",
"time.time",
"monet.lm_ops.list_ops",
"pickle.load",
"models.unet.UNet",
"collections.namedtuple",
"tor... | [((284, 372), 'collections.namedtuple', 'namedtuple', (['"""ScheduleType"""', '"""recompute store_output delete_nodes store_intermediate"""'], {}), "('ScheduleType',\n 'recompute store_output delete_nodes store_intermediate')\n", (294, 372), False, 'from collections import namedtuple\n'), ((14185, 14210), 'argparse.... |
# Estos son los mรณdulos que necesitas
import datetime
import calendar
import locale
def get_today_as_string():
"""
Funcion que me dice el dรญa de la semana que es hoy, en formato string.
Pequeรฑa guia de implementaciรณn:
1. Obtรฉn el dรญa de la semana que es hoy, en formato entero (1, 2, 3, etc... | [
"locale.setlocale"
] | [((555, 601), 'locale.setlocale', 'locale.setlocale', (['locale.LC_ALL', '"""es_ES.UTF-8"""'], {}), "(locale.LC_ALL, 'es_ES.UTF-8')\n", (571, 601), False, 'import locale\n')] |
# Before executing the script, we need urllib3. Run `pip install urllib3`
# A simple script for automatically download the ihme-covid19.zip file and extract it
import requests
import os
import sys
import calendar
import datetime
def download_file_by_date(path, date):
# metadata
prefix = "https://raw.githubuserc... | [
"datetime.datetime.today",
"os.makedirs",
"os.path.exists",
"datetime.timedelta",
"requests.get",
"os.path.join"
] | [((818, 873), 'os.path.join', 'os.path.join', (['path', "('Projection_' + date + '/cdc_hosp/')"], {}), "(path, 'Projection_' + date + '/cdc_hosp/')\n", (830, 873), False, 'import os\n'), ((714, 731), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (726, 731), False, 'import requests\n'), ((1653, 1678), 'datet... |
#!/usr/bin/env python
# coding:utf-8
from selenium import webdriver
import config
driver = webdriver.Chrome(executable_path=r'C:\Program Files Tools\Python27\Scripts\chromedriver.exe')
def tskepx_login():
if config.DEBUG:
print('Main :: tskepx_login')
driver.get(config.WEBSITE)
input_name = dri... | [
"selenium.webdriver.Chrome"
] | [((94, 195), 'selenium.webdriver.Chrome', 'webdriver.Chrome', ([], {'executable_path': '"""C:\\\\Program Files Tools\\\\Python27\\\\Scripts\\\\chromedriver.exe"""'}), "(executable_path=\n 'C:\\\\Program Files Tools\\\\Python27\\\\Scripts\\\\chromedriver.exe')\n", (110, 195), False, 'from selenium import webdriver\n'... |
import asyncio
from asyevent.callback import Callback
from asyevent.event import Event
from asyevent.command import Command
from asyevent.exceptions import (
CommandNotFound,
EventNotFound,
CommandAlreadyRegistered,
EventAlreadyRegistered,
)
from typing import Callable, Optional, Union, List, Tuple
... | [
"asyevent.exceptions.CommandNotFound",
"asyncio.get_event_loop",
"asyevent.event.Event",
"asyevent.exceptions.EventAlreadyRegistered",
"asyevent.exceptions.CommandAlreadyRegistered",
"asyevent.exceptions.EventNotFound",
"asyevent.command.Command"
] | [((634, 658), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (656, 658), False, 'import asyncio\n'), ((3486, 3641), 'asyevent.command.Command', 'Command', (['callback'], {'event_manager': 'self', 'name': 'name', 'handle_errors': 'handle_errors', 'multiple_callbacks': 'multiple_callbacks', 'priori... |
import os
import time
from collections import Counter
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
from tensorflow import keras
from tensorflow.python.keras.callbacks import ModelCheckpoint, EarlyStopping, TensorBoard
from sklearn.metrics import f1_score, precision_score, recall_score, accur... | [
"numpy.load",
"numpy.save",
"utils_data_text.get_features_from_data",
"tensorflow_hub.Module",
"tensorflow.global_variables_initializer",
"sklearn.metrics.accuracy_score",
"numpy.zeros",
"sklearn.metrics.recall_score",
"tensorflow.placeholder",
"tensorflow.matmul",
"sklearn.metrics.f1_score",
... | [((2516, 2571), 'utils_data_text.get_features_from_data', 'get_features_from_data', (['train_data', 'val_data', 'test_data'], {}), '(train_data, val_data, test_data)\n', (2538, 2571), False, 'from utils_data_text import get_features_from_data, read_class_results\n'), ((2742, 2803), 'tensorflow.placeholder', 'tf.placeho... |
from __future__ import annotations
from asyncio import ensure_future
from asyncio.tasks import ensure_future
from logging import getLogger
from typing import Any, Awaitable, Callable, Dict, List, NamedTuple, cast
from anyio import create_task_group
from ._fixed_jsonpatch import apply_patch, make_patch # type: ignor... | [
"anyio.create_task_group",
"logging.getLogger"
] | [((419, 438), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (428, 438), False, 'from logging import getLogger\n'), ((1261, 1280), 'anyio.create_task_group', 'create_task_group', ([], {}), '()\n', (1278, 1280), False, 'from anyio import create_task_group\n')] |
# Generated by Django 2.2.4 on 2019-09-23 15:04
from django.db import migrations
def update_user_card_from_member(apps, schema_editor):
"""
Set user card number from member card number
"""
Member = apps.get_model('internal', 'Member')
db_alias = schema_editor.connection.alias
for member in M... | [
"django.db.migrations.RunPython",
"django.db.migrations.RemoveField"
] | [((1128, 1220), 'django.db.migrations.RunPython', 'migrations.RunPython', (['update_user_card_from_member', 'reverse_update_user_card_from_member'], {}), '(update_user_card_from_member,\n reverse_update_user_card_from_member)\n', (1148, 1220), False, 'from django.db import migrations\n'), ((1226, 1289), 'django.db.m... |
from terra_sdk.client.lcd import LCDClient
import terra_sdk
import pandas as pd
import numpy as np
import re
import requests
terra = LCDClient(chain_id="columbus-5", url="https://lcd.terra.dev")
def wallet_balance(wallet):
"""
This Function takes in an input of a wallet address
and returns a DataFrame ... | [
"pandas.DataFrame",
"terra_sdk.core.bech32.is_acc_address",
"pandas.to_datetime",
"requests.get",
"pandas.concat",
"terra_sdk.client.lcd.LCDClient"
] | [((135, 196), 'terra_sdk.client.lcd.LCDClient', 'LCDClient', ([], {'chain_id': '"""columbus-5"""', 'url': '"""https://lcd.terra.dev"""'}), "(chain_id='columbus-5', url='https://lcd.terra.dev')\n", (144, 196), False, 'from terra_sdk.client.lcd import LCDClient\n'), ((1823, 1865), 'pandas.DataFrame', 'pd.DataFrame', (["v... |
import sys
import os
import time
test = None
def change():
global test
print(test)
test = 12
print(test)
return
def main():
start = time.time()
# print(sys.executable)
# print(sys.argv)
while True:
if test == 12:
os.execv(sys.executable, ['python3'] + sys.arg... | [
"os.execv",
"time.sleep",
"time.time"
] | [((161, 172), 'time.time', 'time.time', ([], {}), '()\n', (170, 172), False, 'import time\n'), ((331, 346), 'time.sleep', 'time.sleep', (['(0.1)'], {}), '(0.1)\n', (341, 346), False, 'import time\n'), ((274, 322), 'os.execv', 'os.execv', (['sys.executable', "(['python3'] + sys.argv)"], {}), "(sys.executable, ['python3'... |
from typing import Dict, Any
from batchout.core.config import with_config_key
from batchout.core.registry import Registry
from batchout.indexes import Index
from batchout.extractors import XPathExtractor
class ScalarIndexConfigInvalid(Exception):
pass
@with_config_key('path', raise_exc=ScalarIndexConfigInvalid... | [
"batchout.core.config.with_config_key",
"batchout.core.registry.Registry.bind"
] | [((262, 321), 'batchout.core.config.with_config_key', 'with_config_key', (['"""path"""'], {'raise_exc': 'ScalarIndexConfigInvalid'}), "('path', raise_exc=ScalarIndexConfigInvalid)\n", (277, 321), False, 'from batchout.core.config import with_config_key\n'), ((323, 387), 'batchout.core.config.with_config_key', 'with_con... |
# -*- coding: utf-8 -*-
import pandas as pd
from sqlalchemy import Column, DateTime
from sqlalchemy.ext.declarative import declarative_base
from zvt.contract import TradableEntity
from zvt.contract.register import register_schema, register_entity
CoinMetaBase = declarative_base()
@register_entity(entity_type='coin'... | [
"pandas.date_range",
"zvt.contract.register.register_entity",
"zvt.contract.register.register_schema",
"sqlalchemy.ext.declarative.declarative_base",
"sqlalchemy.Column"
] | [((264, 282), 'sqlalchemy.ext.declarative.declarative_base', 'declarative_base', ([], {}), '()\n', (280, 282), False, 'from sqlalchemy.ext.declarative import declarative_base\n'), ((286, 321), 'zvt.contract.register.register_entity', 'register_entity', ([], {'entity_type': '"""coin"""'}), "(entity_type='coin')\n", (301... |
from datetime import date
from django.test import TestCase, RequestFactory
from django.contrib.auth.models import User, AnonymousUser
from molo.profiles.context_processors import get_profile_data
from molo.core.tests.base import MoloTestCaseMixin
class ContextProcessorsTest(TestCase, MoloTestCaseMixin):
def se... | [
"django.contrib.auth.models.AnonymousUser",
"django.test.RequestFactory",
"molo.profiles.context_processors.get_profile_data",
"datetime.date",
"django.contrib.auth.models.User.objects.create_user"
] | [((377, 393), 'django.test.RequestFactory', 'RequestFactory', ([], {}), '()\n', (391, 393), False, 'from django.test import TestCase, RequestFactory\n'), ((414, 502), 'django.contrib.auth.models.User.objects.create_user', 'User.objects.create_user', ([], {'username': '"""tester"""', 'email': '"""<EMAIL>"""', 'password'... |
import numpy
#numpy.genfromtxt('arr.txt', dtype=bool)
test_input = """00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010"""
with open('input') as f:
input = f.read().rstrip()
def parse_data(input):
return numpy.array([[int(char) for char in list(line)] for line in input.splitlines()])
... | [
"numpy.shape",
"numpy.count_nonzero",
"numpy.sum",
"numpy.argwhere"
] | [((1028, 1058), 'numpy.shape', 'numpy.shape', (['diagnostic_report'], {}), '(diagnostic_report)\n', (1039, 1058), False, 'import numpy\n'), ((451, 492), 'numpy.count_nonzero', 'numpy.count_nonzero', (['diagnostic_report', '(0)'], {}), '(diagnostic_report, 0)\n', (470, 492), False, 'import numpy\n'), ((609, 650), 'numpy... |
#!/usr/bin/env python3
import sys
import os
import argparse
try:
import matplotlib.pyplot as plt
except ModuleNotFoundError:
plt = None
from tools import groupBy
from output_handling import plotHistostats, canCreateFile
##
TAG_PREFIX = 'Tag='
FIXED_LEGEND = ['Tag', 'Interval_Start', 'Interval_Length', 'co... | [
"argparse.ArgumentParser",
"os.path.basename",
"output_handling.plotHistostats",
"output_handling.canCreateFile",
"tools.groupBy"
] | [((2609, 3117), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Quickly plot "--log-histostats" output from NoSQLBench to an image.\n*******************************************************************\n**** DEPRECATION NOTICE ****\n* For production u... |
import music21 as m21
m21.humdrum.spineParser.flavors['JRP'] = True
import pandas as pd
import numpy as np
import json
import argparse
from fractions import Fraction
from collections import defaultdict
from pathlib import Path
from itertools import zip_longest
from MTCFeatures.MTCFeatureLoader import MTCFeatureLoader... | [
"json.load",
"argparse.ArgumentParser",
"pandas.concat",
"MTCFeatures.MTCFeatureLoader.MTCFeatureLoader",
"json.dumps",
"collections.defaultdict",
"music21.interval.Interval",
"pathlib.Path",
"numpy.array",
"music21.converter.parse",
"fractions.Fraction",
"music21.note.Note"
] | [((739, 815), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Convert MTC .krn to feature sequences"""'}), "(description='Convert MTC .krn to feature sequences')\n", (762, 815), False, 'import argparse\n'), ((2781, 2818), 'pathlib.Path', 'Path', (['args.mtcroot', '"""MTC-FS-INST-2.0"""'],... |
from tensorflow import keras
from tensorflow.keras import layers
# from .preprocess import get_data
import os
import re
import json
import string
import numpy as np
import tensorflow as tf
from tokenizers import BertWordPieceTokenizer
from transformers import BertTokenizer, TFBertModel, BertConfig
max_len = 384
conf... | [
"os.makedirs",
"os.path.exists",
"transformers.BertConfig",
"transformers.BertTokenizer.from_pretrained",
"tokenizers.BertWordPieceTokenizer"
] | [((332, 344), 'transformers.BertConfig', 'BertConfig', ([], {}), '()\n', (342, 344), False, 'from transformers import BertTokenizer, TFBertModel, BertConfig\n'), ((400, 450), 'transformers.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (['"""bert-base-uncased"""'], {}), "('bert-base-uncased')\n", (429... |
import core.model as m
"""
my_model = m.Model('simple problem')
x = my_model.intVar('X', 0, 4)
y = my_model.intVar('Y', 1, 8)
my_model.arithm(x, '+', y, '<', 5).times(x, y, 4)
my_model.solve()
my_model.printStatistics()
print('X -> ' + str(x.getValue()))
print('Y -> ' + str(y.getValue()))
"""
my_model2 = m.Model('si... | [
"core.model.Model"
] | [((309, 336), 'core.model.Model', 'm.Model', (['"""simple problem 2"""'], {}), "('simple problem 2')\n", (316, 336), True, 'import core.model as m\n')] |
from unittest import TestCase
from api.JSONValidator import Validator
from api.models import Manufacturer, Device
from tests.setup_tests import db, seed_db
class ConvertNumTestCase(TestCase):
'''convert_num Test Case'''
def test_valid_no_constraints(self):
'''Returns 7: just passing args num='7' '''
... | [
"tests.setup_tests.db.drop_all",
"tests.setup_tests.db.session.rollback",
"api.JSONValidator.Validator.check_convertable",
"api.JSONValidator.Validator.convert_num",
"tests.setup_tests.seed_db",
"api.JSONValidator.Validator",
"api.JSONValidator.Validator.check_name",
"tests.setup_tests.db.create_all"
... | [((340, 370), 'api.JSONValidator.Validator.convert_num', 'Validator.convert_num', ([], {'num': '"""7"""'}), "(num='7')\n", (361, 370), False, 'from api.JSONValidator import Validator\n'), ((522, 564), 'api.JSONValidator.Validator.convert_num', 'Validator.convert_num', ([], {'minimum': '(5)', 'num': '"""12"""'}), "(mini... |
"""parameter_search.py
Search for optimal parameters for RIDDLE and various ML classifiers.
Requires: Keras, NumPy, scikit-learn, RIDDLE (and their dependencies)
Author: <NAME>, Rzhetsky Lab
Copyright: 2018, all rights reserved
"""
from __future__ import print_function
import argparse
import os
import pickl... | [
"pickle.dump",
"numpy.random.seed",
"argparse.ArgumentParser",
"utils.subset_reencode_features",
"utils.get_param_path",
"utils.get_preprocessed_data",
"os.path.isfile",
"sklearn.svm.SVC",
"utils.vectorize_features",
"utils.recursive_mkdir",
"sklearn.model_selection.RandomizedSearchCV",
"riddl... | [((883, 987), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Perform parameter search for various classification methods."""'}), "(description=\n 'Perform parameter search for various classification methods.')\n", (906, 987), False, 'import argparse\n'), ((4397, 4483), 'riddle.emr.get... |
import pytest
from bitcoinx import TxOutput
import scryptlib
from scryptlib.types import *
contract = './test/res/stateMap.scrypt'
compiler_result = scryptlib.utils.compile_contract(contract)
desc = compiler_result.to_desc()
StateMap = scryptlib.build_contract_class(desc)
MapEntry = scryptlib.contract.build_type_cl... | [
"scryptlib.utils.compile_contract",
"scryptlib.build_contract_class",
"scryptlib.get_preimage_from_input_context",
"scryptlib.contract.build_type_classes",
"bitcoinx.TxOutput",
"scryptlib.create_dummy_input_context"
] | [((152, 194), 'scryptlib.utils.compile_contract', 'scryptlib.utils.compile_contract', (['contract'], {}), '(contract)\n', (184, 194), False, 'import scryptlib\n'), ((240, 276), 'scryptlib.build_contract_class', 'scryptlib.build_contract_class', (['desc'], {}), '(desc)\n', (270, 276), False, 'import scryptlib\n'), ((288... |
import discord.ext.commands as commands
def admin_perms():
return commands.has_permissions(administrator=True)
def mod_perms():
return commands.has_permissions(manage_messages=True)
def kick_perms():
return commands.has_permissions(kick_members=True)
def ban_perms():
return commands.has_permissions(... | [
"discord.ext.commands.has_permissions"
] | [((71, 115), 'discord.ext.commands.has_permissions', 'commands.has_permissions', ([], {'administrator': '(True)'}), '(administrator=True)\n', (95, 115), True, 'import discord.ext.commands as commands\n'), ((145, 191), 'discord.ext.commands.has_permissions', 'commands.has_permissions', ([], {'manage_messages': '(True)'}... |
from flask_restplus import Model, fields
Consent = Model('Consent', {
'timestamp': fields.Integer(required=True, description='When the consent was agreed upon'),
'from_us': fields.Boolean(required=True, description='Self identification as a "US Person"'),
'version': fields.Integer(required=True, descriptio... | [
"flask_restplus.fields.Boolean",
"flask_restplus.fields.String",
"flask_restplus.fields.Integer"
] | [((88, 165), 'flask_restplus.fields.Integer', 'fields.Integer', ([], {'required': '(True)', 'description': '"""When the consent was agreed upon"""'}), "(required=True, description='When the consent was agreed upon')\n", (102, 165), False, 'from flask_restplus import Model, fields\n'), ((182, 268), 'flask_restplus.field... |
import numpy as np
from dialRL.utils import distance, float_equality
origin = np.array([1. , 1.])
target = np.array([10., 10.])
print('origin position: ', origin)
print('Traget position: ', target)
a = distance(origin, target)
b = np.random.uniform(0, 9)
# , b = np.random.uniform(0, 9)
# a, b = np.max([a, b]), np.... | [
"numpy.random.uniform",
"dialRL.utils.distance",
"numpy.array"
] | [((79, 99), 'numpy.array', 'np.array', (['[1.0, 1.0]'], {}), '([1.0, 1.0])\n', (87, 99), True, 'import numpy as np\n'), ((108, 130), 'numpy.array', 'np.array', (['[10.0, 10.0]'], {}), '([10.0, 10.0])\n', (116, 130), True, 'import numpy as np\n'), ((205, 229), 'dialRL.utils.distance', 'distance', (['origin', 'target'], ... |
from django.http import HttpResponseForbidden
def allow_only_staff_or_author_during_submission(method):
def _func(self, request, *args, **kwargs):
user = request.user
self.kwargs = kwargs
obj = self.get_object()
if user.is_superuser or user.is_staff or obj.speaker is not None and u... | [
"django.http.HttpResponseForbidden"
] | [((413, 436), 'django.http.HttpResponseForbidden', 'HttpResponseForbidden', ([], {}), '()\n', (434, 436), False, 'from django.http import HttpResponseForbidden\n')] |
# NEXT STEPS
# LOL MAKE EVERYTHING NOT RERUN IF THE FIRST CHECK FAILS
# Incorporate text blob better
# FUTURE
# Chart of words?
# Compare two rappers to each other? Or overall, compare rappers?
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Outp... | [
"dash_html_components.H6",
"dash.Dash",
"dash_html_components.Br",
"dash_html_components.Div",
"dash_html_components.Button",
"dash.dependencies.State",
"dash_core_components.Input",
"dash.dependencies.Input",
"Rap.Rap",
"dash.dependencies.Output"
] | [((948, 1010), 'dash.Dash', 'dash.Dash', (['__name__'], {'external_stylesheets': 'external_stylesheets'}), '(__name__, external_stylesheets=external_stylesheets)\n', (957, 1010), False, 'import dash\n'), ((492, 497), 'Rap.Rap', 'Rap', ([], {}), '()\n', (495, 497), False, 'from Rap import Rap\n'), ((1965, 2028), 'dash.d... |
# -----------------------------------------------------------------------------
# From Pytnon to Numpy
# Copyright (2017) <NAME> - BSD license
# More information at https://github.com/rougier/numpy-book
# -----------------------------------------------------------------------------
import numpy as np
import matplotlib.... | [
"numpy.arctan2",
"numpy.empty",
"numpy.einsum",
"numpy.ones",
"matplotlib.animation.FuncAnimation",
"matplotlib.pyplot.figure",
"numpy.sin",
"numpy.multiply",
"numpy.dstack",
"numpy.divide",
"matplotlib.pyplot.show",
"numpy.hypot",
"numpy.cos",
"numpy.dot",
"numpy.random.uniform",
"mat... | [((6821, 6885), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 10 * height / width)', 'facecolor': '"""white"""'}), "(figsize=(10, 10 * height / width), facecolor='white')\n", (6831, 6885), True, 'import matplotlib.pyplot as plt\n'), ((7318, 7370), 'matplotlib.animation.FuncAnimation', 'FuncAnimation'... |
# Copyright the Karmabot authors and contributors.
# All rights reserved. See AUTHORS.
#
# This file is part of 'karmabot' and is distributed under the BSD license.
# See LICENSE for more details.
from karmabot.core.commands import CommandSet, action
from .base import Facet
from ..ircutils import bold
class NameFac... | [
"karmabot.core.commands.CommandSet"
] | [((381, 397), 'karmabot.core.commands.CommandSet', 'CommandSet', (['name'], {}), '(name)\n', (391, 397), False, 'from karmabot.core.commands import CommandSet, action\n')] |
#! /usr/bin/env python3
"""
Bishbot - https://github.com/ldgregory/bishbot
<NAME> <<EMAIL>>
rules.py v0.1
Tested to Python v3.7.3
Description:
Test cog for testing things out. Would suggest setting commands to hidden=True
until you move the command to a production cog.
Changelog:
2020601 - Initial code
Copyright 2... | [
"discord.ext.commands.command",
"discord.Embed",
"discord.ext.commands.Cog.listener",
"datetime.datetime.now",
"os.getenv"
] | [((981, 1012), 'os.getenv', 'os.getenv', (['"""DISCORD_BOT_PREFIX"""'], {}), "('DISCORD_BOT_PREFIX')\n", (990, 1012), False, 'import os\n'), ((1114, 1137), 'discord.ext.commands.Cog.listener', 'commands.Cog.listener', ([], {}), '()\n', (1135, 1137), False, 'from discord.ext import commands\n'), ((1209, 1356), 'discord.... |
import json
import pickle
import re
import sqlite3
import sys
from collections import OrderedDict
from datetime import date, datetime, time
from datetime import timedelta as t
from time import sleep
from typing import cast
from unittest.mock import MagicMock
from unittest.mock import patch as mock_patch
import yaml
fr... | [
"pickle.dump",
"typing.cast",
"yaml.dump",
"pickle.load",
"datetime.time",
"google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file",
"googleapiclient.discovery.build",
"datetime.datetime.fromisoformat",
"unittest.mock.MagicMock",
"dateutil.tz.tzlocal",
"datetime.timedelta",
"re.se... | [((1158, 1167), 'dateutil.tz.tzlocal', 'tzlocal', ([], {}), '()\n', (1165, 1167), False, 'from dateutil.tz import tzlocal\n'), ((589, 631), 'datetime.datetime.combine', 'datetime.combine', (['thedate', 'thetime', 'tzinfo'], {}), '(thedate, thetime, tzinfo)\n', (605, 631), False, 'from datetime import date, datetime, ti... |
"""
Stats client GUI
Copyright 2021 'My Name'. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unle... | [
"threading.Thread",
"stats_client.project.stats_client_project.StatsClientProject",
"stats_client.widget.stats_dataset_widget.StatsDatasetWidget",
"hyfed_client.widget.join_widget.JoinWidget",
"stats_client.widget.stats_project_info_widget.StatsProjectInfoWidget",
"hyfed_client.widget.hyfed_project_status... | [((1169, 1196), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1186, 1196), False, 'import logging\n'), ((1336, 1742), 'hyfed_client.widget.join_widget.JoinWidget', 'JoinWidget', ([], {'title': '"""Stats Client"""', 'local_server_name': '"""Localhost"""', 'local_server_url': '"""http://l... |
#!/usr/local/bin/python3.6
#-*- coding: utf-8 -*-
#Author WangJiang@2019 15810438848 <EMAIL>
#All rights reserved
################################################################################################################
import argparse
############################################################################... | [
"argparse.ArgumentParser"
] | [((486, 511), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (509, 511), False, 'import argparse\n')] |
from __future__ import absolute_import, division, print_function
from mmtbx.validation.ramalyze import draw_ramachandran_plot
import math
from scipy import interpolate
import numpy as np
def calculate_indexes(x, y, xmin, x_step, ymin, y_step):
i = math.floor((x-xmin) / x_step)
j = math.floor((y-ymin) / y_step)
... | [
"math.floor",
"mmtbx.validation.ramalyze.draw_ramachandran_plot",
"scipy.interpolate.interp2d",
"numpy.array",
"numpy.swapaxes"
] | [((253, 284), 'math.floor', 'math.floor', (['((x - xmin) / x_step)'], {}), '((x - xmin) / x_step)\n', (263, 284), False, 'import math\n'), ((289, 320), 'math.floor', 'math.floor', (['((y - ymin) / y_step)'], {}), '((y - ymin) / y_step)\n', (299, 320), False, 'import math\n'), ((3135, 3179), 'scipy.interpolate.interp2d'... |
import utils
import os
import sys
import numpy as np
from skimage import io
class CityDataset(utils.Dataset):
def load_instances(self, config, subset):
"""Load a subset of the cityscapes dataset.
dataset_dir: Root directory of the dataset
subset: Subset to load. Either the name of the su... | [
"os.path.join",
"os.listdir",
"skimage.io.imread"
] | [((698, 732), 'os.path.join', 'os.path.join', (['config.CITYDATA_PATH'], {}), '(config.CITYDATA_PATH)\n', (710, 732), False, 'import os\n'), ((759, 807), 'os.path.join', 'os.path.join', (['dataset_dir', '"""leftImg8bit"""', 'subset'], {}), "(dataset_dir, 'leftImg8bit', subset)\n", (771, 807), False, 'import os\n'), ((1... |
from uuid import UUID
import psycopg
from infrastructure.event.sqlite.sqlite_event_store import MultipleJsonEncoders, UUIDEncoder, EnumEncoder, \
DateTimeEncoder
class Migration:
def __init__(self, connection_url: str) -> None:
super().__init__()
self.connection_url = connection_url
... | [
"psycopg.connect",
"infrastructure.event.sqlite.sqlite_event_store.MultipleJsonEncoders"
] | [((337, 400), 'infrastructure.event.sqlite.sqlite_event_store.MultipleJsonEncoders', 'MultipleJsonEncoders', (['UUIDEncoder', 'EnumEncoder', 'DateTimeEncoder'], {}), '(UUIDEncoder, EnumEncoder, DateTimeEncoder)\n', (357, 400), False, 'from infrastructure.event.sqlite.sqlite_event_store import MultipleJsonEncoders, UUID... |
import base64
import os
import traceback
from saq.analysis import Analysis
from saq.constants import *
from saq.modules import AnalysisModule
from saq.modules.file_analysis import FileTypeAnalysis
from saq.render import *
KEY_CONTENT = 'content'
KEY_CONTENT_TYPE = 'content_type'
KEY_JOB_ID = 'job_id'
KEY_RESULT_DESCR... | [
"os.path.join",
"traceback.format_exc",
"base64.b64decode"
] | [((3997, 4050), 'os.path.join', 'os.path.join', (['self.root.storage_dir', 'observable.value'], {}), '(self.root.storage_dir, observable.value)\n', (4009, 4050), False, 'import os\n'), ((7217, 7263), 'os.path.join', 'os.path.join', (['self.root.storage_dir', 'file_name'], {}), '(self.root.storage_dir, file_name)\n', (7... |
def plot_chromatogram(x, y, title='XIC for Sample', **kwargs):
"""
Plots a Chromatogram.
Parameters
----------
x : array-like
X values.
y : array-like
Y values.
title : str, optional
Title of plot.
**kwargs
Keyword arguments for ``plt.plot``.
"""
... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] | [((357, 381), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {}), '(x, y, **kwargs)\n', (365, 381), True, 'import matplotlib.pyplot as plt\n'), ((386, 410), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time (min)"""'], {}), "('Time (min)')\n", (396, 410), True, 'import matplotlib.pyplot as plt\n'), ((415, 438), ... |
class Solution:
def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
from bisect import bisect_left
# sort the envelopes
envelopes.sort(key=lambda x: (x[0], -1*x[1]))
def lis(nums):
dp = []
for i in range(len(nums)):
ix ... | [
"bisect.bisect_left"
] | [((322, 346), 'bisect.bisect_left', 'bisect_left', (['dp', 'nums[i]'], {}), '(dp, nums[i])\n', (333, 346), False, 'from bisect import bisect_left\n')] |
import pytest
from torchtext.data import Field
from svae.dataset_utils import SOS_TOKEN, EOS_TOKEN, UNK_TOKEN, PAD_TOKEN
from svae.dataset_utils.datasets import YelpReview
def test_yelp_review():
TEXT = Field(sequential=True, use_vocab=True, lower=True, init_token=SOS_TOKEN, eos_token=EOS_TOKEN,
... | [
"svae.dataset_utils.datasets.YelpReview",
"torchtext.data.Field"
] | [((211, 395), 'torchtext.data.Field', 'Field', ([], {'sequential': '(True)', 'use_vocab': '(True)', 'lower': '(True)', 'init_token': 'SOS_TOKEN', 'eos_token': 'EOS_TOKEN', 'pad_token': 'PAD_TOKEN', 'unk_token': 'UNK_TOKEN', 'tokenize': '"""spacy"""', 'include_lengths': '(True)'}), "(sequential=True, use_vocab=True, low... |
import asyncio
import discord
import random
client = discord.Client()
token = "https://google.com"
@client.event
async def on_ready():
print("logged in as :")
print(client.user.name)
print(client.user.id)
print("------")
await client.change_presence(game=discord.Game(name=... | [
"discord.Game",
"random.choice",
"discord.Client"
] | [((62, 78), 'discord.Client', 'discord.Client', ([], {}), '()\n', (76, 78), False, 'import discord\n'), ((302, 330), 'discord.Game', 'discord.Game', ([], {'name': '"""์ฌ๊ฐํ ๊ณ ๋์ค"""'}), "(name='์ฌ๊ฐํ ๊ณ ๋์ค')\n", (314, 330), False, 'import discord\n'), ((627, 666), 'random.choice', 'random.choice', (["['์๋๋ฐ?', '๋น์ฐํ์ง', '์ ๋ชฐ๋ผ']"]... |
import os
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
from norc.settings import MEDIA_ROOT
urlpatterns = patterns('',
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_... | [
"django.contrib.admin.autodiscover"
] | [((137, 157), 'django.contrib.admin.autodiscover', 'admin.autodiscover', ([], {}), '()\n', (155, 157), False, 'from django.contrib import admin\n')] |
"""(C) <NAME>
Draw a tree with given branching factor and depth and save the image as png file."""
from __future__ import print_function, division
import pygame.gfxdraw as gfx
import pygame
class Node:
def __init__(self, coord):
self.x = coord[0]
self.y = coord[1]
def coord(self):
ret... | [
"pygame.Surface",
"pygame.event.get",
"pygame.display.set_mode",
"pygame.draw.aaline",
"pygame.display.flip",
"pygame.gfxdraw.filled_circle",
"pygame.gfxdraw.aacircle",
"pygame.image.save"
] | [((3016, 3047), 'pygame.display.set_mode', 'pygame.display.set_mode', (['(W, H)'], {}), '((W, H))\n', (3039, 3047), False, 'import pygame\n'), ((3093, 3128), 'pygame.image.save', 'pygame.image.save', (['screen', '"""b4.png"""'], {}), "(screen, 'b4.png')\n", (3110, 3128), False, 'import pygame\n'), ((419, 453), 'pygame.... |
import time
import win32com.client
time.sleep(3) # allow user quickly switch to another window's text field
shell = win32com.client.Dispatch("WScript.Shell")
while True:
shell.SendKeys("<NAME>")
time.sleep(1)
shell.SendKeys("{Enter}")
time.sleep(5)
| [
"time.sleep"
] | [((39, 52), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (49, 52), False, 'import time\n'), ((209, 222), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (219, 222), False, 'import time\n'), ((253, 266), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (263, 266), False, 'import time\n')] |
import random
import time
wcounter = 0
lcounter = 0
while True:
rand1 = random.randint(0,23)
rand2 = random.randint(33,57)
randzahl = random.randint(rand1, rand2)
print("Wins: " + str(wcounter))
print("Loses: " + str(lcounter))
userin = input('Bitte gib eine Zahl zwischen ' + str(rand1) + '... | [
"random.randint",
"time.sleep"
] | [((79, 100), 'random.randint', 'random.randint', (['(0)', '(23)'], {}), '(0, 23)\n', (93, 100), False, 'import random\n'), ((112, 134), 'random.randint', 'random.randint', (['(33)', '(57)'], {}), '(33, 57)\n', (126, 134), False, 'import random\n'), ((150, 178), 'random.randint', 'random.randint', (['rand1', 'rand2'], {... |
import numpy as np
from tictactoe import search
from tictactoe.search import Minimax, SearchAlgorithm
from tictactoe.board import Board, Winner
def app(algorithm: SearchAlgorithm, player: bool):
b = Board(np.full((3,3), None))
if not player:
print(str(b))
while b.winner == Winner.UNDETERMINED:
... | [
"numpy.full",
"tictactoe.search.Minimax"
] | [((211, 232), 'numpy.full', 'np.full', (['(3, 3)', 'None'], {}), '((3, 3), None)\n', (218, 232), True, 'import numpy as np\n'), ((864, 881), 'tictactoe.search.Minimax', 'Minimax', (['(False)', '(5)'], {}), '(False, 5)\n', (871, 881), False, 'from tictactoe.search import Minimax, SearchAlgorithm\n')] |
from copy import deepcopy
import numpy as np
from bridge_sim.bridges.bridge_705 import bridge_705
from bridge_sim.configs import opensees_default
from bridge_sim.vehicles import truck1
from bridge_sim.model import PointLoad
from bridge_sim.util import flatten
c = opensees_default(bridge_705(0.5))
entering_time = truc... | [
"bridge_sim.vehicles.truck1.to_wheel_track_xs",
"copy.deepcopy",
"bridge_sim.util.flatten",
"bridge_sim.vehicles.truck1.time_left_bridge",
"bridge_sim.bridges.bridge_705.bridge_705",
"bridge_sim.vehicles.truck1.to_point_load_pw",
"bridge_sim.vehicles.truck1.total_kn",
"bridge_sim.vehicles.truck1.time_... | [((316, 360), 'bridge_sim.vehicles.truck1.time_entering_bridge', 'truck1.time_entering_bridge', ([], {'bridge': 'c.bridge'}), '(bridge=c.bridge)\n', (343, 360), False, 'from bridge_sim.vehicles import truck1\n'), ((376, 419), 'bridge_sim.vehicles.truck1.time_entered_bridge', 'truck1.time_entered_bridge', ([], {'bridge'... |
"""low-level ebuild utility"""
import sys
from snakeoil.cli.exceptions import ExitException
from snakeoil.strings import pluralism
from ..operations import OperationError, observer
from ..package.errors import MetadataException
from ..util.commandline import ArgumentParser, StoreTarget
argparser = ArgumentParser(de... | [
"snakeoil.strings.pluralism",
"sys.stderr.flush",
"snakeoil.cli.exceptions.ExitException"
] | [((2019, 2037), 'sys.stderr.flush', 'sys.stderr.flush', ([], {}), '()\n', (2035, 2037), False, 'import sys\n'), ((3261, 3324), 'snakeoil.cli.exceptions.ExitException', 'ExitException', (['f"""caught exception executing phase {phase}: {e}"""'], {}), "(f'caught exception executing phase {phase}: {e}')\n", (3274, 3324), F... |
# <NAME> <<EMAIL>>
import ROOT
import re
##__________________________________________________________________||
class BranchAddressManagerForVector(object):
"""The branch address manager for ROOT TTree
This class manages ROOT.vector objects used for branch addresses
of ROOT TTree. The main purpose of this... | [
"re.search",
"ROOT.vector"
] | [((1168, 1203), 're.search', 're.search', (['"""^(.*)<(.*)>$"""', 'typename'], {}), "('^(.*)<(.*)>$', typename)\n", (1177, 1203), False, 'import re\n'), ((1424, 1452), 'ROOT.vector', 'ROOT.vector', (['elementtypename'], {}), '(elementtypename)\n', (1435, 1452), False, 'import ROOT\n')] |
import json
from datetime import datetime
import boto3
import os
def lambda_handler(event, context):
# print(event)
s3_client = boto3.client('s3')
s3_bucket_name=os.environ['bucketName']
s3_prefx=os.environ['prefix']
print("Received event, numberOfRecords: " + str(len(event['Records'])))
... | [
"boto3.client"
] | [((142, 160), 'boto3.client', 'boto3.client', (['"""s3"""'], {}), "('s3')\n", (154, 160), False, 'import boto3\n')] |
#!/usr/bin/env python3
from PIL import Image
image = Image.open("image.jpg")
image.rotate(180).resize((640, 480)).save("rotated_and_resized_image.jpg")
| [
"PIL.Image.open"
] | [((55, 78), 'PIL.Image.open', 'Image.open', (['"""image.jpg"""'], {}), "('image.jpg')\n", (65, 78), False, 'from PIL import Image\n')] |
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
("auth", "0006_require_contenttypes_0002"),
("oneevent", "0001_initial"),
]
operations = [
migrations.AddField(
model_name="event",
name="employees_exception_g... | [
"django.db.models.ManyToManyField"
] | [((346, 518), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'related_name': '"""employees_exceptions_for_event+"""', 'verbose_name': '"""Groups NOT considered as Employees (exceptions)"""', 'to': '"""auth.Group"""', 'blank': '(True)'}), "(related_name='employees_exceptions_for_event+',\n verbos... |
import rospy
import numpy as np
import pcl
from tools import *
#Import error, but we don't really used this file anymore
#from scipy.linalg import lstsq
from std_msgs.msg import Header, Int64
from geometry_msgs.msg import Point
from pointcloud_operations import filtering
from sensor_msgs.msg import PointCloud2
from sen... | [
"std_msgs.msg.Int64",
"rospy.Subscriber",
"rospy.Time.now",
"gpd.msg.CloudIndexed",
"std_msgs.msg.Header",
"rospy.Publisher",
"rospy.sleep",
"numpy.ones",
"numpy.where",
"pointcloud_operations.filtering",
"geometry_msgs.msg.Point",
"sensor_msgs.point_cloud2.read_points",
"pcl.PointCloud"
] | [((449, 465), 'pcl.PointCloud', 'pcl.PointCloud', ([], {}), '()\n', (463, 465), False, 'import pcl\n'), ((621, 711), 'rospy.Subscriber', 'rospy.Subscriber', (['"""/camera/depth_registered/points"""', 'PointCloud2', 'self.cloud_callback'], {}), "('/camera/depth_registered/points', PointCloud2, self.\n cloud_callback)... |
#########
# Predicting Research Trends with Semantic and Neural Networks with an application in Quantum Physics
# <NAME>, <NAME>
# https://arxiv.org/abs/1906.06843 (in PNAS)
#
# This file is the navigator for creating a semantic network from data,
# and using it for predicting future research trends using artific... | [
"sys.path.append",
"train_nn.train_nn",
"create_full_article_data_APS.create_full_data_APS",
"analyse_network.collaps_network",
"create_full_article_data.create_full_data_arxiv",
"prepare_ancient_semnets.create_ancient_networks",
"calc_properties.calculate_all_network_properties",
"create_network.crea... | [((636, 678), 'sys.path.append', 'sys.path.append', (['"""1aCreateFullArticleData"""'], {}), "('1aCreateFullArticleData')\n", (651, 678), False, 'import sys\n'), ((680, 726), 'sys.path.append', 'sys.path.append', (['"""1bCreateFullArticleData_APS"""'], {}), "('1bCreateFullArticleData_APS')\n", (695, 726), False, 'impor... |
import os, pickle, glob
from pandas.core.reshape.concat import concat
from common.tflogs2pandas import tflog2pandas
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
from common.gym_interface import template
if False:
def read_df(body):
dfs = []
for seed ... | [
"common.tflogs2pandas.tflog2pandas",
"numpy.arange",
"common.gym_interface.template",
"pandas.read_pickle",
"pandas.concat"
] | [((1324, 1371), 'pandas.read_pickle', 'pd.read_pickle', (['"""output_data/tmp/oracle_1xx_df"""'], {}), "('output_data/tmp/oracle_1xx_df')\n", (1338, 1371), True, 'import pandas as pd\n'), ((1115, 1145), 'numpy.arange', 'np.arange', ([], {'start': '(100)', 'stop': '(200)'}), '(start=100, stop=200)\n', (1124, 1145), True... |
from collections import OrderedDict
import pkg_resources
from gitgud.levels.util import BasicChallenge
all_challenges = OrderedDict()
all_challenges['commits'] = BasicChallenge('commits', pkg_resources.resource_filename(__name__, '_commits/'))
del pkg_resources
del BasicChallenge | [
"collections.OrderedDict",
"pkg_resources.resource_filename"
] | [((123, 136), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (134, 136), False, 'from collections import OrderedDict\n'), ((191, 245), 'pkg_resources.resource_filename', 'pkg_resources.resource_filename', (['__name__', '"""_commits/"""'], {}), "(__name__, '_commits/')\n", (222, 245), False, 'import pkg_res... |
#########################################################
#Copyright (c) 2020-present, drliang219
#All rights reserved.
#
#This source code is licensed under the BSD-style license found in the
#LICENSE file in the root directory of this source tree.
##########################################################
import Co... | [
"threading.Thread",
"os.makedirs",
"logging.basicConfig",
"Queue.Queue",
"os.path.dirname",
"subprocess.check_output",
"os.path.exists",
"time.sleep",
"threading.Lock",
"logging.info",
"InstanceEvent.InstanceEvent.Event_type",
"ConfigParser.RawConfigParser",
"libvirt.virEventRunDefaultImpl",... | [((19806, 19836), 'ConfigParser.RawConfigParser', 'ConfigParser.RawConfigParser', ([], {}), '()\n', (19834, 19836), False, 'import ConfigParser\n'), ((20000, 20030), 'os.path.dirname', 'os.path.dirname', (['log_file_name'], {}), '(log_file_name)\n', (20015, 20030), False, 'import os\n'), ((20096, 20213), 'logging.basic... |
from bs4 import BeautifulSoup
import urllib.request as req
import urllib.parse as rep
import os
# # naver headers
# opener = req.build_opener()
# opener.addheaders = [('User-agent','Mozilla/5.0')]
# req.install_opener(opener)
base_url = 'https://search.naver.com/search.naver?where=image&sm=tab_jum&query='
query = '์ ํ... | [
"os.makedirs",
"os.path.isdir",
"urllib.request.urlopen",
"urllib.request.urlretrieve",
"urllib.parse.quote_plus",
"bs4.BeautifulSoup",
"os.path.join"
] | [((331, 352), 'urllib.parse.quote_plus', 'rep.quote_plus', (['query'], {}), '(query)\n', (345, 352), True, 'import urllib.parse as rep\n'), ((388, 427), 'os.path.join', 'os.path.join', (['"""./crawling/image"""', 'query'], {}), "('./crawling/image', query)\n", (400, 427), False, 'import os\n'), ((617, 633), 'urllib.req... |
"""Mailing list API."""
from __future__ import division
import json
import math
from .base import ApiResource, silence_error
class MailingList(ApiResource):
"""
Mailing list resource.
"""
api_endpoint = "lists"
MEMBERS_UPLOAD_LIMIT = 1000
def create(self, address, name=None, description=Non... | [
"json.dumps"
] | [((1915, 1937), 'json.dumps', 'json.dumps', (['parameters'], {}), '(parameters)\n', (1925, 1937), False, 'import json\n'), ((2795, 2817), 'json.dumps', 'json.dumps', (['parameters'], {}), '(parameters)\n', (2805, 2817), False, 'import json\n'), ((3779, 3804), 'json.dumps', 'json.dumps', (['members_batch'], {}), '(membe... |