id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
4838261 | import requests
import os
import json
import frontmatter
import sys
def init(token):
headers = {'Authorization': 'Bearer {}'.format(token)}
r = requests.get('https://api.medium.com/v1/me', headers=headers)
try:
user_data = r.json()['data']
except KeyError:
print('error: invalid integrat... |
4838263 | from flask_wtf import FlaskForm
from wtforms import StringField,TextAreaField,SubmitField
from wtforms.validators import DataRequired
class chatbotform(FlaskForm):
user_input=StringField(validators=[DataRequired()])
send=SubmitField('Send')
|
4838265 | from django.apps import AppConfig
from django.core.checks import register, Tags
from django.utils.translation import gettext_lazy as _
class MaintenanceConfig(AppConfig):
name = 'geotrek.maintenance'
verbose_name = _("Maintenance")
def ready(self):
from .forms import InterventionForm, ProjectForm... |
4838272 | import os
import sys
import unittest
sys.path.insert(1, os.path.abspath('../..'))
from MiscUtils import StringIO
from WebUtils.HTMLTag import HTMLReader
class HTMLTagTest(unittest.TestCase):
def setUp(self):
self._html = """\
<html>
<head>
<title>Example</title>
</head>
<body lang="en">
<p>What... |
4838316 | import re
from botoy import GroupMsg, S
from botoy import async_decorators as deco
__doc__ = """把B站小程序转成链接"""
dont_Send_miniProgram_Base64PIC = r"""
<KEY>
UUUBRRRQFFFFAUUUUBRRRQFFFFAUUUUBRRRQFFFFAUUUUBRRRQFFFFAUUUUBRRRQFFFFAUUUUBRR
RQFFFFAUUUUH/9k=
"""
@deco.ignore_botself
@deco.these_msgtypes("XmlMsg")
async def ... |
4838317 | import os
import yaml
def read_yaml(path):
if not os.path.exists(path):
return {}
with open(path) as f:
return yaml.safe_load(f)
def write_yaml(path, payload):
folder, _ = os.path.split(path)
os.makedirs(folder, exist_ok=True)
with open(path, 'w') as f:
yaml.safe_dump(p... |
4838359 | import tensorflow as tf
x = [[1,2,3],[4,5,6]]
x = tf.convert_to_tensor(x)
xtrans = tf.transpose(x)
y=([[[1,2,3],[6,5,4]],[[4,5,6],[3,6,3]]])
y = tf.convert_to_tensor(y)
ytrans = tf.transpose(y, perm=[0, 2, 1])
with tf.Session() as sess:
print(sess.run(xtrans))
print(sess.run(ytrans)) |
4838367 | import numpy as np
from ...core.utils import as_id_array
from ...graph.structured_quad.structured_quad import StructuredQuadGraphTopology
from . import _neighbors_at_link
def neighbors_at_link(shape, links):
"""Get neighbor links.
Examples
--------
>>> import numpy as np
>>> from landlab.compone... |
4838368 | from typing import Generic
from pydantic.generics import GenericModel
from .pagination_types import PT
class PaginationOutput(GenericModel, Generic[PT]):
total: int
limit: int
offset: int
order: list[str]
data: list[PT]
|
4838372 | import colorsys
import cv2
import numpy as np
import os
import pickle
import logging
from PIL import Image
import pkg_resources
import pytesseract
import regex
from .simpleocr_utils.segmentation import segments_to_numpy
from .simpleocr_utils.feature_extraction import SimpleFeatureExtractor
TESSDATA_DIR = os.path.dirn... |
4838385 | class Solution:
def integerReplacement(self, n: 'int') -> 'int':
table = {1:0}
def dfs(n):
if n in table:
return table[n]
if n & 1:
result = 1 + min(dfs(n + 1), dfs(n - 1))
else:
result = 1 + dfs(n // 2)
... |
4838407 | import io
import pytest
from yoga.model import options
class Test_normalize_options(object):
def test_no_parameter_returns_default_options(self):
opt = options.normalize_options()
assert opt is not options.DEFAULT_OPTIONS
for k, v in options.DEFAULT_OPTIONS.items():
assert ... |
4838424 | from typing import List, Iterable, Sequence, Optional
from allennlp.common.registrable import Registrable
from allennlp.data.instance import Instance
class BatchSampler(Registrable):
def get_batch_indices(self, instances: Sequence[Instance]) -> Iterable[List[int]]:
raise NotImplementedError
def get_... |
4838433 | from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic.base import RedirectView
# from haystack.query import SearchQuerySet
from haystack.query import SearchQuerySet, EmptySearchQuerySet
from councilmatic_core.views import CouncilmaticSearchForm, CouncilmaticFacetedSearchVi... |
4838449 | import unittest
from pycoin.cmds.tx import DEFAULT_VERSION
from pycoin.encoding.hexbytes import h2b
from pycoin.symbols.btc import network
Spendable = network.tx.Spendable
Tx = network.tx
TxIn = network.tx.TxIn
TxOut = network.tx.TxOut
class SignTest(unittest.TestCase):
def test_sign_p2sh(self):
tx_ou... |
4838453 | import numpy as np
import pytest
from scipy import signal
from mixsea import helpers
def test_psd_output_dims():
"""Make sure output dimensions of psd work as expected."""
# generate input matrix
m = np.arange(0, 30)
M = m.size
n = np.linspace(0, 12 * np.pi, 1000)
N = n.size
g = np.tile(... |
4838477 | import torch
class RawFeatsStage(object):
def __init__(self):
pass
def eval(self):
return self
def encode(self, c):
"""fake vqmodel interface because self.cond_stage_model should have something
similar to coord.py but even more `dummy`"""
# assert 0.0 <= c.min() an... |
4838490 | from pprint import pformat
import re
import time
from collections import OrderedDict
import requests
from elifetools import utils as etoolsutils
REMOVE_TITLE_TAGS = ["b", "i", "sub", "sup"]
REMOVE_ABSTRACT_TAGS = ["a", "b", "i", "span", "sub", "sup"]
def substitute_math_tags(string, replacement="[Formula: see text]... |
4838504 | from captcha.image import ImageCaptcha #pip install captcha
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import random
#验证码中的字符
number = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
ALPHABET = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P',... |
4838560 | from __future__ import absolute_import
from __future__ import print_function
import os
import sys
from pyverilog.vparser.preprocessor import VerilogPreprocessor
codedir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + '/verilogcode/'
expected = """\
`default_nettype none
module led #
... |
4838614 | import time, os
import urllib.request
import os.path
import re
from glob import glob
import xml.etree.ElementTree as etree
from wheezy.template.engine import Engine
from wheezy.template.ext.core import CoreExtension
from wheezy.template.loader import FileLoader
#############################################... |
4838615 | from typing import Any
import cv2
import numpy as np
import torch
import torchvision
import yacs.config
from .types import GazeEstimationMethod
def create_transform(config: yacs.config.CfgNode) -> Any:
if config.mode == GazeEstimationMethod.MPIIGaze.name:
return _create_mpiigaze_transform(config)
el... |
4838617 | import re
from generators.common.Helper import Helper, AttributeKind
class PythonHelper(Helper):
@staticmethod
def add_required_import(required_import: set, import_type, class_name, base_class_name):
for typename in re.split('[\\[\\]]', import_type):
if typename:
if typen... |
4838633 | import unittest
import joerd.source.ned as ned
import joerd.source.ned_base as ned_base
import joerd.source.ned_topobathy as ned_topo
FAKE_OPTIONS = dict(
base_dir='',
ftp_server='',
base_path=''
)
class TestNEDSource(unittest.TestCase):
def test_zip_file_name_parsing_topo(self):
fname = 'n... |
4838673 | from sqlalchemy import Column, Integer, ForeignKey, Boolean, String
from sqlalchemy.orm import relationship
from .database import Base
from ..tools import db2array
from ..molior.configuration import Configuration
class Chroot(Base):
__tablename__ = "chroot"
id = Column(Integer, primary_key=True)
build_i... |
4838741 | import numpy as np
from .util import diagonal_dot, unitize, is_shape
from .points import point_plane_distance
from .constants import tol
def cross(triangles):
'''
Returns the cross product of two edges from input triangles
triangles: vertices of triangles (n,3,3)
returns: cross product of two edg... |
4838754 | def test_path(event):
assert event.path == "event:/Vehicles/Car Engine"
def test_create_instance(event):
inst = event.create_instance()
assert inst.is_valid
def test_parameter_description_count(event):
assert event.parameter_description_count == 8
def test_user_property_count(event):
assert event... |
4838768 | class Solution:
def shortestBridge(self, A: List[List[int]]) -> int:
m, n = len(A),len(A[0])
i,j = self.getFirst(A)
visited = set()
self.helper(A, i, j, visited)
res = float('inf')
lst = []
lst.extend(visited)
for (i, j) in lst:
... |
4838839 | from django.contrib import admin
from django.urls import path
from ninja import NinjaAPI
api = NinjaAPI()
@api.get("/add")
def add(request, a: int, b: int):
return {"result": a + b}
urlpatterns = [
path("admin/", admin.site.urls),
path("api/", api.urls),
]
|
4838856 | from . import DjediMiddleware
from .mixins import AdminPanelMixin
class DjediAdminMiddleware(DjediMiddleware, AdminPanelMixin):
def process_response(self, request, response):
self.inject_admin_panel(request, response)
return super(DjediAdminMiddleware, self).process_response(request, response)
|
4838857 | from argparse import ArgumentParser
import shutil
from tensorboard.backend.event_processing.event_file_inspector import get_inspection_units, print_dict, get_dict_to_print
"""
Deletes all folders with small tensorboard run files
"""
parser = ArgumentParser('delete small runs')
parser.add_argument('--logdir', type=str... |
4838864 | import numpy as np
from phonopy import Phonopy
from phonopy.structure.symmetry import Symmetry
from phonopy.structure.cells import (
get_supercell, get_primitive, guess_primitive_matrix)
from phonopy.harmonic.dynamical_matrix import DynamicalMatrix
from phonopy.units import VaspToTHz
from upho.phonon.band_structure... |
4838866 | import logging
import numpy as np
import scipy as sp
import collections
import torch
import functools
from numpy.lib.stride_tricks import as_strided
from sklearn.utils.extmath import randomized_svd
from sklearn.utils import check_random_state
logging.basicConfig()
def form_lag_matrix(X, T, stride=1, stride_tricks=... |
4838869 | from faster_rcnn import network
from faster_rcnn.faster_rcnn import FasterRCNN
from faster_rcnn.utils.timer import Timer
import os
import numpy as np
import cv2
def cut_det(data_dir, dest_dire, img_size=(256,256), dest_type='jpg'):
if not os.path.exists(dest_dir):
print('making new dir for converted imgs:... |
4838871 | import os
import pprint
import utils.files
import copy
import constants as c
from predictions.prediction import Prediction
class MegaEnsemblePrediction(Prediction):
"""
Prediction combining multiple experiments, models and epochs
"""
def __init__(self, name, pred_type, fpath, thresholds,
... |
4838884 | from setuptools import setup, find_packages
import platform
platform_install_requires = []
if platform.system() == 'Darwin':
platform_install_requires += ['pyobjc-framework-CoreBluetooth']
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# G... |
4838956 | from bg_atlasapi.structure_class import StructuresDict
from bg_atlasapi.utils import read_json
from bg_atlasapi import descriptors
import meshio as mio
import pytest
structures_list = [
{
"acronym": "root",
"id": 997,
"name": "root",
"structure_id_path": [997],
"rgb_triplet... |
4839023 | def base10toN(num,n):
"""Change a to a base-n number.
Up to base-36 is supported without special notation."""
num_rep={10:'a',
11:'b',
12:'c',
13:'d',
14:'e',
15:'f',
16:'g',
17:'h',
18:'i',
19:'j',
20:'k',
2... |
4839024 | import ast
import torch
class PolynomialLR(torch.optim.lr_scheduler._LRScheduler):
r"""Set the learning rate of each parameter group using a polynomial
schedule.
Args:
optimizer (Optimizer): Wrapped optimizer.
T_max (int): Maximum number of iterations.
eta_min (float): Minimum lear... |
4839087 | from django.conf.urls import url
from django.core.urlresolvers import reverse
from django.core.exceptions import PermissionDenied
from django.contrib.staticfiles import finders
from django.contrib.auth import get_permission_codename
from django.utils.functional import cached_property
from widgy import registry
from wi... |
4839098 | import src.c2oObject as Node
##-----------------------------BatchNormalization层 = BatchNorm + Scale-------------------------------------##
#获取超参数
def getBNAttri(layer):
#超参数字典
dict = {"epsilon": layer.batch_norm_param.eps, # 滑动系数
"momentum": layer.batch_norm_param.moving_average_fraction
... |
4839116 | import re
import os
from bsearch.plugins.base import Plugin
from bsearch.utils import base64decode
class UniqueCSP(Plugin):
CSP = 'Content-Security-Policy'
CSP_RE = re.compile('Content-Security-Policy: (.*?)\n')
NONCE_RE = re.compile("'nonce-(.*?)'")
TARGET = os.environ.get('TARGET', None)
def ... |
4839122 | from syft.message import SyftMessage
from syft.protos import SyftMessageProto
from syft.message.syft_message import SyftMessageProxy
import pickle
def test_message_creation() -> None:
any_object = set([1, 2, 3])
message = SyftMessage(
capability="message",
obj=any_object,
args=["a", ... |
4839152 | from .version import VERSION
from .base_handler import BaseHandler
from .oxygen import listener, OxygenLibrary
__all__ = ['BaseHandler', 'listener', 'OxygenLibrary']
__version__ = VERSION
|
4839201 | import uuid
import flask
import pjrpc.server
from pjrpc.server.integration import flask as integration
methods_v1 = pjrpc.server.MethodRegistry()
@methods_v1.add
def add_user_v1(user: dict):
user_id = uuid.uuid4().hex
flask.current_app.users[user_id] = user
return {'id': user_id, **user}
methods_v2... |
4839207 | import os
import argparse
import jsonlines
import json
import pickle
import matplotlib.pyplot as plt
import csv
from preprocessing.dpr_preprocessing import corpus_to_ctx_file
from eval.eval_bm25_coliee2021 import read_label_file
from preprocessing.coliee21_task2_bm25 import ranking_eval, eval_ranking_bm25
fro... |
4839228 | from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^api/$', 'sentiment.views.sentiment'),
)
|
4839232 | import logging
import requests
from django.conf import settings
from .base import BaseSmsClient
logger = logging.getLogger("notifier")
class CGSmsClient(BaseSmsClient):
@classmethod
def send(cls, number: str, text: str, **kwargs):
sub_account = settings.NOTIFIER["SMS"]["GATEWAYS"]["CGS"]["SUB_ACCO... |
4839233 | import torch
import torch.nn as nn
import rdkit.Chem as Chem
import torch.nn.functional as F
from hgraph.nnutils import *
from hgraph.encoder import IncHierMPNEncoder
from hgraph.mol_graph import MolGraph
from hgraph.inc_graph import IncTree, IncGraph
class HTuple():
def __init__(self, node=None, mess=None, vmask=... |
4839293 | from .chord import Chord, BassChord, UkuleleChord
from .fretboard import Fretboard
__version__ = '1.0.0'
__author__ = '<NAME> <<EMAIL>>'
__license__ = 'MIT'
|
4839326 | import os
import pytest
from . import run
from .conditions import has_http
def test_unit(cmake, unittest):
cwd = cmake(
["sentry_test_unit"], {"SENTRY_BACKEND": "none", "SENTRY_TRANSPORT": "none"}
)
env = dict(os.environ)
run(cwd, "sentry_test_unit", ["--no-summary", unittest], check=True, env... |
4839353 | from unittest import TestCase
from collective.solr.parser import SolrFlare
from collective.solr.flare import PloneFlare
class FlareTests(TestCase):
def testRelevanceFormatting(self):
def score(**kw):
return PloneFlare(SolrFlare(**kw)).data_record_normalized_score_
self.assertEqual(sc... |
4839368 | import itertools
import json
from itertools import product
import networkx as nx
import pandas as pd
from networkx.algorithms.dag import topological_sort
from pybbn.graph.dag import Bbn
from pybbn.graph.edge import Edge, EdgeType
from pybbn.graph.node import BbnNode
from pybbn.graph.variable import Variable
class F... |
4839402 | import numpy as np
from qtrader.utils.numpy import eps
def _mu_p(w: np.ndarray, r: np.ndarray) -> float:
"""Portfolio Returns."""
return np.dot(w.T, r)
def _sigma_p(w: np.ndarray, Sigma: np.ndarray) -> float:
"""Portoflio Variance"""
return np.dot(np.dot(w.T, Sigma), w)
def _trans_costs(w: np.nda... |
4839426 | import torch
from sklearn.feature_extraction.text import CountVectorizer
def squash(value):
if not torch.is_tensor(value):
raise ValueError(f"unexpected `value` of type {value.__class__}")
if value.ndim == 2:
return value
return value.mean(dim=1)
def get_all_candidates(text, n_gram_range... |
4839482 | import logging
import re
import urllib.parse
from datetime import datetime
from datetime import timedelta
from datetime import timezone
from typing import Any
from typing import Dict
from typing import Optional
import dateutil.parser
import requests
from bs4 import BeautifulSoup
from nefelibata.assistants import Assi... |
4839512 | from uuid import UUID, uuid4
import pytest
from rest_framework.test import APIRequestFactory
@pytest.fixture
def article_id() -> UUID:
return uuid4()
@pytest.fixture
def user_id() -> UUID:
return uuid4()
@pytest.fixture
def article_vote_id() -> UUID:
return uuid4()
@pytest.fixture
def arf():
re... |
4839513 | from gui.tools import HeightSlideTextInput
from kivy.app import App
from kivy.factory import Factory
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen
Builder.load_file(r"gui\level.kv")
class LevelScreen(Screen):
def __init__(self, **kwargs):
self.util = App.get_running_app().util
... |
4839528 | import os
import pathlib
from dotenv import load_dotenv
load_dotenv()
class BaseConfig(object):
"""Base Configuration"""
DEBUG = False
CSRF_ENABLED = True
SECRET = os.getenv("SECRET")
SQLALCHEMY_DATABASE_URI = os.getenv("DATABASE_URL")
class DevelopmentConfig(BaseConfig):
"""Development C... |
4839541 | import Mykytea
mk = Mykytea.Mykytea("")
def tokenize(text):
"""
A method for word segmentation.
Parameters
----------
text : str
An input text
Returns
-------
words : list
A list of words
"""
words = [word for word in mk.getWS(text)]
return words
def o... |
4839546 | import datetime as _datetime
from flask import url_for
from bleach import clean
from markdown import markdown
from werkzeug.utils import escape
import cache
from model.PostReplyExtension import PostReplyExtension
from model.SpacingExtension import SpacingExtension
from model.Spoiler import SpoilerExtension
from model... |
4839550 | import os
import sys
import logging
import tempfile
import subprocess
from farnsworth.models import ChallengeSetFielding, IDSRuleFielding, Exploit, PovFuzzer1Job, PovTestResult
import pov_fuzzing
import compilerex
logging.basicConfig()
l = logging.getLogger("main_type1")
l.setLevel("INFO")
# make compilerex executa... |
4839571 | import logging
from plugin import Plugin
from utils import rich_response
log = logging.getLogger('discord')
class Commands(Plugin):
fancy_name = 'Custom Commands'
async def get_commands(self, server):
storage = await self.get_storage(server)
commands = sorted(await storage.smembers('comma... |
4839586 | def get_parameter_count(network):
"""
Calculate the number of parameters used by the fully connected network.
Hint: Casting the result of network.parameters() to a list may make it
easier to work with
Args:
network: Network to calculate the parameters of
Returns:
param_count: The number ... |
4839600 | from gitlab import cli
from gitlab import exceptions as exc
from gitlab.base import RESTManager
__all__ = [
"SidekiqManager",
]
class SidekiqManager(RESTManager):
"""Manager for the Sidekiq methods.
This manager doesn't actually manage objects but provides helper fonction
for the sidekiq metrics API... |
4839614 | t = int(input())
while t:
N = int(input())
L = list(map(int,input().split()))
D = dict()
for i in range(N):
if L[i] not in D:
D[L[i]]=1
else:
D[L[i]]+=1
arr = list(D.keys())
c = 0
for key,value in D.items():
if value>1:
... |
4839620 | import os
import pickle
import random
from config import dev_wav_folder, data_file
def get_data():
print('getting data...')
dirs = [d for d in os.listdir(dev_wav_folder) if d.startswith('id')]
samples = []
for id in dirs:
label = build_dict(id)
folder = os.path.join(dev_wav_folder,... |
4839644 | from client_stub import ClientStub
def main():
stub = ClientStub(("192.168.36.123", 50051))
result = stub.get("sum", (1, 2))
print(f"1+2={result}")
result = stub.get("sum", (1.1, 2))
print(f"1.1+2={result}")
time_str = stub.get("get_time")
print(time_str)
if __name__ == "__main__":
... |
4839675 | import random
from src.tipboard.app.properties import COLOR_TAB
# Datasets is always an arrays with the always the same possible value for different chart
# Every dataset is a dict, go to chartJS documentation to see the possibility
# "datasets": [
# {
# "label": "Series 1",
# "fill": true,
# ... |
4839686 | from rest_framework import serializers
from rest_framework.reverse import reverse
from server.models import Calendar
class CalendarListSerializer(serializers.ModelSerializer):
id = serializers.PrimaryKeyRelatedField(source='pk', read_only=True)
year = serializers.SerializerMethodField()
url = serializer... |
4839695 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDHarvester import DQMEDHarvester
from DQMOffline.Trigger.SiPixel_OfflineMonitoring_HistogramManager_cfi import *
# order is important and it should follow ordering in hltSiPixelPhase1ClustersConf VPSet
hltSiPixelPhase1ClustersCharge = hltDefaultHistoD... |
4839724 | from typing import Type, Dict, List
from pathlib import Path
from .abc import DataContainer, DataContainerHolder
from .enums import Resource
from .miscmodels import TimeDelta
SPELLS_FILE_PATH = Path(__file__).parent.joinpath(Path("static/spells.json"))
class Spell(DataContainer):
"""Represents a Spell object a... |
4839805 | import datetime
import unittest
from zoomus import components, util
import responses
def suite():
"""Define all the tests of the module."""
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(GetUserReportV1TestCase))
suite.addTest(unittest.makeSuite(GetUserReportV2TestCase))
return sui... |
4839822 | from pathlib import Path
import pandas
import numpy
def _febrl_load_data(filename):
# Internal function for loading febrl data
filepath = Path(
Path(__file__).parent,
'febrl',
filename
)
febrl_data = pandas.read_csv(filepath,
index_col="rec_... |
4839841 | import argparse
import typing
import aztk
from aztk_cli import config, log
def setup_parser(parser: argparse.ArgumentParser):
parser.add_argument(
"--id", dest="cluster_ids", nargs="*", required=True, help="The unique id of your spark cluster")
parser.add_argument(
"--force",
"-f",
... |
4839842 | import os
from subprocess import check_output
import sys
sys.path.insert(0, os.path.abspath('../src'))
sys.path.insert(0, os.path.abspath('.'))
# Fake imports to avoid actually loading CFFI and C extension modules
import fake_sounddevice
sys.modules['sounddevice'] = sys.modules['fake_sounddevice']
import fake_rtmixer... |
4839855 | import time
import msgpack
import operator
from bw2python.client import Client
from xbos.services.hod import HodClient
from xbos.devices.thermostat import Thermostat
from xbos.devices.plug import Plug
from xbos.devices.meter import Meter
from xbos.devices.evse import EVSE
_BASEBOARD_HEATER_CONSUMPTION = 1100 #W
_MAX_E... |
4839857 | from pathlib import Path
from frost import FrostServer
from server.scores import Scores
class Server(FrostServer):
def __init__(self, file: str) -> None:
db = Path('pyfrost.sqlite3')
if not db.exists():
from server.utils import init_db
init_db()
# Load up our co... |
4839872 | expected_output = {
"RM-NAM-IBGP-OUT": {
"statements": {
"10": {
"actions": {
"set_next_hop_self": False,
"route_disposition": "permit",
"set_local_pref": 700,
"set_community": "1:1"
},
"conditions": {},
"policy_routing_matches": { "pac... |
4839934 | import numbers
from scipy.stats import mode
import pandas as pd
import numpy as np
import datetime
from mlapp.utils.exceptions.framework_exceptions import UnsupportedFileType
class ClassificationFeatureEngineering(object):
def drop_features(self, data_df, features_to_drop=None):
"""
Dropping requ... |
4839935 | from django.test import TestCase
# from rodan.models.workflowjob import WorkflowJob
# from rodan.models.inputporttype import InputPortType
from rodan.models.inputport import InputPort
from model_mommy import mommy
from rodan.test.helpers import RodanTestTearDownMixin, RodanTestSetUpMixin
class InputPortTestCase(Rodan... |
4839952 | from rest_framework import status
from rest_framework.response import Response
from mayan.apps.documents.permissions import permission_document_create
from mayan.apps.rest_api import generics
from .models import Source
from .permissions import (
permission_sources_create, permission_sources_delete,
permission... |
4839981 | from __future__ import annotations
from torch import nn
from ..resnet import ResNetBasicBlock, ResNetBottleneckBlock, ResNet
from glasses.nn.att import SpatialSE, ChannelSE, WithAtt
from glasses.utils.weights.PretrainedWeightsProvider import pretrained
SENetBasicBlock = WithAtt(ResNetBasicBlock, att=SpatialSE)
SENetBo... |
4839988 | from .arq import ARQ, Arq, GenericApiError, InvalidApiKey
__all__ = ["Arq", "ARQ", "InvalidApiKey", "GenericApiError"]
|
4840057 | from ml4ir.base.model.scoring.scoring_base import ScoringBase
class PairwiseScoring(ScoringBase):
def get_scoring_fn(self, **kwargs):
"""
Define a pointwise ranking scoring function with specified architecture
"""
def _scoring_fn(features):
raise NotImplementedError
... |
4840078 | from .pointer import Pointer
from typing import TypeVar, NoReturn
from .exceptions import IsFrozenError
import gc
__all__ = ("FrozenPointer", "to_const_ptr")
T = TypeVar("T")
class FrozenPointer(Pointer[T]):
def assign(self, _: Pointer[T]) -> NoReturn:
"""Point to a different address."""
... |
4840146 | import os
import sys
from collections import namedtuple
import numpy as np
import pandas as pd
from keras_xlnet.backend import keras
from keras_bert.layers import Extract
from keras_xlnet import Tokenizer, load_trained_model_from_checkpoint, ATTENTION_TYPE_BI
from keras_radam import RAdam
EPOCH = 10
BATCH_SIZE = 4
S... |
4840171 | import torch
import numpy as np
import dgl
import os
import math
import pickle
import json
import copy
import torch.utils.data as data
from collections import defaultdict, Counter
from tqdm import tqdm
from utils import get_enc_len, int2onehot, \
batch_convert_tensor_to_tensor, batch_convert_array_to_array
INF = f... |
4840195 | from dynamic_programming.car_rentals import JacksCarRental
import argparse
parser = argparse.ArgumentParser(description="Car Rental Exercise")
parser.add_argument('--convergence',
type=float,
help='Convergence criteria for policy evaluation',
default=1.0)
ar... |
4840213 | import os,ldap,pickle
temp_file_name = os.path.join(os.environ.get('TMP','/tmp'),'pickle_ldap-%d' % (os.getpid()))
l1 = ldap.ldapobject.ReconnectLDAPObject('ldap://localhost:1390',trace_level=1)
l1.protocol_version = 3
l1.search_s('',ldap.SCOPE_BASE,'(objectClass=*)')
pickle.dump(l1,open(temp_file_name,'wb'))
l2 = ... |
4840217 | import os
import time
import datetime
# The sum of elements in celeba test data recognition & not recognition ≠ the number of celeba test data.
# So I code this to detect repeat elements.
# a:celeba test data; b:recognition; c:not recognition
# There are 5 cases:
# 1.in b+c not in a
# 2.in a not in b+c
# 3.in b and in... |
4840231 | import sys
from logger import logger
import config
def get_stream_direction():
source = get_current_source()
if source is None:
return None
if source["source"].isdigit():
return "outgoing"
return "incoming"
def set_source(source: dict):
logger.debug("Setting new video source")
... |
4840236 | import numpy as np
from numpy.polynomial import Chebyshev as Ch
from scipy.linalg import cho_factor, cho_solve
from scipy.optimize import minimize
import psoap
from psoap import constants as C
from psoap import matrix_functions
from psoap.data import lredshift
try:
import celerite
from celerite import terms
... |
4840315 | import json
import numpy as np
import matplotlib.pyplot as plt
from scipy.io.wavfile import write
# Synthesize the tone based on the input parameters
def tone_synthesizer(freq, duration, amplitude=1.0, sampling_freq=44100):
# Construct the time axis
time_axis = np.linspace(0, duration, duration * sampling_fr... |
4840327 | import os
from urllib.parse import urlparse, urlunparse
def fix_assets_path(path):
fullpath = os.path.join(os.path.dirname(__file__), "../", path)
return fullpath
def array_from_string(s):
array = s.split(",")
if "" in array:
array.remove("")
return array
def set_from_string(s):
r... |
4840335 | import numpy as np
def better(old_value, new_value, mode):
""" Check if new value is better than the old value"""
if (old_value is None or np.isnan(old_value)) and (new_value is not None and not np.isnan(new_value)):
return True
if mode == 'min':
return new_value < old_value
elif mode... |
4840347 | import argparse
import eosfactory.core.teos as teos
def build(
contract_dir_hint,
c_cpp_properties_path="",
compile_only=False, is_test_options=False, is_execute=False, silent=False):
verbosity=[] if silent else None
teos.build(
contract_dir_hint, c_cpp_propert... |
4840361 | import pickle
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/')
def index():
return "Hello, World!"
@app.route('/predict')
# http://127.0.0.1:5000/predict?text=technology
def predict():
text = request.args.get('text', type = str)
print 'Pred... |
4840384 | from GLOBAL_VAR import *
from METHOD_VAR import *
from scipy.stats import fisher_exact
from scipy.stats import chi2_contingency
from statsmodels.stats import multitest
def one_factorActive(outlier_snps, in_tissues, sub_feature = None):
outlier_snps_ts = np.array(outlier_snps[in_tissues])
if ',' in ... |
4840426 | from pybbn.graph.dag import Bbn
from pybbn.graph.edge import EdgeType, Edge
from pybbn.graph.node import BbnNode
from pybbn.graph.variable import Variable
from pybbn.pptc.inferencecontroller import InferenceController
# you have built a BBN
a = BbnNode(Variable(0, 'a', ['t', 'f']), [0.2, 0.8])
b = BbnNode(Variable(1, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.