text stringlengths 2 999k |
|---|
# coding: utf-8
from flask import url_for, current_app
from flask_babelex import lazy_gettext as __
from .base import BaseTestCase
from . import utils
class MenuTestCase(BaseTestCase):
# Collection Menu
def test_alpha_link_is_selected_for_list_alpha(self):
"""
Verficamos que o link do menú... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2006-2018, Alexis Royer, http://alexis.royer.free.fr/CLI
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# * Redistrib... |
if __name__ == '__main__':
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
def call():
return 1
call()
# Check that we're not setting return values here.
assert '__pydevd_ret_val_dict' not in sys._getframe().f_locals
try:
import enum
... |
#!/usr/bin/python
#
# Copyright 2019 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
# Copyright 2021 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, ... |
#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "Li... |
import sys, os
from pyprojroot import here
import logging
import pathlib
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
logger = logging.getLogger()
PATH = pathlib.Path(str(here()))
# root = here(project_files=[".here"])
sys.path.append(str(here()))
import argparse
import numpy as np
# drought tools
fr... |
"""
Helioviewer Client tests
"""
from __future__ import absolute_import
#pylint: disable=C0103,R0904,W0201,W0212,W0232,E1103
import sunpy
from sunpy.net.helioviewer import HelioviewerClient
class TestHelioviewerClient:
"""Tests the Helioviewer.org API Client class"""
def setup_class(self):
self.client... |
from miniworldmaker.boards import pixel_board
from miniworldmaker.connectors import physics_connector
class PhysicsBoard(pixel_board.PixelBoard):
def add_to_board(self, token, position):
"""
Adds a token to the board.
The method is called with __init__ method of the token
Args:
... |
# -*- coding: utf-8 -*-
"""
/dms/linklist/views_edit.py
.. enthaelt den View zurm Aendern der Eigenschaften der Linkliste
Django content Management System
Hans Rauch
hans.rauch@gmx.net
Die Programme des dms-Systems koennen frei genutzt und den spezifischen
Beduerfnissen entsprechend angepasst werden.
0.01 ... |
print('Calcule os 10 primeiros termos de um PA!')
pt = int(input('Digite o primeiro termo: '))
razao = int(input('Digite a razão: '))
prox = pt
c = 1
while c <= 10:
print(prox, "→", end=' ')
prox = pt + razao
pt = prox
c += 1
print('Acabou!')
|
import os
from gym import spaces
import numpy as np
import pybullet as p
from .scratch_itch import ScratchItchEnv
class ScratchItchMeshEnv(ScratchItchEnv):
def __init__(self, robot, human):
super(ScratchItchMeshEnv, self).__init__(robot=robot, human=human)
self.general_model = True
# Param... |
"""Config flow for TP-Link."""
import logging
import re
from pycountry import countries as py_countries, languages as py_languages
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.core import callback
from homeassistant.const import CONF_REGION, CONF_TOKEN, __version__
from .const... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from Icosahedron_net import IcosahedronNet
### Settings for your paper globe ###
stars_directory = '.' # (relative) path from this script to the stars.dat file
filename = 'paper_globe.pdf' # filename for your paper globe
scale = 1.5 # ove... |
import sys
import sly_globals as g
import train_config
def init_script_arguments(state):
sys.argv.append(train_config.main_config_path)
#sys.argv.append(os.path.join(g.root_source_dir, "configs/resnet/resnet18_b16x8_cifar10.py"))
sys.argv.extend(["--work-dir", g.checkpoints_dir])
#sys.argv.extend(["-... |
from django import template
from sitio.models import sitio_personalizacion
register = template.Library()
@register.simple_tag(name='personalizacion')
def personalizacion(opcion):
try:
obj = sitio_personalizacion.objects.filter(id=1).values()[0]
result = obj[opcion]
except Exception as e:
... |
import numpy as np
import biorbd
from biorbd_optim import (
Instant,
OptimalControlProgram,
ConstraintList,
Constraint,
ObjectiveList,
Objective,
DynamicsTypeList,
DynamicsType,
BoundsList,
QAndQDotBounds,
InitialConditionsList,
ShowResult,
StateTransitionList,
)
d... |
"""
API for updating Galaxy Pages
"""
import logging
from galaxy.exceptions import RequestParameterInvalidException
from galaxy.managers.base import get_object
from galaxy.managers.markdown_util import internal_galaxy_markdown_to_pdf
from galaxy.managers.pages import (
PageManager,
PageSerializer
)
from galaxy... |
# coding=utf-8
# author: al0ne
# https://github.com/al0ne
import requests
import re
from lib.random_header import get_ua
from lxml import etree
import concurrent.futures
from lib.settings import TIMEOUT
class JsParse():
def __init__(self, host):
self.host = host
self.result = []
def jsparse(... |
"""PRAW Integration test suite."""
import inspect
import logging
import pytest
import requests
from betamax import Betamax
from praw import Reddit
class IntegrationTest:
"""Base class for PRAW integration tests."""
logger = logging.getLogger(__name__)
def setup(self):
"""Setup runs before all ... |
from rest_framework import serializers
from core.models import Tag, Ingredient, Recipe
class TagSerializer(serializers.ModelSerializer):
"""serializer for tag object"""
class Meta:
model = Tag
fields = ('id', 'name')
read_only_fields = ('id',)
class IngredientSerializer(serializers... |
#!/usr/bin/python3
import re, logging, time, threading
from serial_comm import SerialComm
class PiTalk(SerialComm):
""" Class for pitalk modem interaction """
# parsing AT command errors
CM_ERROR_REGEX = re.compile(r'^\+(CM[ES]) ERROR: (\d+)$')
# parsing signal strength query response\
CSQ_REGEX... |
class Person:
def __init__(self,name):
self.name = name
def hi(self):
print("Hi %s" % self.name)
p = Person("Hussain")
d = Person("Jack")
print(p)
print(d)
p.hi()
|
# Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
import config_util # pylint: disable=import-error
# This class doesn't need an __init__ method, so we disable the warning
# pylint: disable=no... |
"""Auto-generated file, do not edit by hand. IQ metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_IQ = PhoneMetadata(id='IQ', country_code=964, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='[1-7]\\d{7,9}', possible_number_pattern=... |
import numpy as np
import laspy
def test_mmap(mmapped_file_path):
with laspy.mmap(mmapped_file_path) as las:
las.classification[:] = 25
assert np.all(las.classification == 25)
las = laspy.read(mmapped_file_path)
assert np.all(las.classification == 25)
|
'''
@author: Mahbub Ul Alam (alammb@ims.uni-stuttgart.de)
@date: 21.09.2017
@version: 1.0+
@copyright: Copyright (c) 2017-2018, Mahbub Ul Alam (alammb@ims.uni-stuttgart.de)
@license : MIT License
'''
import tensorflow as tf
import numpy as np
from neural_network import seq_convertors
import analyze_relevance
import p... |
# This file is where you keep secret settings, passwords, and tokens!
# If you put them in the code you risk committing that info or sharing it
settings = {
'ssid' : 'my access point',
'password' : 'my password',
'timezone' : -5, # this is offset from UTC
'github_token' : 'abcdefghij0123456789',
'a... |
#!/usr/bin/env python
''' Script to do very basic conversion of TRAC to reST format '''
import sys
import re
rst_section_levels = ['*', '=', '-', '~', '^']
heading_re = re.compile('^(=+) +([^=]+) +(=+)')
enumerate_re = re.compile(r'^ +(\d+\)) +(.*)')
link_re = re.compile(r'\[+ *(http://[\w.\-~/]+) +(.+?) *\]+')
itali... |
from telegram import Bot, Update
from src.gorrion import Gorrion
from src.config import Config
from src.clients.spotify import Spotify, SpotifyApiError
from src.clients.twitter import Twitter, TwitterLocal
from src.clients.musixmatch import Musixmatch
class TelegramBot:
def __init__(self) -> None:
self._... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.5.3
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
im... |
# --------------------------------------------------------------------------------------
# Copyright (c) 2018-2021, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# --------------------------------------... |
from functions import updateDb, insertDb
updateDb()
|
"""Controllers for echo module."""
from src.protocol import make_response
from src.database import session_scope
from src.decorators import logged
from .models import Message
@logged
def echo_controller(request):
"""Make echo response based on request data."""
data = request.get('data')
with session_scop... |
import datetime
from io import StringIO
import itertools
from itertools import product
from warnings import catch_warnings, simplefilter
import numpy as np
from numpy.random import randn
import pytest
import pytz
from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype
import pandas as pd
from pandas i... |
# -*- coding: utf-8 -*-
"""
Copyright (c) 2021 Colin Curtain
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, mer... |
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json
import time
from pymongo import MongoClient
from SentimentAnalysis import SentimentAnalysis
from DataLake import Mongo
# User credentials to access Twitter API
consumer_key = ''
consumer_secret = ''
access... |
import numpy as np
from numpy.testing import assert_equal
from .common import get_test_dataset
def test_flash_id_sanity():
glm, flash_ids = get_test_dataset()
# Make sure the flash IDs returned are the same as the flash IDs requested
fls = glm.get_flashes(flash_ids)
assert_equal(flash_ids, f... |
"""
ASGI config for DjangoSampleProject project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('... |
from seldon_e2e_utils import (
wait_for_status,
wait_for_rollout,
retry_run,
to_resources_path,
initial_rest_request,
)
def test_xss_escaping(namespace):
sdep_name = "mymodel"
sdep_path = to_resources_path("graph-echo.json")
retry_run(f"kubectl apply -f {sdep_path} -n {namespace}")
... |
from typing import Any
import aiosqlite
from fibo.util.byte_types import hexstr_to_bytes
from fibo.util.db_wrapper import DBWrapper
from fibo.util.streamable import Streamable
class KeyValStore:
"""
Multipurpose persistent key-value store
"""
db_connection: aiosqlite.Connection
db_wrapper: DBWr... |
# Copyright (c) 2021, NVIDIA CORPORATION. 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 required by applic... |
# -----------------------------------------------------------------------------
# Copyright (C) Jupyter Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
# ------------------------------------------------------------... |
# coding: utf-8
"""
Consolidate Services
Description of all APIs # noqa: E501
The version of the OpenAPI document: version not set
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import datetime
import argocd_client
from argocd_client.model... |
from __future__ import annotations
from typing import Union
from scipy.signal import firwin
from nptyping import Array
import numpy as np
from modules.audio.settings import CHANNELS, FRAME_RATE
from modules.modulator.constants import AM, AM_SC, NO_MOD
from modules.modulator.error import (InvalidModulationTypeErr... |
from .constants import (APPLICATION_ERROR, UNAUTHORIZED, NOT_FOUND, BAD_REQUEST,
FORBIDDEN, NOT_ACCEPTABLE, GONE, PRECONDITION_FAILED,
CONFLICT, UNSUPPORTED_MEDIA_TYPE, EXPECTATION_FAILED,
I_AM_A_TEAPOT, TOO_MANY_REQUESTS, UNPROCESSABLE_ENTITY,
... |
# Copyright (c) 2015 Arista Networks, Inc. All rights reserved.
# Arista Networks, Inc. Confidential and Proprietary.
#!/usr/bin/python
#Python Module Imports
import pexpect #SSH library with expect support
import sys
import os
import time
import string
import argparse
import socket
import subprocess
from random imp... |
from .client import port_manager |
# Copyright 2016 The TensorFlow Authors. 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 required by... |
def f(x):
return x**x
def right(a,b,n):
h = abs(b-a)/n
S = 0
while fabs(a-b)>0.0001:
a += h
S += f(a)
return S*h
def left(a,b,n):
h = abs(b-a)/n
S = 0
while fabs(a-b)>0.0001:
S += f(a)
a += h
return S*h
def centr(a,b,n):
h = ... |
"""Added hash column to uploads table
Revision ID: 591022583d54
Revises: 50d1a487c7ab
Create Date: 2016-05-04 20:02:24.955367
"""
# revision identifiers, used by Alembic.
revision = '591022583d54'
down_revision = '50d1a487c7ab'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto ge... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilitie... |
""" from https://github.com/keithito/tacotron """
import re
from . import cleaners
from .symbols import symbols
# Mappings from symbol to numeric ID and vice versa:
_symbol_to_id = {s: i for i, s in enumerate(symbols)}
_id_to_symbol = {i: s for i, s in enumerate(symbols)}
# Regular expression matching text enclosed ... |
""" Module for taking data using arbitrary experiment scripts
and Dataset objects """
import os
import sys
import importlib
import time
from datetime import datetime
import numpy as np
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtCore import Qt
from pylabnet.utils.logging.logger import LogHandler
from ... |
# 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 ... |
from __future__ import absolute_import
import six
from sentry.api.serializers import Serializer, register
from sentry.models import ReleaseFile
@register(ReleaseFile)
class ReleaseFileSerializer(Serializer):
def serialize(self, obj, attrs, user):
return {
'id': six.text_type(obj.id),
... |
# Ultroid - UserBot
# Copyright (C) 2020 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
"""
✘ Commands Available -
• `{i}ftyping <time/in secs>`
`Show Fake ... |
from typing import Iterable, Dict, List
import torch
from einops import rearrange, repeat
from torch import Tensor
from torch import nn
from torch.nn import Identity
from perceiver_pytorch.caching import cache_by_name_fn
from perceiver_pytorch.modalities import InputModality, modality_encoding
from perceiver_pytorch.... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Ver... |
"""
Copyright 2021 Andrey Plugin (9keepa@gmail.com)
Licensed under the Apache License v2.0
http://www.apache.org/licenses/LICENSE-2.0
"""
from tool import log as _log
log = _log("MAIN")
log.info("This logger for main script") |
from donerkebab import ChromeDriver
# Get an instance of the browser window
driver = ChromeDriver()
driver.open('https://duckduckgo.com/')
# Browser will wait at max 10 seconds until element is found
driver.set_timeout(10)
# You can find elements by their CSS selectors
input_box = driver.get_element('input#search_f... |
import datetime
import logging
import os
import socket
import threading
from galaxy.model import WorkerProcess
from galaxy.model.orm.now import now
log = logging.getLogger(__name__)
class DatabaseHeartbeat:
def __init__(self, application_stack, heartbeat_interval=60):
self.application_stack = applicati... |
"""
WSGI config for tstdanieldjart_dev_22880 project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefa... |
from src.models import Sensor
class Writer(object):
def __init__(self, **sensor_data):
self.sensor_data = sensor_data
def validation(self):
pass
def save(self):
return Sensor.create(temperature=self.sensor_data["temperature"],
humidity=self.sensor_da... |
#!/usr/bin/env python
# coding: utf-8
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
import networkx as nx
import utils
def solve(image, lambd):
"""
region fusion for piecewise regression
"""
# build graph with affine parameters
... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gui.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, Q... |
# use constants in class, so they don't need to be separately accessed
# use constants for string options
# constants for option names (value is the ini entry name)
# general
LAST_CONFIG_FILE = "last_config_file"
DISPLAY_APP_VERSIONS = "disp_app_versions"
DISPLAY_APP_CHANNELS = "disp_app_channels"
# import at the ... |
import Pyro4
uri = input("What is the Pyro uri of the greeting object? ").strip()
name = input("What is your name? ").strip()
greeting_maker = Pyro4.Proxy(uri) # get a Pyro proxy to the greeting object
print(greeting_maker.get_fortune(name)) # call method normally |
###########################
#
# #386 Maximum length of an antichain - Project Euler
# https://projecteuler.net/problem=386
#
# Code by Kevin Marciniak
#
###########################
|
'''define the config file for voc and resnet101os16'''
import os
from .base_cfg import *
# modify dataset config
DATASET_CFG = DATASET_CFG.copy()
DATASET_CFG.update({
'type': 'voc',
'rootdir': os.path.join(os.getcwd(), 'VOCdevkit/VOC2012'),
})
DATASET_CFG['train']['set'] = 'trainaug'
# modify dataloader confi... |
from __future__ import absolute_import
import logging
import re
import urllib
import feedparser
from flexget import plugin
from flexget.entry import Entry
from flexget.event import event
from flexget.utils.search import normalize_unicode
log = logging.getLogger('extratorrent')
REGEXP = re.compile(r'https?://extrator... |
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("keys", "0002_auto_20150710_2133")]
operations = [
migrations.AlterUniqueTogether(
name="key", unique_together={("user", "password")}
)
]
|
class Room:
def __init__(self, number, capacity):
self.number = number
self.capacity = capacity
self.guests = 0
self.is_taken = False
def take_room(self, people):
if not self.is_taken and self.capacity >= people:
self.is_taken = True
self.guests +... |
# training and testing settings
train_cfg = dict(
assigner=dict(
type='GridAssigner', pos_iou_thr=0.5, neg_iou_thr=0.5, min_pos_iou=0))
test_cfg = dict(
nms_pre=1000,
min_bbox_size=0,
score_thr=0.05,
conf_thr=0.005,
nms=dict(type='nms', iou_threshold=0.45),
max_per_img=100)
|
import unittest
from flask_socketio import SocketIOTestClient
from config.loader import neo_config
from api import NeoAPI, socketio, sockets
from config.database import db
from utils.testutils import authenticate_user
from utils.testutils import authenticate_device
from models.User import User as UserModel
from... |
from setuptools import setup, find_packages
requirements = [
"numpy",
"pandas",
"edict",
"elist",
"tlist"
]
setup(
name="dtable",
version = "0.0.5", #@version@#
description="handle,.in progressing..,APIs",
author="ihgazni2",
url="https://github.com/ihgazni2/dtable",
... |
#!/usr/bin/env python
"""
A very simple progress bar where the name of the task scrolls, because it's too long.
iterator.
"""
from __future__ import unicode_literals
from prompt_toolkit.shortcuts.progress_bar import progress_bar
import time
def main():
with progress_bar(title='Scrolling task name (make sure the w... |
import numpy as np
import tensorflow as tf
import os
import sys
def fatal_error(message):
tf.logging.log(tf.logging.ERROR, message)
sys.exit(1)
def init_logging(verbosity):
tf.logging.set_verbosity(verbosity)
tf.logging.log(tf.logging.INFO, "Using Python version %s" % sys.version)
tf.logging.log(tf.loggin... |
import os
import sys
sys.path.append(os.getcwd())
import torch
from torch import nn
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class GRUEncode... |
#!/usr/bin/env python
# Copyright 2016, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this fi... |
# Copyright 2021 The KubeEdge Authors.
#
# 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... |
# Copyright 2016 The TensorFlow Authors. 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 required by applica... |
# 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 ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
class Form(models.Model):
def getforms(self):
pass
def html(self):
pass
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Q_MLP(nn.Module):
"""
simple mlp for 1-D observation input from envs like
CartPole-v1 etc.
Args:
input_size: a 2-D tuple or equivalent Iterable, indicating the size
of input, i.e, the obervation space
... |
"""Functions that read and write gzipped files.
The user of the file doesn't have to worry about the compression,
but random access is not allowed."""
# based on Andrew Kuchling's minigzip.py distributed with the zlib module
import struct, sys, time
import zlib
import __builtin__
__all__ = ["GzipFile","open"]
FTEX... |
import giambio
from debugger import Debugger
async def child():
print("[child] Child spawned!! Sleeping for 2 seconds")
await giambio.sleep(2)
print("[child] Had a nice nap!")
raise TypeError("rip")
async def child1():
print("[child 1] Child spawned!! Sleeping for 8 seconds")
await giambio.s... |
"""
Keycloak Client.
~~~~~~~~~~~~~~~~
"""
import re
import requests
import time
class NoSessionException(Exception):
pass
class KeycloakClient(object):
ADMIN_LOGIN_CLIENT_ID = 'admin-cli'
RELATIVE_HEALTH_CHECK_ENDPOINT = '/realms/master'
RELATIVE_TOKEN_ENDPOINT = '/realms/master/protocol/openid-con... |
from rest_framework import serializers
from api.models import *
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = Users
fields = ('id', 'first_name', 'last_name', 'email', 'registered')
class BookerSerializer(serializers.ModelSerializer):
user = UserSerializer(many=False... |
# -*- coding: UTF-8 -*-
import sys
import textwrap
import click
import tweepy
from blabbr.config import Config
from blabbr.model import ModelBuilder, TwitterDigger
from blabbr.twitter import TwitterClient
from blabbr.bot import Bot
class Cli:
def __init__(self, cfg=None, model=None, **kw):
self.cfg = C... |
# -*- test-case-name: twisted.names.test.test_names,twisted.names.test.test_server -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Async DNS server
Future plans:
- Better config file format maybe
- Make sure to differentiate between different classes
- notice truncation bit... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from cc... |
from model.semseg.base import BaseNet
import torch
from torch import nn
import torch.nn.functional as F
import pytorch_lightning as pl
class DeepLabV3Plus(BaseNet):
def __init__(self, backbone, nclass, args=None):
super(DeepLabV3Plus, self).__init__(backbone, nclass, args)
low_level_channels = s... |
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.forms import modelformset_factory
from django.http import JsonResponse
from django.shortcuts import get_obje... |
import logging
import os
from abc import abstractmethod
import copy
class EntityRecognizer:
MIN_SCORE = 0
MAX_SCORE = 1.0
CONTEXT_SIMILARITY_THRESHOLD = 0.65
CONTEXT_SIMILARITY_FACTOR = 0.35
MIN_SCORE_WITH_CONTEXT_SIMILARITY = 0.6
CONTEXT_PREFIX_COUNT = 5
CONTEXT_SUFFIX_COUNT = 0
def ... |
"""
Pattern matching detection.
"""
import numpy as np
import pandas as pd
def pattern_matching_detection(activation, patterns, method, **kwargs):
"""General function to perform pattern matching based detection.
Parameters
----------
activation: array_like
description of the activity of the... |
# Generated from Csv.g4 by ANTLR 4.8
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\b")
buf.write("\64\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7... |
import torch
from torch.autograd import Variable
import torch.optim as optim
import torch.nn.functional as F
import sys
from dataset import MitbinDataset
from model import TCN
import numpy as np
import argparse
from collections import defaultdict
from sklearn.metrics import roc_auc_score
from sklearn.metrics import auc... |
from os import mkdir, listdir, getcwd
from os.path import join
import datetime
import numpy as np
def calculate_number_of_peaks_gottschalk_80_rule(peak_to_measure, spread):
"""
Calculate number of peaks optimal for SOBP optimization
on given spread using Gottschalk 80% rule.
"""
width = peak_to_m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.