code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
from urllib.parse import urljoin
from qiniu import Auth,put_file
from swiper import config
def qn_upload(filename,filepath):
'''将文件上传至七牛云'''
#构建鉴权对象
qn = Auth(config.QN_ACCESS_KEY,config.QN_SECRET_KEY)
#生产上传 Token,有效期为1小时
token = qn.upload_token(config.QN_BUCKET,filename,3600)
#上传文件
ret,i... | [
"qiniu.put_file",
"urllib.parse.urljoin",
"qiniu.Auth"
] | [((169, 217), 'qiniu.Auth', 'Auth', (['config.QN_ACCESS_KEY', 'config.QN_SECRET_KEY'], {}), '(config.QN_ACCESS_KEY, config.QN_SECRET_KEY)\n', (173, 217), False, 'from qiniu import Auth, put_file\n'), ((326, 361), 'qiniu.put_file', 'put_file', (['token', 'filename', 'filepath'], {}), '(token, filename, filepath)\n', (33... |
#!/usr/bin/env python
#
# Generated Mon Jun 10 11:49:52 2019 by generateDS.py version 2.32.0.
# Python 3.6.7 (default, Oct 22 2018, 11:32:17) [GCC 8.2.0]
#
# Command line options:
# ('-f', '')
# ('-o', 's3_api.py')
# ('-s', 's3_sub.py')
# ('--super', 's3_api')
#
# Command line arguments:
# schemas/AmazonS3.... | [
"sys.stdout.write",
"io.BytesIO",
"lxml.etree.tostring",
"lxml.etree.parse",
"lxml.etree.ETCompatXMLParser",
"os.path.join",
"sys.exit"
] | [((945, 990), 'lxml.etree.parse', 'etree_.parse', (['infile'], {'parser': 'parser'}), '(infile, parser=parser, **kwargs)\n', (957, 990), True, 'from lxml import etree as etree_\n'), ((30208, 30219), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (30216, 30219), False, 'import sys\n'), ((773, 799), 'lxml.etree.ETCompat... |
from os import path
import numpy as np
from torch import nn
import torch
def get_embedding(embedding_path=None,
embedding_np=None,
num_embeddings=0, embedding_dim=0, freeze=True, **kargs):
"""Create embedding from:
1. saved numpy vocab array, embedding_path, freeze
2. n... | [
"torch.nn.Embedding",
"torch.Tensor",
"os.path.exists",
"numpy.load"
] | [((665, 717), 'torch.nn.Embedding', 'nn.Embedding', (['num_embeddings', 'embedding_dim'], {}), '(num_embeddings, embedding_dim, **kargs)\n', (677, 717), False, 'from torch import nn\n'), ((458, 485), 'os.path.exists', 'path.exists', (['embedding_path'], {}), '(embedding_path)\n', (469, 485), False, 'from os import path... |
# coding=utf-8
"""
Copyright (c) 2021 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, dist... | [
"binaryninja.log_error"
] | [((2267, 2320), 'binaryninja.log_error', 'binaryninja.log_error', (['"""λ - Unsupported LOADSEG file"""'], {}), "('λ - Unsupported LOADSEG file')\n", (2288, 2320), False, 'import binaryninja\n')] |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | [
"gym.envs.registration.register"
] | [((620, 729), 'gym.envs.registration.register', 'register', ([], {'id': '"""MB_FetchSlide-v1"""', 'entry_point': '"""pddm.envs.fetch.slide:FetchSlideEnv"""', 'max_episode_steps': '(50)'}), "(id='MB_FetchSlide-v1', entry_point=\n 'pddm.envs.fetch.slide:FetchSlideEnv', max_episode_steps=50)\n", (628, 729), False, 'fro... |
lastlineKEY = ""
lastlineTOKEN = ""
lastlinePORTALACCOUNT = ""
import json
try:
import requests
HAVE_REQUESTS = True
except ImportError:
HAVE_REQUESTS = False
from viper.common.abstracts import Module
from viper.core.session import __sessions__
BASE_URL = 'https://analysis.lastline.com'
SUBMIT_URL ... | [
"viper.core.session.__sessions__.is_set",
"requests.post",
"json.dumps"
] | [((1062, 1083), 'viper.core.session.__sessions__.is_set', '__sessions__.is_set', ([], {}), '()\n', (1081, 1083), False, 'from viper.core.session import __sessions__\n'), ((2177, 2224), 'requests.post', 'requests.post', (['(BASE_URL + SUBMIT_URL)'], {'data': 'data'}), '(BASE_URL + SUBMIT_URL, data=data)\n', (2190, 2224)... |
from functools import wraps
from flask import session, url_for, request, redirect
def is_authenticated():
return 'username' in session
def login_required(f):
@wraps(f)
def wrapper(*args, **kwargs):
if is_authenticated():
return f(*args, **kwargs)
else:
return redire... | [
"flask.redirect",
"flask.url_for",
"functools.wraps"
] | [((169, 177), 'functools.wraps', 'wraps', (['f'], {}), '(f)\n', (174, 177), False, 'from functools import wraps\n'), ((452, 460), 'functools.wraps', 'wraps', (['f'], {}), '(f)\n', (457, 460), False, 'from functools import wraps\n'), ((566, 596), 'flask.redirect', 'redirect', (["request.args['next']"], {}), "(request.ar... |
# #This will allow us to create file paths accross operating systems
import pathlib
# #Path to collect data from Recources folder
election_csvpath =pathlib.Path('PyPoll/Resources/election_data.csv')
#Module for reading CSV files
import csv
with open(election_csvpath, mode='r') as csvfile:
#CSV reader specifies d... | [
"pathlib.Path",
"csv.reader",
"csv.writer"
] | [((149, 199), 'pathlib.Path', 'pathlib.Path', (['"""PyPoll/Resources/election_data.csv"""'], {}), "('PyPoll/Resources/election_data.csv')\n", (161, 199), False, 'import pathlib\n'), ((1334, 1386), 'pathlib.Path', 'pathlib.Path', (['"""PyPoll/Analysis/election_results.txt"""'], {}), "('PyPoll/Analysis/election_results.t... |
#!/usr/bin/env python3
# goal: of the 6230 objects exported by v5 (vat-mints), how many are Purses vs Payments vs other?
import sys, json, time, hashlib, base64
from collections import defaultdict
exports = {} # kref -> type
double_spent = set()
unspent = set() # kref
died_unspent = {}
def find_interfaces(body):
... | [
"collections.defaultdict",
"json.loads"
] | [((2059, 2075), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (2070, 2075), False, 'from collections import defaultdict\n'), ((2375, 2391), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (2386, 2391), False, 'from collections import defaultdict\n'), ((2619, 2635), 'collections... |
# Copyright 2017 Neural Networks and Deep Learning lab, MIPT
#
# 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... | [
"numpy.random.seed",
"tensorflow.set_random_seed",
"random.seed",
"os.path.join",
"os.listdir"
] | [((2425, 2455), 'numpy.random.seed', 'np.random.seed', ([], {'seed': 'self.seed'}), '(seed=self.seed)\n', (2439, 2455), True, 'import numpy as np\n'), ((2464, 2488), 'random.seed', 'random.seed', ([], {'a': 'self.seed'}), '(a=self.seed)\n', (2475, 2488), False, 'import random\n'), ((2497, 2531), 'tensorflow.set_random_... |
#!/usr/bin/env python
# coding: utf-8
# ## Load and process Park et al. data
#
# For each sample, we want to compute:
#
# * (non-silent) binary mutation status in the gene of interest
# * binary copy gain/loss status in the gene of interest
# * what "class" the gene of interest is in (more detail on what this means ... | [
"sys.path.append",
"config.distance_data_dir.mkdir",
"pandas.DataFrame",
"pickle.dump",
"pandas.read_csv",
"pathlib.Path",
"pickle.load"
] | [((553, 574), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (568, 574), False, 'import sys\n'), ((1059, 1115), 'pathlib.Path', 'Path', (['"""/home/jake/research/mpmp/data/pancancer_data.pkl"""'], {}), "('/home/jake/research/mpmp/data/pancancer_data.pkl')\n", (1063, 1115), False, 'from pathlib im... |
"""
Parse, don't validate. - <NAME>
"""
from munch import Munch
from .functions import TomlFunction
from .shared import OnThrowValue
def parse_on_throw(from_obj, to_obj):
"""
Expects "or_else" to already have been processed on "to_obj"
"""
throw_action = {
"or_else": OnThrowValue.OrElse,
... | [
"munch.Munch"
] | [((825, 832), 'munch.Munch', 'Munch', ([], {}), '()\n', (830, 832), False, 'from munch import Munch\n'), ((1040, 1047), 'munch.Munch', 'Munch', ([], {}), '()\n', (1045, 1047), False, 'from munch import Munch\n'), ((2582, 2589), 'munch.Munch', 'Munch', ([], {}), '()\n', (2587, 2589), False, 'from munch import Munch\n'),... |
# -*- coding: utf-8 -*-
"""
Project: neurohacking
File: clench.py.py
Author: wffirilat
"""
import numpy as np
import time
import sys
import plugin_interface as plugintypes
from open_bci_v3 import OpenBCISample
class PluginClench(plugintypes.IPluginExtended):
def __init__(self):
self.release = True
... | [
"numpy.zeros",
"time.time"
] | [((719, 750), 'numpy.zeros', 'np.zeros', (['(8, self.storelength)'], {}), '((8, self.storelength))\n', (727, 750), True, 'import numpy as np\n'), ((771, 802), 'numpy.zeros', 'np.zeros', (['(8, self.storelength)'], {}), '((8, self.storelength))\n', (779, 802), True, 'import numpy as np\n'), ((1766, 1777), 'time.time', '... |
import discord, time, os, praw, random, json
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions, MissingPermissions
from discord.utils import get
from itertools import cycle
import datetime as dt
from datetime import datetime
done3 = []
beg_lim_users = []
timers = {}
done = []
s... | [
"os.mkdir",
"json.dump",
"json.load",
"discord.ext.commands.command",
"random.randint",
"discord.Embed",
"discord.ext.commands.has_permissions",
"discord.ext.tasks.loop",
"os.chdir"
] | [((652, 706), 'discord.ext.commands.command', 'commands.command', ([], {'aliases': "['resetmoney', 'moneyreset']"}), "(aliases=['resetmoney', 'moneyreset'])\n", (668, 706), False, 'from discord.ext import commands, tasks\n'), ((712, 747), 'discord.ext.commands.has_permissions', 'has_permissions', ([], {'administrator':... |
#!/usr/bin/env python
#fn; get_mismatch.py
#ACTGCAGCGTCATAGTTTTTGAG
import os
import copy
def getMismatch(start,seq,name,end):
#name = seq
quality = 'IIIIIIIIIIIIIIIIIIIIII'
OUTFILE = open('./mis_test.fastq','a')
ls = list(seq)
ls_1 = copy.deepcopy(ls)
ii = start+1
for i in ls_1[ii:end]:... | [
"copy.deepcopy"
] | [((259, 276), 'copy.deepcopy', 'copy.deepcopy', (['ls'], {}), '(ls)\n', (272, 276), False, 'import copy\n')] |
# Generated by Django 2.0.10 on 2020-05-25 19:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('circles', '0003_auto_20200525_1531'),
]
operations = [
migrations.RemoveField(
model_name='membership',
name='is_Ac... | [
"django.db.migrations.RemoveField",
"django.db.models.BooleanField",
"django.db.models.PositiveSmallIntegerField"
] | [((236, 301), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""membership"""', 'name': '"""is_Active"""'}), "(model_name='membership', name='is_Active')\n", (258, 301), False, 'from django.db import migrations, models\n'), ((452, 594), 'django.db.models.BooleanField', 'models.Boolea... |
# -*- coding: utf-8 -*-
r"""Run the vacuum coefficients 3nu example shown in README.md.
Runs the three-neutrino example of coefficients for oscillations in
vacuum shown in README.md
References
----------
.. [1] <NAME>, "Exact neutrino oscillation probabilities:
a fast general-purpose computation method for two an... | [
"sys.path.append",
"oscprob3nu.evolution_operator_3nu",
"numpy.multiply",
"hamiltonians3nu.hamiltonian_3nu_vacuum_energy_independent",
"oscprob3nu.hamiltonian_3nu_coefficients",
"numpy.array",
"numpy.printoptions",
"oscprob3nu.evolution_operator_3nu_u_coefficients"
] | [((549, 574), 'sys.path.append', 'sys.path.append', (['"""../src"""'], {}), "('../src')\n", (564, 574), False, 'import sys\n'), ((769, 896), 'hamiltonians3nu.hamiltonian_3nu_vacuum_energy_independent', 'hamiltonians3nu.hamiltonian_3nu_vacuum_energy_independent', (['S12_NO_BF', 'S23_NO_BF', 'S13_NO_BF', 'DCP_NO_BF', 'D2... |
# coding: utf-8
"""
Hydrogen Atom API
The Hydrogen Atom API # noqa: E501
OpenAPI spec version: 1.7.0
Contact: <EMAIL>
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import nucleus_api
from nucleus_api.api.roundup_ap... | [
"unittest.main",
"nucleus_api.api.roundup_api.RoundupApi"
] | [((2072, 2087), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2085, 2087), False, 'import unittest\n'), ((517, 557), 'nucleus_api.api.roundup_api.RoundupApi', 'nucleus_api.api.roundup_api.RoundupApi', ([], {}), '()\n', (555, 557), False, 'import nucleus_api\n')] |
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect, Http404
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.http import require_POST
from django.contrib.auth.decorators import login_required
from django.core.... | [
"django.core.urlresolvers.reverse",
"django.utils.timezone.now",
"watson.search.filter",
"django.http.JsonResponse",
"django.shortcuts.get_object_or_404",
"django.core.paginator.Paginator",
"django.http.Http404",
"django.shortcuts.render",
"logging.getLogger"
] | [((820, 847), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (837, 847), False, 'import logging\n'), ((921, 956), 'django.core.paginator.Paginator', 'Paginator', (['lst', 'num_objects_on_page'], {}), '(lst, num_objects_on_page)\n', (930, 956), False, 'from django.core.paginator import Pag... |
import time
import logging
import betfairlightweight
from betfairlightweight.filters import streaming_market_filter
from pythonjsonlogger import jsonlogger
from flumine import Flumine, clients, BaseStrategy
from flumine.order.trade import Trade
from flumine.order.ordertype import LimitOrder
from flumine.order.order im... | [
"pythonjsonlogger.jsonlogger.JsonFormatter",
"betfairlightweight.filters.streaming_market_filter",
"betfairlightweight.APIClient",
"flumine.order.ordertype.LimitOrder",
"logging.StreamHandler",
"flumine.Flumine",
"flumine.clients.BetfairClient",
"logging.getLogger",
"flumine.order.trade.Trade"
] | [((347, 366), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (364, 366), False, 'import logging\n'), ((435, 458), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (456, 458), False, 'import logging\n'), ((471, 510), 'pythonjsonlogger.jsonlogger.JsonFormatter', 'jsonlogger.JsonFormatter',... |
from unittest.mock import patch
from urllib.parse import urlencode, quote_plus
from kairon.shared.utils import Utility
import pytest
import os
from mongoengine import connect, ValidationError
from kairon.shared.chat.processor import ChatDataProcessor
from re import escape
import responses
class TestChat:
@pytes... | [
"kairon.shared.chat.processor.ChatDataProcessor.save_channel_config",
"kairon.shared.chat.processor.ChatDataProcessor.list_channel_config",
"urllib.parse.urlencode",
"kairon.shared.utils.Utility.load_environment",
"pytest.fixture",
"responses.add",
"re.escape",
"unittest.mock.patch",
"pytest.raises"... | [((315, 358), 'pytest.fixture', 'pytest.fixture', ([], {'autouse': '(True)', 'scope': '"""class"""'}), "(autouse=True, scope='class')\n", (329, 358), False, 'import pytest\n'), ((459, 485), 'kairon.shared.utils.Utility.load_environment', 'Utility.load_environment', ([], {}), '()\n', (483, 485), False, 'from kairon.shar... |
from flask import (
Blueprint,
flash,
redirect,
render_template,
request,
url_for)
from flask_login import current_user, login_user, logout_user
from werkzeug.wrappers import Response
from .forms import (
AccountForm,
DeleteForm,
LoginForm,
RegisterForm,
ResetForm,
Updat... | [
"flask.flash",
"flask.Blueprint",
"flask.request.args.get",
"flask.redirect",
"utils.admin_auth",
"flask_login.logout_user",
"utils.make_api_request",
"flask.url_for",
"flask.render_template",
"utils.is_staging"
] | [((404, 461), 'flask.Blueprint', 'Blueprint', (['"""users"""', '__name__'], {'template_folder': '"""templates"""'}), "('users', __name__, template_folder='templates')\n", (413, 461), False, 'from flask import Blueprint, flash, redirect, render_template, request, url_for\n'), ((1334, 1377), 'flask.render_template', 'ren... |
from tkinter import *
from tkinter import messagebox
from tkinter.ttk import *
import re
class TagSettings(Toplevel):
def __init__(self, parent):
super().__init__(parent)
# Class variables
self.tags = dict()
self.changes_made = False
# Window Parameters
self.title... | [
"tkinter.messagebox.showerror",
"re.match"
] | [((13733, 13760), 're.match', 're.match', (['"""^[0-9]+$"""', 'value'], {}), "('^[0-9]+$', value)\n", (13741, 13760), False, 'import re\n'), ((13959, 14015), 'tkinter.messagebox.showerror', 'messagebox.showerror', (['"""Error"""', '"""You must enter a value."""'], {}), "('Error', 'You must enter a value.')\n", (13979, ... |
"""
Convert ground truth latent classes into binary sensitive attributes
"""
def attr_fn_0(y):
return y[:,0] >= 1
def attr_fn_1(y):
return y[:,1] >= 1
def attr_fn_2(y):
return y[:,2] >= 3
def attr_fn_3(y):
return y[:,3] >= 20
def attr_fn_4(y):
return y[:,4] >= 16
def attr_fn_5(y):
ret... | [
"numpy.zeros"
] | [((3653, 3671), 'numpy.zeros', 'np.zeros', (['(10, 10)'], {}), '((10, 10))\n', (3661, 3671), True, 'import numpy as np\n')] |
# coding: utf-8
# # Example
# In[3]:
import turicreate as tc
# ## Get the data
# In[22]:
data = 'path-to-data-here'
sf = tc.SFrame(data).dropna(columns=['Age'])
train, test = sf.random_split(fraction=0.8)
test, validations = test.random_split(fraction=0.5)
# ## Modeling
# In[27]:
from turicreate import log... | [
"turicreate.SFrame",
"turicreate.logistic_classifier.create"
] | [((345, 430), 'turicreate.logistic_classifier.create', 'logistic_classifier.create', (['train'], {'target': '"""Survived"""', 'validation_set': 'validations'}), "(train, target='Survived', validation_set=validations\n )\n", (371, 430), False, 'from turicreate import logistic_classifier\n'), ((129, 144), 'turicreate.... |
import argparse
import os
import random
import time
import warnings
from math import cos, pi
import cv2
import numpy as np
import torch
import torch.optim as optim
from DLBio.pt_train_printer import Printer
from DLBio.pytorch_helpers import get_lr
class ITrainInterface():
"""
TrainInterfaces handle the pred... | [
"numpy.random.seed",
"torch.optim.lr_scheduler.StepLR",
"argparse.ArgumentParser",
"DLBio.pytorch_helpers.get_lr",
"torch.no_grad",
"random.seed",
"math.cos",
"torch.manual_seed",
"torch.cuda.manual_seed",
"torch.cuda.is_available",
"DLBio.pt_train_printer.Printer",
"cv2.setRNGSeed",
"time.t... | [((22861, 22936), 'torch.optim.lr_scheduler.StepLR', 'optim.lr_scheduler.StepLR', (['optimizer', 'step_size'], {'gamma': 'gamma', 'last_epoch': '(-1)'}), '(optimizer, step_size, gamma=gamma, last_epoch=-1)\n', (22886, 22936), True, 'import torch.optim as optim\n'), ((23885, 23905), 'numpy.random.seed', 'np.random.seed'... |
import pandas as pd
import numpy as np
import logging
# IF CHOPPINESS INDEX >= 61.8 - -> MARKET IS CONSOLIDATING
# IF CHOPPINESS INDEX <= 38.2 - -> MARKET IS TRENDING
# https://medium.com/codex/detecting-ranging-and-trending-markets-with-choppiness-index-in-python-1942e6450b58
class WyckoffAccumlationDistribution:
... | [
"pandas.DataFrame",
"numpy.log10",
"logging.error",
"pandas.concat"
] | [((1742, 1760), 'numpy.log10', 'np.log10', (['lookback'], {}), '(lookback)\n', (1750, 1760), True, 'import numpy as np\n'), ((1191, 1215), 'pandas.DataFrame', 'pd.DataFrame', (['(high - low)'], {}), '(high - low)\n', (1203, 1215), True, 'import pandas as pd\n'), ((3523, 3591), 'logging.error', 'logging.error', (['f"""W... |
'''
Created on 17 Mar 2018
@author: julianporter
'''
from OSGridConverter.algebra import Vector3
from OSGridConverter.mapping import Datum
from math import radians,degrees,sin,cos,sqrt,atan2,isnan
class Cartesian (Vector3):
def __init__(self,arg):
try:
phi=radians(arg.latitude)
l... | [
"math.isnan",
"math.sqrt",
"math.atan2",
"math.radians",
"math.sin",
"math.cos",
"OSGridConverter.mapping.Datum.get",
"math.degrees"
] | [((1208, 1229), 'math.atan2', 'atan2', (['self.y', 'self.x'], {}), '(self.y, self.x)\n', (1213, 1229), False, 'from math import radians, degrees, sin, cos, sqrt, atan2, isnan\n'), ((1505, 1522), 'OSGridConverter.mapping.Datum.get', 'Datum.get', (['newTag'], {}), '(newTag)\n', (1514, 1522), False, 'from OSGridConverter.... |
"""
https://www.practicepython.org
Exercise 18: Cows and Bulls
3 chilis
Create a program that will play the “cows and bulls” game with the user.
The game works like this:
Randomly generate a 4-digit number. Ask the user to guess a 4-digit number.
For every digit that the user guessed correctly in the correct place, ... | [
"random.triangular"
] | [((971, 990), 'random.triangular', 'random.triangular', ([], {}), '()\n', (988, 990), False, 'import random\n')] |
import time
mainIsOn = True
targetValue = -1
while mainIsOn:
print("Select category\n"
"0 - Close App\n"
"1 - Lists\n"
"2 - While\n")
if targetValue == -1:
try:
targetValue = int(input())
except ValueError as e:
print("Wrong statement. Try ag... | [
"time.sleep"
] | [((610, 623), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (620, 623), False, 'import time\n'), ((954, 967), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (964, 967), False, 'import time\n'), ((1053, 1066), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (1063, 1066), False, 'import time\n'), ((1094, 1... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 TH<NAME>, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in complianc... | [
"backend.components.paas_auth.get_access_token",
"backend.utils.FancyDict",
"backend.utils.whitelist.can_access_webconsole",
"backend.components.paas_auth.get_user_by_access_token",
"logging.getLogger"
] | [((962, 989), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (979, 989), False, 'import logging\n'), ((2314, 2355), 'backend.utils.FancyDict', 'FancyDict', ([], {'user_access_token': 'access_token'}), '(user_access_token=access_token)\n', (2323, 2355), False, 'from backend.utils import Fa... |
#!/user/bin/env python
#_*_ coding=utf-8 *_*
"""
Function:微信消息自动回复
Date:2015/05/26
Author:lvzhang
ChangeLog:v0.1 init
"""
import itchat
@itchat.msg_register('Text')
def text_replay(msg):
# 自己实现问答
print("已经自动回复")
return "[自动回复]您好,我正忙,一会儿再联系您!!!"
if __name__=="__main__":
print("运行成功!!!")
itchat.aut... | [
"itchat.auto_login",
"itchat.run",
"itchat.msg_register"
] | [((138, 165), 'itchat.msg_register', 'itchat.msg_register', (['"""Text"""'], {}), "('Text')\n", (157, 165), False, 'import itchat\n'), ((310, 343), 'itchat.auto_login', 'itchat.auto_login', ([], {'hotReload': '(True)'}), '(hotReload=True)\n', (327, 343), False, 'import itchat\n'), ((348, 360), 'itchat.run', 'itchat.run... |
import unittest
import random
import numpy as np
from mep.genetics.population import Population
from mep.genetics.chromosome import Chromosome
class TestPopulation(unittest.TestCase):
"""
Test the Population class.
"""
def test_random_tournament_selection(self):
"""
Test the random_to... | [
"numpy.zeros",
"random.seed",
"mep.genetics.chromosome.Chromosome"
] | [((401, 415), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (412, 415), False, 'import random\n'), ((1321, 1335), 'random.seed', 'random.seed', (['(0)'], {}), '(0)\n', (1332, 1335), False, 'import random\n'), ((534, 572), 'numpy.zeros', 'np.zeros', (['(num_examples, num_features)'], {}), '((num_examples, num_fe... |
from wtforms import (
StringField, SelectField, HiddenField
)
from webapp.home.forms import EDIForm
class AccessSelectForm(EDIForm):
pass
class AccessForm(EDIForm):
userid = StringField('User ID', validators=[])
permission = SelectField('Permission',
choices=[("all", "a... | [
"wtforms.StringField",
"wtforms.HiddenField",
"wtforms.SelectField"
] | [((191, 228), 'wtforms.StringField', 'StringField', (['"""User ID"""'], {'validators': '[]'}), "('User ID', validators=[])\n", (202, 228), False, 'from wtforms import StringField, SelectField, HiddenField\n'), ((246, 381), 'wtforms.SelectField', 'SelectField', (['"""Permission"""'], {'choices': "[('all', 'all'), ('chan... |
import time, discord
from Config._functions import grammar_list
class EVENT:
LOADED = False
RUNNING = False
param = { # Define all the parameters necessary
"CHANNEL": "",
"EMOJIS": []
}
# Executes when loaded
def __init__(self):
self.LOADED = True
# Executes when activated
def start(self, TWOW_CENTR... | [
"Config._functions.grammar_list"
] | [((1284, 1305), 'Config._functions.grammar_list', 'grammar_list', (['correct'], {}), '(correct)\n', (1296, 1305), False, 'from Config._functions import grammar_list\n'), ((1405, 1428), 'Config._functions.grammar_list', 'grammar_list', (['incorrect'], {}), '(incorrect)\n', (1417, 1428), False, 'from Config._functions im... |
import re
from typing import Any, Dict, List, Optional, Type
from dokklib_db.errors import exceptions as ex
from dokklib_db.errors.client import ClientError
from dokklib_db.op_args import OpArg
CancellationReasons = List[Optional[Type[ClientError]]]
class TransactionCanceledException(ClientError):
"""The entir... | [
"re.search",
"re.compile"
] | [((584, 643), 're.compile', 're.compile', (['"""reasons\\\\W+\\\\[([A-Za-z0-9, ]+)]"""', 're.MULTILINE'], {}), "('reasons\\\\W+\\\\[([A-Za-z0-9, ]+)]', re.MULTILINE)\n", (594, 643), False, 'import re\n'), ((1615, 1651), 're.search', 're.search', (['self._reasons_re', 'message'], {}), '(self._reasons_re, message)\n', (1... |
# -*- coding: utf-8 -*-
from __future__ import print_function,division
import os
import time
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
from torch.autograd import Variable
from torchvision import datasets,transforms
from load_text i... | [
"torch.optim.lr_scheduler.StepLR",
"argparse.ArgumentParser",
"loss.TripletLoss",
"random.shuffle",
"loader.ClassUniformlySampler",
"load_text.load_dataset",
"random.randint",
"torch.multiprocessing.set_sharing_strategy",
"torch.load",
"utils.getDataset",
"utils.save_network",
"utils.Logger",
... | [((628, 685), 'torch.multiprocessing.set_sharing_strategy', 'torch.multiprocessing.set_sharing_strategy', (['"""file_system"""'], {}), "('file_system')\n", (670, 685), False, 'import torch\n'), ((696, 753), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Training arguments"""'}), "(descri... |
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
#=======================================================================================
# Imports
#=======================================================================================
import sys
import os
from lib.configutils import *
#===============================... | [
"os.path.dirname",
"os.path.join"
] | [((1605, 1645), 'os.path.join', 'os.path.join', (['self.execDirPath', '"""config"""'], {}), "(self.execDirPath, 'config')\n", (1617, 1645), False, 'import os\n'), ((1673, 1714), 'os.path.join', 'os.path.join', (['self.execDirPath', '"""plugins"""'], {}), "(self.execDirPath, 'plugins')\n", (1685, 1714), False, 'import o... |
#! /usr/bin/python3
import subprocess
import time
import sys
import os
subprocess.Popen(["./marueditor.py","--debug"])
while 1:
time.sleep(1)
| [
"subprocess.Popen",
"time.sleep"
] | [((72, 120), 'subprocess.Popen', 'subprocess.Popen', (["['./marueditor.py', '--debug']"], {}), "(['./marueditor.py', '--debug'])\n", (88, 120), False, 'import subprocess\n'), ((133, 146), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (143, 146), False, 'import time\n')] |
import os, yaml
config = {
'debug': False,
'user': '',
'token': '',
'sql_url': '',
'client_id': '',
'client_secret': '',
'cookie_secret': '',
'redirect_uri': '',
'web_port': 8001,
'irc': {
'host': 'irc.chat.twitch.tv',
'port': 6697,
'use_ssl': True,
}... | [
"os.environ.get",
"os.path.isfile",
"yaml.load",
"os.path.expanduser"
] | [((1048, 1086), 'os.environ.get', 'os.environ.get', (['"""LOGITCH_CONFIG"""', 'None'], {}), "('LOGITCH_CONFIG', None)\n", (1062, 1086), False, 'import os, yaml\n'), ((1360, 1380), 'os.path.isfile', 'os.path.isfile', (['path'], {}), '(path)\n', (1374, 1380), False, 'import os, yaml\n'), ((1496, 1508), 'yaml.load', 'yaml... |
import config.config as config
# Decoder class for use with a rotary encoder.
class decoder:
"""Class to decode mechanical rotary encoder pulses."""
def __init__(self, pi, rot_gpioA, rot_gpioB, switch_gpio, rotation_callback, switch_callback):
"""
Instantiate the class with the p... | [
"rotary_encoder.decoder",
"pigpio.pi",
"time.sleep"
] | [((3833, 3844), 'pigpio.pi', 'pigpio.pi', ([], {}), '()\n', (3842, 3844), False, 'import pigpio\n'), ((3862, 3904), 'rotary_encoder.decoder', 'rotary_encoder.decoder', (['pi', '(2)', '(4)', 'callback'], {}), '(pi, 2, 4, callback)\n', (3884, 3904), False, 'import rotary_encoder\n'), ((3912, 3927), 'time.sleep', 'time.sl... |
import arcade
from game.title_view import Title
from game.player import Player
from game import constants
class Director():
def __init__(self):
"""Directs the game"""
self.window = arcade.Window(
constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT, constants.SCREEN_TITLE)
self.main... | [
"game.title_view.Title",
"game.player.Player",
"arcade.run",
"arcade.Window"
] | [((203, 294), 'arcade.Window', 'arcade.Window', (['constants.SCREEN_WIDTH', 'constants.SCREEN_HEIGHT', 'constants.SCREEN_TITLE'], {}), '(constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT, constants.\n SCREEN_TITLE)\n', (216, 294), False, 'import arcade\n'), ((345, 353), 'game.player.Player', 'Player', ([], {}), '()\n'... |
import os
import tornado.httpserver
import tornado.ioloop
import tornado.log
import tornado.web
from tornado.options import define, options, parse_command_line
import config
import handlers.web
import handlers.api
class Application(tornado.web.Application):
def __init__(self, debug):
routes = [
... | [
"os.path.dirname",
"tornado.options.define",
"tornado.options.parse_command_line"
] | [((1295, 1353), 'tornado.options.define', 'define', (['"""port"""'], {'default': 'config.port', 'help': '"""port"""', 'type': 'int'}), "('port', default=config.port, help='port', type=int)\n", (1301, 1353), False, 'from tornado.options import define, options, parse_command_line\n'), ((1364, 1431), 'tornado.options.defi... |
#!env python
import sys
import json
import csv
json_input = json.load(sys.stdin)
csv_output = csv.writer(sys.stdout)
csv_output.writerow(['Library', 'URL', 'License'])
for package_name, data in json_input.items():
name = package_name.split('@')[0]
url = ''
if 'homepage' in data:
if type(data['h... | [
"json.load",
"csv.writer"
] | [((62, 82), 'json.load', 'json.load', (['sys.stdin'], {}), '(sys.stdin)\n', (71, 82), False, 'import json\n'), ((96, 118), 'csv.writer', 'csv.writer', (['sys.stdout'], {}), '(sys.stdout)\n', (106, 118), False, 'import csv\n')] |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Q
from django_datatables_view.base_datatable_view import BaseDatatableView
from apps.Servers.models import TemplateServer, ServerProfile, Parameters
class ServerTemplatesListJson(LoginRequiredMixin, BaseDatatableView):
model =... | [
"django.db.models.Q"
] | [((620, 645), 'django.db.models.Q', 'Q', ([], {'name__icontains': 'search'}), '(name__icontains=search)\n', (621, 645), False, 'from django.db.models import Q\n'), ((664, 696), 'django.db.models.Q', 'Q', ([], {'description__icontains': 'search'}), '(description__icontains=search)\n', (665, 696), False, 'from django.db.... |
# %% Packages
import json
from dotmap import DotMap
# %% Functions
def get_config_from_json(json_file):
with open(json_file, "r") as config_file:
config_dict = json.load(config_file)
config = DotMap(config_dict)
return config
def process_config(json_file):
config = get_config_from_json(js... | [
"dotmap.DotMap",
"json.load"
] | [((213, 232), 'dotmap.DotMap', 'DotMap', (['config_dict'], {}), '(config_dict)\n', (219, 232), False, 'from dotmap import DotMap\n'), ((177, 199), 'json.load', 'json.load', (['config_file'], {}), '(config_file)\n', (186, 199), False, 'import json\n')] |
from typing import Callable
import numpy as np
import torch
import torch.nn as nn
from util.data import transform_observation
class PommerQEmbeddingRNN(nn.Module):
def __init__(self, embedding_model):
super(PommerQEmbeddingRNN, self).__init__()
self.embedding_model = embedding_model
self.... | [
"torch.nn.ReLU",
"util.data.transform_observation",
"torch.nn.Softmax",
"numpy.array",
"torch.nn.Linear",
"torch.device",
"torch.nn.LSTM",
"torch.nn.Flatten"
] | [((400, 415), 'torch.nn.LSTM', 'nn.LSTM', (['(64)', '(64)'], {}), '(64, 64)\n', (407, 415), True, 'import torch.nn as nn\n'), ((497, 509), 'torch.nn.Flatten', 'nn.Flatten', ([], {}), '()\n', (507, 509), True, 'import torch.nn as nn\n'), ((523, 532), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (530, 532), True, 'impor... |
# This script does the following:
# 1) Record H264 Video using PiCam at a maximum bitrate of 300 kbps
# 2) Stream video data to a local BytesIO object
# 3) Send raw data over LTE
# 4) Store raw data to an onboard file
# 5) Clears BytesIO object after network stream and file store
# 6) Interrupts and ends recording afte... | [
"io.BytesIO",
"threading.Timer",
"Hologram.HologramCloud.HologramCloud",
"socket.socket",
"os.system",
"time.time",
"picamera.PiCamera"
] | [((1709, 1719), 'picamera.PiCamera', 'PiCamera', ([], {}), '()\n', (1717, 1719), False, 'from picamera import PiCamera\n'), ((3440, 3449), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (3447, 3449), False, 'from io import BytesIO\n'), ((3928, 3939), 'time.time', 'time.time', ([], {}), '()\n', (3937, 3939), False, 'import ... |
# coding: utf8
"""
weasyprint.tests.w3_test_suite.web
----------------------------------
A simple web application to run and inspect the results of
the W3C CSS 2.1 Test Suite.
See http://test.csswg.org/suites/css2.1/20110323/
:copyright: Copyright 2011-2012 <NAME> and contributors, see AUTHOR... | [
"pygments.formatters.HtmlFormatter",
"flask.safe_join",
"weasyprint.CSS",
"flask.Flask",
"flask.abort",
"pygments.lexers.HtmlLexer",
"flask.send_from_directory"
] | [((2591, 2606), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (2596, 2606), False, 'from flask import Flask, render_template, abort, send_from_directory, safe_join\n'), ((3515, 3619), 'weasyprint.CSS', 'CSS', ([], {'string': '"""\n @page { margin: 20px; size: 680px }\n body { margin: 0 }\n ... |
# This script parses MLB data from retrosheet and creates a dataframe
# Importing required modules
import pandas as pd
import glob
# Defining username + directory
username = ''
filepath = 'C:/Users/' + username + '/Documents/Data/mlbozone/'
# Create a list of all files in the raw_data subfolder
file... | [
"pandas.read_csv",
"pandas.concat",
"pandas.Series",
"glob.glob"
] | [((342, 376), 'glob.glob', 'glob.glob', (["(filepath + 'raw_data/*')"], {}), "(filepath + 'raw_data/*')\n", (351, 376), False, 'import glob\n'), ((1882, 1922), 'pandas.Series', 'pd.Series', (['attendance'], {'name': '"""Attendance"""'}), "(attendance, name='Attendance')\n", (1891, 1922), True, 'import pandas as pd\n'),... |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from six.moves.urllib.parse import urlencode, quote
from nltk.token... | [
"nltk.tokenize.RegexpTokenizer",
"time.sleep",
"selenium.webdriver.ChromeOptions",
"selenium.webdriver.Chrome",
"bs4.BeautifulSoup",
"selenium.webdriver.support.ui.WebDriverWait"
] | [((426, 459), 'nltk.tokenize.RegexpTokenizer', 'RegexpTokenizer', (['"""[a-zA-Z\\\\s\\\\d]"""'], {}), "('[a-zA-Z\\\\s\\\\d]')\n", (441, 459), False, 'from nltk.tokenize import RegexpTokenizer\n'), ((470, 495), 'selenium.webdriver.ChromeOptions', 'webdriver.ChromeOptions', ([], {}), '()\n', (493, 495), False, 'from sele... |
from django.shortcuts import render,redirect
from .models import QuesModel
from django.http import JsonResponse
# Create your views here.
def audioquiz(request):
quiz=QuesModel.objects.all()
if request.method == 'POST':
print(request.POST)
score = 0
wrong = 0
correct = 0
... | [
"django.shortcuts.render",
"django.http.JsonResponse"
] | [((959, 1002), 'django.shortcuts.render', 'render', (['request', '"""aqz.html"""', "{'quiz': quiz}"], {}), "(request, 'aqz.html', {'quiz': quiz})\n", (965, 1002), False, 'from django.shortcuts import render, redirect\n'), ((1144, 1172), 'django.http.JsonResponse', 'JsonResponse', (["{'quiz': quiz}"], {}), "({'quiz': qu... |
# -*- coding: utf-8 -*-
#
from math import pi
import numpy
from .. import helpers
def show(scheme, backend="mpl"):
"""Displays scheme for 3D ball quadrature.
"""
helpers.backend_to_function[backend](
scheme.points,
scheme.weights,
volume=4.0 / 3.0 * pi,
edges=[],
b... | [
"numpy.multiply.outer",
"numpy.array",
"numpy.swapaxes"
] | [((438, 457), 'numpy.array', 'numpy.array', (['center'], {}), '(center)\n', (449, 457), False, 'import numpy\n'), ((467, 508), 'numpy.multiply.outer', 'numpy.multiply.outer', (['radius', 'rule.points'], {}), '(radius, rule.points)\n', (487, 508), False, 'import numpy\n'), ((518, 543), 'numpy.swapaxes', 'numpy.swapaxes'... |
import unittest
from pyjsonassert.matchers import StringMatcher
class TestStringMatcher(unittest.TestCase):
string = "asfasdf"
number_as_string = "12"
number = 12
float = 12.2
boolean = False
def test_should_identify_an_string(self):
assert StringMatcher.match(self.string) is True
... | [
"pyjsonassert.matchers.StringMatcher.match"
] | [((278, 310), 'pyjsonassert.matchers.StringMatcher.match', 'StringMatcher.match', (['self.string'], {}), '(self.string)\n', (297, 310), False, 'from pyjsonassert.matchers import StringMatcher\n'), ((414, 456), 'pyjsonassert.matchers.StringMatcher.match', 'StringMatcher.match', (['self.number_as_string'], {}), '(self.nu... |
from machine import Pin
led1 = Pin(("LED1", 52), Pin.OUT_PP)
led2 = Pin(("LED2", 53), Pin.OUT_PP)
key1 = Pin(("KEY1", 85), Pin.IN, Pin.PULL_UP)
key2 = Pin(("KEY2", 86), Pin.IN, Pin.PULL_UP)
while True:
if key1.value():
led1.value(1)
else:
led1.value(0)
if key2.value():
led2.value(1)
... | [
"machine.Pin"
] | [((31, 60), 'machine.Pin', 'Pin', (["('LED1', 52)", 'Pin.OUT_PP'], {}), "(('LED1', 52), Pin.OUT_PP)\n", (34, 60), False, 'from machine import Pin\n'), ((68, 97), 'machine.Pin', 'Pin', (["('LED2', 53)", 'Pin.OUT_PP'], {}), "(('LED2', 53), Pin.OUT_PP)\n", (71, 97), False, 'from machine import Pin\n'), ((105, 143), 'machi... |
# -*- coding: utf-8 -*-
#
# inventory/suppliers/admin.py
#
"""
Supplier Admin
"""
__docformat__ = "restructuredtext en"
from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from inventory.common.admin_mixins import UserAdminMixin, UpdaterFilter
from .models import Supplier
#
# Su... | [
"django.contrib.admin.register",
"django.utils.translation.gettext_lazy"
] | [((335, 359), 'django.contrib.admin.register', 'admin.register', (['Supplier'], {}), '(Supplier)\n', (349, 359), False, 'from django.contrib import admin\n'), ((728, 739), 'django.utils.translation.gettext_lazy', '_', (['"""Status"""'], {}), "('Status')\n", (729, 739), True, 'from django.utils.translation import gettex... |
#----------------------------------------------------------------------------#
# Imports
#----------------------------------------------------------------------------#
from flask import Flask, render_template, request
from flask_basicauth import BasicAuth
# from flask.ext.sqlalchemy import SQLAlchemy
import logging
fr... | [
"pymongo.MongoClient",
"logging.FileHandler",
"flask.Flask",
"flask_basicauth.BasicAuth",
"logging.Formatter",
"flask.render_template",
"flask.request.get_json"
] | [((638, 653), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (643, 653), False, 'from flask import Flask, render_template, request\n'), ((798, 812), 'flask_basicauth.BasicAuth', 'BasicAuth', (['app'], {}), '(app)\n', (807, 812), False, 'from flask_basicauth import BasicAuth\n'), ((848, 959), 'pymongo.Mongo... |
from rest_framework import exceptions, status
from rest_framework.views import Response, exception_handler
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first to get the standard error response.
response = exception_handler(exc, context)
# if there is an In... | [
"rest_framework.views.exception_handler"
] | [((264, 295), 'rest_framework.views.exception_handler', 'exception_handler', (['exc', 'context'], {}), '(exc, context)\n', (281, 295), False, 'from rest_framework.views import Response, exception_handler\n')] |
"""
Utils for generating random data and comparing performance
"""
import os
import time
import pickle
import random
from kmeans import kmeans, here
here = here(__file__)
try:
range = xrange
except NameError:
pass
def timer():
start = time.clock()
return lambda: time.clock() - start
def random_poin... | [
"pickle.dump",
"kmeans.kmeans",
"kmeans.here",
"time.clock",
"pickle.load",
"random.randrange",
"os.path.join"
] | [((156, 170), 'kmeans.here', 'here', (['__file__'], {}), '(__file__)\n', (160, 170), False, 'from kmeans import kmeans, here\n'), ((250, 262), 'time.clock', 'time.clock', ([], {}), '()\n', (260, 262), False, 'import time\n'), ((651, 685), 'os.path.join', 'os.path.join', (['here', '"""_perf.sample"""'], {}), "(here, '_p... |
# Examples from the article "Two-stage recursive algorithms in XSLT"
# By <NAME> and <NAME>
# http://www.topxml.com/xsl/articles/recurse/
from Xml.Xslt import test_harness
BOOKS = """ <book>
<title>Angela's Ashes</title>
<author><NAME></author>
<publisher>HarperCollins</publisher>
<isbn>0 00... | [
"Xml.Xslt.test_harness.FileInfo",
"Xml.Xslt.test_harness.XsltTest"
] | [((17899, 17936), 'Xml.Xslt.test_harness.FileInfo', 'test_harness.FileInfo', ([], {'string': 'sheet_1'}), '(string=sheet_1)\n', (17920, 17936), False, 'from Xml.Xslt import test_harness\n'), ((18412, 18449), 'Xml.Xslt.test_harness.FileInfo', 'test_harness.FileInfo', ([], {'string': 'sheet_2'}), '(string=sheet_2)\n', (1... |
from click.testing import CliRunner
from luna.pathology.cli.infer_tile_labels import cli
def test_cli(tmp_path):
runner = CliRunner()
result = runner.invoke(cli, [
'pyluna-pathology/tests/luna/pathology/cli/testdata/data/test/slides/123/test_generate_tile_ov_labels/TileImages/data/',
... | [
"click.testing.CliRunner"
] | [((130, 141), 'click.testing.CliRunner', 'CliRunner', ([], {}), '()\n', (139, 141), False, 'from click.testing import CliRunner\n')] |
import logging
import requests
from injector import inject
import app_config
from microsoft_graph import MicrosoftGraphAuthentication
class MicrosoftGraph:
@inject
def __init__(self, authentication_handler: MicrosoftGraphAuthentication):
self.authentication_handler = authentication_handler
d... | [
"logging.error",
"requests.get"
] | [((684, 718), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (696, 718), False, 'import requests\n'), ((918, 952), 'logging.error', 'logging.error', (['"""token not updated"""'], {}), "('token not updated')\n", (931, 952), False, 'import logging\n')] |
from semantic_aware_models.models.recommendation.abstract_recommender import AbstractRecommender
from semantic_aware_models.dataset.movielens.movielens_data_model import *
from surprise import NormalPredictor
from surprise.reader import Reader
from surprise.dataset import Dataset
import time
class RandomRecommender(... | [
"surprise.dataset.Dataset",
"surprise.NormalPredictor",
"time.time"
] | [((692, 709), 'surprise.NormalPredictor', 'NormalPredictor', ([], {}), '()\n', (707, 709), False, 'from surprise import NormalPredictor\n'), ((2301, 2323), 'surprise.dataset.Dataset', 'Dataset', ([], {'reader': 'reader'}), '(reader=reader)\n', (2308, 2323), False, 'from surprise.dataset import Dataset\n'), ((3295, 3306... |
import torch, sys
import torch.nn as nn
sys.path.append('..')
from MPLayers.lib_stereo import TRWP_hard_soft as TRWP_stereo
from MPLayers.lib_seg import TRWP_hard_soft as TRWP_seg
from utils.label_context import create_label_context
# references:
# http://www.benjack.io/2017/06/12/python-cpp-tests.html
# https://pytor... | [
"sys.path.append",
"utils.label_context.create_label_context",
"torch.empty",
"torch.sigmoid",
"torch.nn.Softmax"
] | [((40, 61), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (55, 61), False, 'import torch, sys\n'), ((5845, 5958), 'utils.label_context.create_label_context', 'create_label_context', (['self.args'], {'enable_seg': 'self.args.enable_seg', 'enable_symmetric': 'self.args.enable_symmetric'}), '(self.... |
from __future__ import print_function
import keras.backend as K
import keras.losses as losses
import keras.optimizers as optimizers
import numpy as np
from keras.callbacks import ModelCheckpoint
from keras.layers.advanced_activations import LeakyReLU
from keras.layers import Input, RepeatVector, Reshape
from keras.la... | [
"keras.layers.Input",
"numpy.expand_dims",
"keras.models.Model"
] | [((1293, 1334), 'keras.layers.Input', 'Input', (['img_shape'], {'name': '"""predictor_img_in"""'}), "(img_shape, name='predictor_img_in')\n", (1298, 1334), False, 'from keras.layers import Input, RepeatVector, Reshape\n'), ((1352, 1394), 'keras.layers.Input', 'Input', (['img_shape'], {'name': '"""predictor_img0_in"""'}... |
import random
from collections import OrderedDict
from urllib.parse import quote
from rest_framework import filters
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
DEFAULT_PAGE_SIZE = 15
DEFAULT_SEED = 1234
class OptionalPageNumberPagination(PageNumberPaginat... | [
"collections.OrderedDict",
"urllib.parse.quote"
] | [((2345, 2447), 'collections.OrderedDict', 'OrderedDict', (["[('count', self._random_count), ('next', self._random_next_page), (\n 'results', data)]"], {}), "([('count', self._random_count), ('next', self._random_next_page\n ), ('results', data)])\n", (2356, 2447), False, 'from collections import OrderedDict\n'),... |
import inspect
import os
import sys
import time
from datetime import datetime
from uuid import uuid4
import pkg_resources
import pyfiglet
from ZathuraProject.bugtracker import (send_data_to_bugtracker,
send_verbose_log_to_bugtracker)
CURRENT_VERSION = "v0.0.6 beta"
def create... | [
"ZathuraProject.bugtracker.send_data_to_bugtracker",
"ZathuraProject.bugtracker.send_verbose_log_to_bugtracker",
"pyfiglet.figlet_format",
"inspect.stack",
"sys.exit"
] | [((435, 448), 'sys.exit', 'sys.exit', (['(255)'], {}), '(255)\n', (443, 448), False, 'import sys\n'), ((728, 775), 'pyfiglet.figlet_format', 'pyfiglet.figlet_format', (['"""Zathura"""'], {'font': '"""speed"""'}), "('Zathura', font='speed')\n", (750, 775), False, 'import pyfiglet\n'), ((1990, 2150), 'ZathuraProject.bugt... |
import torch
import numpy as np
import pickle
def filterit(s,W2ID):
s=s.lower()
S=''
for c in s:
if c in ' abcdefghijklmnopqrstuvwxyz0123456789':
S+=c
S = " ".join([x if x and x in W2ID else "<unk>" for x in S.split()])
return S
def Sentence2Embeddings(sentence,W2ID,EMB):
if... | [
"torch.stack",
"pickle.load",
"torch.nn.utils.rnn.pad_sequence",
"numpy.vstack",
"torch.from_numpy"
] | [((1080, 1115), 'numpy.vstack', 'np.vstack', (['[GloVe[w] for w in W2ID]'], {}), '([GloVe[w] for w in W2ID])\n', (1089, 1115), True, 'import numpy as np\n'), ((1651, 1665), 'torch.stack', 'torch.stack', (['A'], {}), '(A)\n', (1662, 1665), False, 'import torch\n'), ((1908, 1922), 'torch.stack', 'torch.stack', (['A'], {}... |
#!/usr/bin/env python
# coding:utf-8
"""
Name : test_mod_group.py
Author : <NAME>
Date : 6/21/2021
Desc:
"""
from model.group import Group
from random import randrange
def test_modification_some_group(app, db, check_ui):
if len(db.get_group_list()) == 0:
app.group.create(Group(name="test"))
... | [
"model.group.Group"
] | [((405, 450), 'model.group.Group', 'Group', ([], {'name': '"""111"""', 'header': '"""222"""', 'footer': '"""333"""'}), "(name='111', header='222', footer='333')\n", (410, 450), False, 'from model.group import Group\n'), ((1008, 1031), 'model.group.Group', 'Group', ([], {'name': '"""New group"""'}), "(name='New group')\... |
#! /usr/bin/env python
import tensorflow as tf
import numpy as np
import os
import data_helpers
import csv
import pickle
import data_helpers as dp
import json
# Parameters
# ==================================================
# Data Parameters
tf.flags.DEFINE_string("positive_data_file", "./data/rt-polaritydata/rt-po... | [
"json.load",
"tensorflow.Session",
"data_helpers.pad_sentences",
"tensorflow.ConfigProto",
"pickle.load",
"tensorflow.train.latest_checkpoint",
"tensorflow.Graph",
"tensorflow.flags.DEFINE_integer",
"os.path.join",
"tensorflow.flags.DEFINE_boolean",
"tensorflow.flags.DEFINE_string"
] | [((246, 378), 'tensorflow.flags.DEFINE_string', 'tf.flags.DEFINE_string', (['"""positive_data_file"""', '"""./data/rt-polaritydata/rt-polarity.pos"""', '"""Data source for the positive data."""'], {}), "('positive_data_file',\n './data/rt-polaritydata/rt-polarity.pos',\n 'Data source for the positive data.')\n", ... |
#! /usr/bin/env python3
import argparse
import yaml
def merge_two_dict(d1, d2):
result = {}
for key in set(d1) | set(d2):
if isinstance(d1.get(key), dict) or isinstance(d2.get(key), dict):
result[key] = merge_two_dict(d1.get(key, dict()), d2.get(key, dict()))
else:
res... | [
"yaml.safe_load",
"argparse.ArgumentParser",
"yaml.safe_dump"
] | [((848, 896), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'description'}), '(description=description)\n', (871, 896), False, 'import argparse\n'), ((686, 721), 'yaml.safe_dump', 'yaml.safe_dump', (['output', 'open_output'], {}), '(output, open_output)\n', (700, 721), False, 'import yaml\n... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''第 0015 题: 纯文本文件 city.txt为城市信息, 里面的内容(包括花括号)如下所示:
{
"1" : "上海",
"2" : "北京",
"3" : "成都"
}
请将上述内容写到 city.xls 文件中。'''
__author__ = 'Drake-Z'
import json
from collections import OrderedDict
from openpyxl import Workbook
def txt_to_xlsx(filename):
file = o... | [
"json.load",
"openpyxl.Workbook"
] | [((378, 411), 'json.load', 'json.load', (['file'], {'encoding': '"""UTF-8"""'}), "(file, encoding='UTF-8')\n", (387, 411), False, 'import json\n'), ((453, 463), 'openpyxl.Workbook', 'Workbook', ([], {}), '()\n', (461, 463), False, 'from openpyxl import Workbook\n')] |
import jax
import jax.numpy as np
import time
import skimage.io
num_iter = 10
key = jax.random.PRNGKey(1234)
Mask = np.array(skimage.io.imread('../data/Mask0.png')) > 0
Mask = np.reshape(Mask, [Mask.shape[0], Mask.shape[1], 1])
Offsets = jax.random.uniform(key, shape=[Mask.shape[0], Mask.shape[1], 2], dtype=np.float3... | [
"jax.jvp",
"jax.random.uniform",
"jax.jit",
"jax.numpy.roll",
"jax.numpy.stack",
"jax.numpy.logical_and",
"time.time",
"jax.vjp",
"jax.random.PRNGKey",
"jax.numpy.cos",
"jax.numpy.ones",
"jax.numpy.sin",
"jax.numpy.reshape"
] | [((86, 110), 'jax.random.PRNGKey', 'jax.random.PRNGKey', (['(1234)'], {}), '(1234)\n', (104, 110), False, 'import jax\n'), ((178, 229), 'jax.numpy.reshape', 'np.reshape', (['Mask', '[Mask.shape[0], Mask.shape[1], 1]'], {}), '(Mask, [Mask.shape[0], Mask.shape[1], 1])\n', (188, 229), True, 'import jax.numpy as np\n'), ((... |
"""Methods for unzipping files."""
import os
from gewittergefahr.gg_utils import file_system_utils
from gewittergefahr.gg_utils import error_checking
def unzip_tar(tar_file_name, target_directory_name=None,
file_and_dir_names_to_unzip=None):
"""Unzips tar file.
:param tar_file_name: Path to in... | [
"gewittergefahr.gg_utils.error_checking.assert_is_string_list",
"os.remove",
"gewittergefahr.gg_utils.error_checking.assert_is_boolean",
"os.system",
"gewittergefahr.gg_utils.error_checking.assert_is_string",
"gewittergefahr.gg_utils.file_system_utils.mkdir_recursive_if_necessary",
"gewittergefahr.gg_ut... | [((729, 775), 'gewittergefahr.gg_utils.error_checking.assert_is_string', 'error_checking.assert_is_string', (['tar_file_name'], {}), '(tar_file_name)\n', (760, 775), False, 'from gewittergefahr.gg_utils import error_checking\n'), ((780, 845), 'gewittergefahr.gg_utils.error_checking.assert_is_string_list', 'error_checki... |
from rest_framework import generics, authentication, permissions
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.exceptions import ValidationError, AuthenticationFailed
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework impor... | [
"rest_framework.exceptions.AuthenticationFailed",
"rest_framework.authtoken.models.Token.objects.get_or_create",
"django.contrib.auth.get_user_model",
"rest_framework.response.Response",
"rest_framework.exceptions.ValidationError"
] | [((1093, 1133), 'rest_framework.authtoken.models.Token.objects.get_or_create', 'Token.objects.get_or_create', ([], {'user': 'author'}), '(user=author)\n', (1120, 1133), False, 'from rest_framework.authtoken.models import Token\n'), ((1305, 1335), 'rest_framework.response.Response', 'Response', (["{'token': token.key}"]... |
#Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo retângulo.
#Calcule e mostre o comprimento da hipotenusa.
"""co = float(input('Valor cateto oposto: '))
ca = float(input('valor cateto adjacente: '))
hi = (co ** 2 + ca ** 2) ** (1/2)
print('O valor da hipotenusa é {:.2f}'.... | [
"math.hypot"
] | [((656, 669), 'math.hypot', 'hypot', (['co', 'ca'], {}), '(co, ca)\n', (661, 669), False, 'from math import hypot\n')] |
import numpy as np
import torch
import torch.nn as nn
from two_thinning.average_based.RL.basic_neuralnet_RL.neural_network import AverageTwoThinningNet
n = 10
m = n
epsilon = 0.1
train_episodes = 3000
eval_runs = 300
patience = 20
print_progress = True
print_behaviour = False
def reward(x):
return -np.max(x)
... | [
"torch.nn.MSELoss",
"torch.argmax",
"torch.DoubleTensor",
"numpy.zeros",
"two_thinning.average_based.RL.basic_neuralnet_RL.neural_network.AverageTwoThinningNet",
"numpy.max",
"numpy.random.randint",
"torch.cuda.is_available",
"torch.rand",
"torch.no_grad"
] | [((494, 521), 'torch.argmax', 'torch.argmax', (['action_values'], {}), '(action_values)\n', (506, 521), False, 'import torch\n'), ((663, 676), 'torch.rand', 'torch.rand', (['(1)'], {}), '(1)\n', (673, 676), False, 'import torch\n'), ((1804, 1836), 'two_thinning.average_based.RL.basic_neuralnet_RL.neural_network.Average... |
from pathlib import Path
from echopype.convert import Convert
def test_2in1_ek80_conversion():
file = Path("./echopype/test_data/ek80/Green2.Survey2.FM.short.slow.-D20191004-T211557.raw").resolve()
nc_path = file.parent.joinpath(file.stem+".nc")
tmp = Convert(str(file), model="EK80")
tmp.raw2nc()
... | [
"pathlib.Path"
] | [((108, 203), 'pathlib.Path', 'Path', (['"""./echopype/test_data/ek80/Green2.Survey2.FM.short.slow.-D20191004-T211557.raw"""'], {}), "(\n './echopype/test_data/ek80/Green2.Survey2.FM.short.slow.-D20191004-T211557.raw'\n )\n", (112, 203), False, 'from pathlib import Path\n')] |
import random
import string
import unittest
from find_the_difference import Solution
from hypothesis import given
from hypothesis.strategies import text
class Test(unittest.TestCase):
def test_1(self):
solution = Solution()
self.assertEqual(solution.findTheDifference("abcd", "abcde"), "e")
@... | [
"unittest.main",
"find_the_difference.Solution",
"random.shuffle",
"random.choice",
"hypothesis.strategies.text"
] | [((646, 661), 'unittest.main', 'unittest.main', ([], {}), '()\n', (659, 661), False, 'import unittest\n'), ((228, 238), 'find_the_difference.Solution', 'Solution', ([], {}), '()\n', (236, 238), False, 'from find_the_difference import Solution\n'), ((383, 393), 'find_the_difference.Solution', 'Solution', ([], {}), '()\n... |
import os
import logging
import json
import pandas as pd
def data_paths_from_periodicity(periodicity):
if periodicity == 'hourly':
return ['../datasets/bitstamp_data_hourly.csv']
elif periodicity == 'daily':
return ['../datasets/bitstamp_data_daily.csv']
return ['../datasets/bitstamp_data.... | [
"pandas.DataFrame",
"pandas.concat",
"pandas.read_csv",
"pandas.merge",
"pandas.to_datetime",
"pandas.factorize",
"os.path.join",
"os.listdir"
] | [((1017, 1038), 'pandas.concat', 'pd.concat', (['li'], {'axis': '(0)'}), '(li, axis=0)\n', (1026, 1038), True, 'import pandas as pd\n'), ((1250, 1357), 'pandas.read_csv', 'pd.read_csv', (['filepath'], {'parse_dates': "['Timestamp']", 'date_parser': 'unix_time_to_date', 'index_col': '"""Timestamp"""'}), "(filepath, pars... |
from http import HTTPStatus
from random import sample
from unittest import mock
from urllib.parse import quote
from pytest import fixture
import jwt
from api.mappings import Sighting, Indicator, Relationship
from .utils import headers
def implemented_routes():
yield '/observe/observables'
yield '/refer/obse... | [
"unittest.mock.MagicMock",
"pytest.fixture",
"unittest.mock.patch",
"urllib.parse.quote",
"unittest.mock.call"
] | [((498, 521), 'pytest.fixture', 'fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (505, 521), False, 'from pytest import fixture\n'), ((4616, 4639), 'pytest.fixture', 'fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (4623, 4639), False, 'from pytest import fixture\n'), ((1776, 1792), 'u... |
# -*- coding: utf-8 -*-
"""
.. invisible:
_ _ _____ _ _____ _____
| | | | ___| | | ___/ ___|
| | | | |__ | | | |__ \ `--.
| | | | __|| | | __| `--. \
\ \_/ / |___| |___| |___/\__/ /
\___/\____/\_____|____/\____/
Created on Apr 13, 2015
BLAS class to use with ocl backend.
██... | [
"opencl4py.blas.CLBLAS",
"zope.interface.implementer",
"os.walk",
"numpy.zeros",
"threading.Lock",
"veles.dummy.DummyWorkflow",
"veles.numpy_ext.roundup",
"weakref.ref"
] | [((1621, 1645), 'zope.interface.implementer', 'implementer', (['IOpenCLUnit'], {}), '(IOpenCLUnit)\n', (1632, 1645), False, 'from zope.interface import implementer\n'), ((2720, 2736), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (2734, 2736), False, 'import threading\n'), ((2760, 2779), 'weakref.ref', 'weakref... |
# Copyright (c) Trainline Limited, 2016-2017. All rights reserved. See LICENSE.txt in the project root for license information.
import base64, json, logging, requests
from retrying import retry
class ConsulError(RuntimeError):
pass
def handle_connection_error(func):
def handle_error(*args, **kwargs):
... | [
"logging.exception",
"json.dumps",
"base64.b64decode",
"logging.info",
"requests.get",
"requests.put",
"retrying.retry"
] | [((1040, 1157), 'retrying.retry', 'retry', ([], {'retry_on_exception': 'retry_if_connection_error', 'wait_exponential_multiplier': '(1000)', 'wait_exponential_max': '(60000)'}), '(retry_on_exception=retry_if_connection_error,\n wait_exponential_multiplier=1000, wait_exponential_max=60000)\n', (1045, 1157), False, 'f... |
import argparse, socket
from time import sleep, time, localtime, strftime
import time
import logging
import sys
import trace
fhand = logging.FileHandler('new20180321.log', mode='a', encoding='GBK')
logging.basicConfig(level=logging.DEBUG, # 控制台打印的日志级别
handlers=[fhand],
format=... | [
"logging.FileHandler",
"logging.basicConfig",
"socket.socket",
"time.time",
"logging.info"
] | [((134, 198), 'logging.FileHandler', 'logging.FileHandler', (['"""new20180321.log"""'], {'mode': '"""a"""', 'encoding': '"""GBK"""'}), "('new20180321.log', mode='a', encoding='GBK')\n", (153, 198), False, 'import logging\n'), ((200, 315), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG', 'ha... |
from utils import parseSource, nodesToString, nodesToLines, dumpNodes, dumpTree
from converters import DecoratorConverter
def test_DecoratorGather_01():
src = """
@require_call_auth( "view" )
def bim():
pass
"""
matches = DecoratorConverter().gather( parseSource( src ) )
mat... | [
"utils.parseSource",
"utils.nodesToLines",
"converters.DecoratorConverter",
"utils.nodesToString"
] | [((640, 656), 'utils.parseSource', 'parseSource', (['src'], {}), '(src)\n', (651, 656), False, 'from utils import parseSource, nodesToString, nodesToLines, dumpNodes, dumpTree\n'), ((670, 690), 'converters.DecoratorConverter', 'DecoratorConverter', ([], {}), '()\n', (688, 690), False, 'from converters import DecoratorC... |
import json
from mobilebdd.reports.base import BaseReporter
class JsonReporter(BaseReporter):
"""
outputs the test run results in the form of a json
one example use case is to plug this into a bdd api that returns the results
in json format.
"""
def __init__(self, config):
super(Jso... | [
"json.dumps"
] | [((488, 528), 'json.dumps', 'json.dumps', (["{u'features': self.features}"], {}), "({u'features': self.features})\n", (498, 528), False, 'import json\n')] |
import json
import logging
from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
logger = logging.getLogger('pretix.security.csp')
@csrf_exempt
def csp_report(request):
try:
body = json.loads(request.body.decode())
logger.warning(
... | [
"django.http.HttpResponseBadRequest",
"django.http.HttpResponse",
"logging.getLogger"
] | [((152, 192), 'logging.getLogger', 'logging.getLogger', (['"""pretix.security.csp"""'], {}), "('pretix.security.csp')\n", (169, 192), False, 'import logging\n'), ((735, 749), 'django.http.HttpResponse', 'HttpResponse', ([], {}), '()\n', (747, 749), False, 'from django.http import HttpResponse, HttpResponseBadRequest\n'... |
# Generated by Django 2.0 on 2017-12-20 16:32
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ctf', '0002_auto_20171220_1128'),
]
operations = [
migrations.AlterField(
model_name='category',
... | [
"django.db.models.ForeignKey",
"django.db.models.TextField"
] | [((367, 521), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'null': '(True)', 'on_delete': 'django.db.models.deletion.SET_NULL', 'related_name': '"""categories_required_by"""', 'to': '"""ctf.Question"""'}), "(blank=True, null=True, on_delete=django.db.models.\n deletion.SET_NULL, relat... |
# Copyright 2020 HuaWei Technologies. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | [
"networking_mlnx_baremetal.ufm_client.get_client",
"oslo_log.log.getLogger",
"copy.deepcopy",
"neutron.db.provisioning_blocks.add_provisioning_component",
"networking_mlnx_baremetal.exceptions.PortBindingException",
"networking_mlnx_baremetal.ironic_client.get_client",
"networking_mlnx_baremetal.plugins... | [((1369, 1396), 'oslo_log.log.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1386, 1396), True, 'from oslo_log import log as logging\n'), ((1397, 1423), 'networking_mlnx_baremetal.plugins.ml2.config.register_opts', 'config.register_opts', (['CONF'], {}), '(CONF)\n', (1417, 1423), False, 'from net... |
import numpy as np
from lipkin.model import LipkinModel
class HartreeFock(LipkinModel):
name = 'Hartree-Fock'
def __init__(self, epsilon, V, Omega):
if Omega%2 == 1:
raise ValueError('This HF implementation assumes N = Omega = even.')
LipkinModel.__init__(self, e... | [
"numpy.empty",
"numpy.square",
"numpy.zeros",
"numpy.linalg.eig",
"lipkin.model.LipkinModel.__init__",
"numpy.sin",
"numpy.array",
"numpy.exp",
"numpy.random.normal",
"numpy.cos",
"numpy.dot",
"numpy.conjugate",
"numpy.sqrt"
] | [((292, 344), 'lipkin.model.LipkinModel.__init__', 'LipkinModel.__init__', (['self', 'epsilon', 'V', 'Omega', 'Omega'], {}), '(self, epsilon, V, Omega, Omega)\n', (312, 344), False, 'from lipkin.model import LipkinModel\n'), ((538, 562), 'numpy.array', 'np.array', (['[theta0, phi0]'], {}), '([theta0, phi0])\n', (546, 5... |
from typing import List, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
import robust_loss_pytorch
class AdaptiveRobustLoss(nn.Module):
"""
This class implements the adaptive robust loss function proposed by <NAME> for image tensors
"""
def __init__(self, device: str = 'cud... | [
"torch.mean",
"robust_loss_pytorch.AdaptiveLossFunction",
"torch.nn.L1Loss",
"torch.nn.functional.softplus",
"torch.tensor"
] | [((620, 732), 'robust_loss_pytorch.AdaptiveLossFunction', 'robust_loss_pytorch.AdaptiveLossFunction', ([], {'num_dims': 'num_of_dimension', 'device': 'device', 'float_dtype': 'torch.float'}), '(num_dims=num_of_dimension, device=\n device, float_dtype=torch.float)\n', (660, 732), False, 'import robust_loss_pytorch\n'... |
"""
Only needed to install the tool in editable mode. See:
https://setuptools.readthedocs.io/en/latest/userguide/quickstart.html#development-mode
"""
import setuptools
setuptools.setup()
| [
"setuptools.setup"
] | [((169, 187), 'setuptools.setup', 'setuptools.setup', ([], {}), '()\n', (185, 187), False, 'import setuptools\n')] |
from markdown.preprocessors import Preprocessor
import re
class CommentPreprocessor(Preprocessor):
''' Searches a Document for comments (e.g. {comment example text here})
and removes them from the document.
'''
def __init__(self, ext, *args, **kwargs):
'''
Args:
ext: An in... | [
"re.sub",
"re.compile"
] | [((469, 526), 're.compile', 're.compile', (["ext.processor_info[self.processor]['pattern']"], {}), "(ext.processor_info[self.processor]['pattern'])\n", (479, 526), False, 'import re\n'), ((1259, 1289), 're.sub', 're.sub', (['self.pattern', '""""""', 'line'], {}), "(self.pattern, '', line)\n", (1265, 1289), False, 'impo... |
# coding: utf-8
# In[1]:
get_ipython().run_cell_magic('javascript', '', '<!-- Ignore this block -->\nIPython.OutputArea.prototype._should_scroll = function(lines) {\n return false;\n}')
# ## Use housing data
# I have loaded the required modules. Pandas and Numpy. I have also included sqrt function from Math li... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"math.sqrt",
"pandas.read_csv",
"numpy.square",
"numpy.zeros",
"numpy.insert",
"numpy.hstack",
"numpy.array",
"numpy.dot",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.subplots"
] | [((722, 748), 'pandas.read_csv', 'pd.read_csv', (['inputFilepath'], {}), '(inputFilepath)\n', (733, 748), True, 'import pandas as pd\n'), ((5725, 5758), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(3)', '(2)'], {'sharey': '"""none"""'}), "(3, 2, sharey='none')\n", (5737, 5758), True, 'import matplotlib.pyplot as p... |
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url
from . import views
urlpatterns=[
url('^$',views.index,name='index'),
url(r'^new/post$',views.new_project, name='new-project'),
url(r'votes/$',views.vote_project, name='vote_project'),
url(r'^us... | [
"django.conf.urls.static.static",
"django.conf.urls.url"
] | [((148, 184), 'django.conf.urls.url', 'url', (['"""^$"""', 'views.index'], {'name': '"""index"""'}), "('^$', views.index, name='index')\n", (151, 184), False, 'from django.conf.urls import url\n'), ((188, 244), 'django.conf.urls.url', 'url', (['"""^new/post$"""', 'views.new_project'], {'name': '"""new-project"""'}), "(... |
"""Convexified Belief Propagation Class"""
import numpy as np
from .MatrixBeliefPropagator import MatrixBeliefPropagator, logsumexp, sparse_dot
class ConvexBeliefPropagator(MatrixBeliefPropagator):
"""
Class to perform convexified belief propagation based on counting numbers. The class allows for non-Bethe
... | [
"numpy.abs",
"numpy.nan_to_num",
"numpy.zeros",
"numpy.ones",
"numpy.hstack",
"numpy.exp"
] | [((1362, 1392), 'numpy.ones', 'np.ones', (['(2 * self.mn.num_edges)'], {}), '(2 * self.mn.num_edges)\n', (1369, 1392), True, 'import numpy as np\n'), ((2257, 2288), 'numpy.zeros', 'np.zeros', (['(2 * self.mn.num_edges)'], {}), '(2 * self.mn.num_edges)\n', (2265, 2288), True, 'import numpy as np\n'), ((4039, 4137), 'num... |
# general plotting functions
import matplotlib.pyplot as plt
# plot the given hourly profile
def hourly_profile(profile):
hourly_profile_building('SFH',profile)
hourly_profile_building('MFH',profile)
hourly_profile_building('COM',profile)
def hourly_profile_building(building,profile):
for(name,data) ... | [
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] | [((405, 449), 'matplotlib.pyplot.title', 'plt.title', (["('Hourly Profiles for ' + building)"], {}), "('Hourly Profiles for ' + building)\n", (414, 449), True, 'import matplotlib.pyplot as plt\n'), ((454, 483), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Hour of the day"""'], {}), "('Hour of the day')\n", (464, 483... |
#! /usr/bin/python3
# -*- coding: utf-8 -*-
from cuadrado import Cuadrado
def run():
cuad = Cuadrado(1,2,3)
print(cuad.show())
if __name__ == '__main__':
run()
| [
"cuadrado.Cuadrado"
] | [((97, 114), 'cuadrado.Cuadrado', 'Cuadrado', (['(1)', '(2)', '(3)'], {}), '(1, 2, 3)\n', (105, 114), False, 'from cuadrado import Cuadrado\n')] |
from __future__ import unicode_literals
from django.shortcuts import render
from datetime import date, timedelta
# django:
from django.views.generic import ListView, DetailView
from django.conf import settings
from django.shortcuts import get_object_or_404
from django.utils.dates import MONTHS_ALT
# thirdparties:
im... | [
"events.utils.common.clean_year_month_day",
"events.utils.common.get_qs",
"events.utils.common.get_now",
"events.utils.displays.day_display",
"events.utils.common.order_events",
"events.utils.common.get_net_category_tag",
"events.utils.displays.month_display",
"events.utils.common.get_next_and_prev",
... | [((1079, 1115), 'events.utils.common.get_net_category_tag', 'c.get_net_category_tag', (['self.request'], {}), '(self.request)\n', (1101, 1115), True, 'from events.utils import common as c\n'), ((1694, 1705), 'events.utils.common.get_now', 'c.get_now', ([], {}), '()\n', (1703, 1705), True, 'from events.utils import comm... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | [
"msrest.Serializer",
"azure.mgmt.core.AsyncARMPipelineClient",
"msrest.Deserializer"
] | [((3333, 3405), 'azure.mgmt.core.AsyncARMPipelineClient', 'AsyncARMPipelineClient', ([], {'base_url': 'base_url', 'config': 'self._config'}), '(base_url=base_url, config=self._config, **kwargs)\n', (3355, 3405), False, 'from azure.mgmt.core import AsyncARMPipelineClient\n'), ((3523, 3548), 'msrest.Serializer', 'Seriali... |