content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# Copyright 2016 Internap
#
# 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, sof... | python |
import concurrent.futures
import sqlite3
import pytest
from yesql.drivers.sio import sqlite
pytestmark = pytest.mark.asyncio
@pytest.fixture(autouse=True)
def connection(MockSQLiteConnection):
conn = MockSQLiteConnection.return_value
yield conn
MockSQLiteConnection.reset_mock()
sqlite3.connect.rese... | python |
import psycopg2
from flask import render_template, request, jsonify
from giraffe_api import app, db
q_metric = "select giraffe.init_metric(%(name)s, %(description)s)"
q_metric_value = "insert into giraffe.metric_value" \
"(db_timestamp, cluster, db, metric_id, integer_value, numeric_value) " \
... | python |
from turtle import Turtle
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.l_score = 0
self.r_score = 0
self.color('white')
self.hideturtle()
self.penup()
self.sety(200)
def increase_r_score(self):
self.r_score += 1
def... | python |
import cv2
import os
# source: https://stackoverflow.com/a/44659589
def image_resize(image, width = None, height = None, inter = cv2.INTER_AREA):
# initialize the dimensions of the image to be resized and
# grab the image size
dim = None
(h, w) = image.shape[:2]
# if both the width and height are N... | python |
from __future__ import absolute_import
from .uploader import GraphiteUploader
| python |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-26 08:15
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('portal', '0006_auto_2016022... | python |
import json
from rentomatic.serializers import storageroom_serializer as srs
from rentomatic.domain.storageroom import StorageRoom
def test_serialize_domain_storageroom():
room = StorageRoom(
'f853578c-fc0f-4e65-81b8-566c5dffa35a',
size=200,
price=10,
longitude='-0.0999... | python |
from django.shortcuts import get_list_or_404, get_object_or_404
from rest_framework.serializers import ModelSerializer, Serializer
from shop.models import Image, Product
from rest_framework import fields
class ImageSerializer(ModelSerializer):
mid_size = fields.ImageField()
class Meta:
model = Im... | python |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import, division, unicode_literals, print_function
import copy
import numpy as np
import warnings
from astropy.extern import six
from astropy.modeling.core import Model
from astropy.modeling.parameters import Parameter
fr... | python |
import colorama, os, ctypes, re, glob
from colorama import Fore
from sys import exit
def cls():
os.system("cls" if os.name=="nt" else "clear")
def fexit():
input(f"\n{Fore.RESET}Press Enter button for exit")
exit()
os.system("cls")
if __name__ == "__main__":
os.system("cls")
ctypes.... | python |
# coding: utf-8
"""
"""
import torch
import torch.optim as optim
import torch.nn as nn
import os
import time
import copy
import numpy as np
import torch.nn.functional as F
from tensorboardX import SummaryWriter
from sklearn.metrics import confusion_matrix
from sklearn.metrics import roc_auc_score, f1_score
from visua... | python |
# Author: Andrew Sainz
#
# Purpose: XMLAnalyze is designed to iterate through a collection of Post data collected from Stack Overflow
# forums. Data collected to analyze the code tagged information to find the language of the code
# being utilized.
#
# How to use: To run from command line input "pytho... | python |
from .bindings import so, FPDF_PATH_POINT, FPDF_RECT
from ctypes import pointer
class Glyph:
'''Represents Glyph drawing instructions'''
LINETO = 0 #: LineTo instruction
CURVETO = 1 #: CurveTo instruction
MOVETO = 2 #: MoveTo instruction
def __init__(self, glyph, parent):
self._glyp... | python |
n = int(raw_input())
comportadas = 0
children = []
for i in range(n):
ent = map(str, raw_input().split())
children.append(ent[1])
if ent[0] == "+":
comportadas += 1
children.sort()
for child in children:
print child
print "Se comportaram: %d | Nao se comportaram: %d" % (comportadas, n - co... | python |
import sys
from mpc_func import *
try:
poses = load_poses(sys.argv[1])
except:
print('Please use the right .csv file!')
sparseness = 100
sparse_poses = poses[1::sparseness, 1:3]
path = [148, 150, 151, 153, 154, 156, 158, 160, 162, 163]
dt = 1 # [s] discrete time
lr = 1.0 # [m]
T = 6 # nu... | python |
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.index, name = 'index'),
path('home/',views.home,name = 'home'),
path('maps/',views.maps, name = 'maps'),
path('maps/3dmap',views.mapsd, name = 'mapsd'),
path('accounts/login/', views.loginpage , name = ... | python |
import os
import sys
import unittest
if __name__ == "__main__":
# add the path to be execute in the main directory
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
testmodules = [
'tests.test_nsga2',
#'pymoo.usage.test_usage'
]
suite = unittest.Tes... | python |
import logging
import os
from peek_plugin_base.PeekVortexUtil import peekStorageName
logger = logging.getLogger(__name__)
class StorageTestMixin:
def __init__(self):
self._dbConn = None
def setUp(self) -> None:
from peek_storage._private.storage import setupDbConn
from peek_storage.... | python |
# -*- coding: utf-8 -*-
"""
654. Maximum Binary Tree
Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
The root is the maximum number in the array.
The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
The right sub... | python |
import torch
import math
import numpy as np
from torch.distributions.multivariate_normal import MultivariateNormal
from spirl.utils.pytorch_utils import ten2ar
from spirl.utils.general_utils import batch_apply
class Gaussian:
""" Represents a gaussian distribution """
# TODO: implement a dict conversion fun... | python |
#-*- coding: utf-8 -*-
""" Use name to identify share isin by using fondout db and google """
"""
1. Lista pa okända shares vi vill söka isin på.
2. Traversera lista.
3. Kontrollera mot shares
4. Kontrollera mot share_company
5. Kontrollera mot shares LIKE från båda håll min chars 5
6. Kontrol... | python |
"""Provides conversion for transaction data into an exchange format."""
import textwrap
import time
from powl import exception
class TransactionConverter(object):
"""
Provides methods to convert data into a financial exchange format.
"""
def convert(self, date, debit, credit, amount, memo):
""... | python |
#!/usr/bin/env python
# pylint: disable=wrong-import-position
import os
import subprocess
import sys
import tempfile
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
from xv_leak_tools.helpers import current_os
if len(sys.argv) != 2:
sys.stderr.write("USAGE: setup_python.py virt... | python |
from otd.skosnavigate import SKOSNavigate
from similarity.csv_parse import get_fragment
from utils.graph import create_bound_graph
def sort_turtle(prefix, identifiers, file_in, file_out):
with open(file_in, encoding='utf8') as fd:
line_iter = iter(fd)
entities = dict()
preamble_finished =... | python |
import pytest
from ee.clickhouse.queries.groups_join_query import GroupsJoinQuery
from posthog.models.filters import Filter
def test_groups_join_query_blank():
filter = Filter(data={"properties": []})
assert GroupsJoinQuery(filter, 2).get_join_query() == ("", {})
def test_groups_join_query_filtering(snaps... | python |
import sys
from tkinter import *
from slideShow import SlideShow
if len(sys.argv) == 2:
picdir = sys.argv[1]
else:
picdir = '../gifs'
root = Tk()
Label(root, text="Two embedded slide shows: each side uses after() loop").pack()
SlideShow(msecs=200,
parent=root, picdir=picdir, bd=3, relief=SUNKEN).pa... | python |
class Transform(object):
"""Transform coordinate systems: scale / translate"""
def __init__(self, scale, translate):
"""Set up the parameters for the transform"""
self.scale = scale
self.translate = translate
def forward(self, pt):
"""From the original box to (-1,-1),(1,1) ... | python |
from facenet_pytorch import InceptionResnetV1
class SiameseNet(nn.Module):
def __init__(self):
super().__init__()
self.encoder = InceptionResnetV1(pretrained='vggface2')
emb_len = 512
self.last = nn.Sequential(
nn.Linear(4*emb_len, 200, bias=False),
... | python |
Import("env")
from SCons.Script import COMMAND_LINE_TARGETS
def buildWeb(source, target, env):
env.Execute("cd web; pnpm build")
print("Successfully built webui")
def convertImages(source, target, env):
env.Execute("cd converter; go run .")
print("Successfully converted images")
env.AddPreAction("bui... | python |
from . import tables
from . unquote import unquote as _unquote
__all__ = 'Quote', 'unquote'
SHORT_ASCII = '\\u{0:04x}'
LONG_ASCII = '\\u{0:04x}\\u{1:04x}'
def Quote(b):
return _QUOTES[bool(b)]
def unquote(s, strict=True):
return _QUOTES[s[0] == tables.SINGLE].remove(s, strict)
class _Quote:
def __in... | python |
""" predict.py
Predict flower name from an image with predict.py along with the probability of
that name. That is, you'll pass in a single image /path/to/image and return the
flower name and class probability.
Basic usage:
python predict.py /path/to/image checkpoint
Args:
--img
--checkpoint
--top_k
... | python |
import accounting.config
import pytransact.testsupport
def pytest_configure(config):
global unconfigure
unconfigure = pytransact.testsupport.use_unique_database()
accounting.config.config.set('accounting', 'mongodb_dbname',
pytransact.testsupport.dbname)
def pytest_unconf... | python |
#!/usr/bin/python3
import math
#Generate the ovsf tree
def ovsfGenerator(numberOfMobile):
#calculate the depth of the OVSF code tree
numberOfColumn = math.ceil(math.log(numberOfMobile,2))
column = [1]
#Generation of the list of codes
for i in range (0,numberOfColumn):
newColumn=[]
xornu... | python |
from pprint import pprint as pp
from funcs import *
import time
import random
import ConfigParser
config= ConfigParser.ConfigParser()
config.read('config.cfg')
PERIOD = int(config.get('Run','period'))
## currently set to make it so we don't hit window
## rate limits on friendship/show
## should be able to increase t... | python |
#!/usr/bin/env python3.6
#
# uloop_check.py
#
# Gianna Paulin <pauling@iis.ee.ethz.ch>
# Francesco Conti <f.conti@unibo.it>
#
# Copyright (C) 2019-2021 ETH Zurich, University of Bologna
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | python |
"""Cron job code."""
from google.appengine.ext import ndb
import cloudstorage
import datetime
import logging
from api import PermissionDenied
from model import (Email, ErrorChecker, Indexer, User)
import config
import util
class Cron:
"""A collection of functions and a permission scheme for running cron jobs.
... | python |
######################################################################################################################
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... | python |
"""
Operators with arity 2.
Take 2 colors and mix them in some way. Owns two 0/1 arity operators,
which calculate the initial colors.
Adds a shift by colors, that is, for two colors [rgb] + [RGB] can mix as
([rR gG bB], [rG gB bR], [rB gR bG]).
"""
from abc import ABC, abstractmethod
from .base import Operator, ope... | python |
from urllib.parse import urlparse
def parse_link(link):
href = link.attrs.get("href")
return href and urlparse(href)
| python |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.13.7
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown] slideshow={"slide_type": "slide"}
# ... | python |
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def ani_easy(tas, cmap='BrBG'):
# Get a handle on the figure and the axes
fig, ax = plt.subplots(figsize=(12,6))
# Plot the initial frame.
cax = tas[0,:,:].plot(
add_colorbar=True,
cmap=cmap,
#cmap='BrBG',
#cmap='m... | python |
from collections import ChainMap, defaultdict
from itertools import chain
import pathlib
import re
from cldfbench import Dataset as BaseDataset, CLDFSpec
from pybtex.database import parse_string
from pydictionaria.sfm_lib import Database as SFM
from pydictionaria.preprocess_lib import marker_fallback_sense, merge_mar... | python |
import requests
from django.conf import settings
DEBUG = getattr(settings, 'DEBUG')
class AppleService(object):
def __init__(self, base_url):
self.base_url = base_url
def notify_all(self, resources, message):
for resource in resources:
data = '{"resource": "' + resource +... | python |
from keepkeylib.client import proto, BaseClient, ProtocolMixin
from ..trezor.clientbase import TrezorClientBase
class KeepKeyClient(TrezorClientBase, ProtocolMixin, BaseClient):
def __init__(self, transport, handler, plugin):
BaseClient.__init__(self, transport)
ProtocolMixin.__init__(self, transpo... | python |
userInput = ('12')
userInput = int(userInput)
print(userInput)
| python |
import json
import os
from typing import Any, Dict, List, Union
here = os.path.abspath(os.path.dirname(__file__))
def _load_list(paths: List[str]) -> dict:
content: Dict[str, Any] = {}
for p in paths:
with open(p) as h:
t = json.load(h)
content.update(t)
return content
d... | python |
'''
Copyright (c) 2018 Modul 9/HiFiBerry
2020 Christoffer Sawicki
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,... | python |
# Module fwpd_histogram
import ctypes as ct
import time
from modules.example_helpers import *
def enable_characterization(ADQAPI, adq_cu, adq_num, channel, enable, only_metadata):
# Enable logic and release reset
assert (channel < 5 and channel > 0), "Channel must be between 1-4."
# Lookup base ... | python |
#
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
#
import pytest
import mlos.global_values
from mlos.OptimizerEvaluationTools.ObjectiveFunctionFactory import ObjectiveFunctionFactory, objective_function_config_store
from mlos.Optimizers.RegressionModels.GoodnessOfFitMetrics import Dat... | python |
from allauth.account import signals
from allauth.account.views import SignupView
from allauth.account.utils import send_email_confirmation
from allauth.exceptions import ImmediateHttpResponse
from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
fr... | python |
# encoding: utf-8
import sys
from PyQt5 import QtQuick
from PyQt5.QtCore import QObject, pyqtSlot, QTimer
from PyQt5.QtGui import QIcon
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtWidgets import QWidget, QApplication, QLabel
from resources import resources
print(QtQuick)
print(resources)
class MyApp... | python |
import logging
import os
import posixpath
from dvc.config import Config
from dvc.config import ConfigError
from dvc.utils import relpath
from dvc.utils.compat import urlparse
logger = logging.getLogger(__name__)
class RemoteConfig(object):
def __init__(self, config):
self.config = config
def get_s... | python |
# DAACS ~= NASA Earthdata data centers
DAACS = [
{
"short-name": "NSIDC",
"name": "National Snow and Ice Data Center",
"homepage": "https://nsidc.org",
"cloud-providers": ["NSIDC_CPRD"],
"on-prem-providers": ["NSIDC_ECS"],
"s3-credentials": "https://data.nsidc.earthda... | python |
from tkinter import *
from SMExp import*
from DMExp import*
import pygame
import time
import random
class SMPage(Frame):
MUTE = False
INFO = False
DIM = 0
def __init__(self, parent, controller):
Frame.__init__(self, parent)
pygame.mixer.init()
SGMWall = PhotoImage(fi... | python |
#!/usr/bin/env python3
#
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import functools
import multiprocessing
import sys
import unittest
from io import StringIO
import click
import tempf... | python |
import random
import json
import requests
from flask import Flask, request, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def home():
rcomb = request.args.get('rcomb','http://appcombiner:5003/rcomb')
return render_template('index.html',... | python |
from django.urls import reverse
from django.views import generic
from . import forms
class KindeditorFormView(generic.FormView):
form_class = forms.KindeditorForm
template_name = "form.html"
def get_success_url(self):
return reverse("kindeditor-form")
kindeditor_form_view = KindeditorFormView.... | python |
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Michael A.G. Aivazis
# California Institute of Technology
# (C) 1998-2003 All Rights Reserved
#
# <LicenseText>
#
# ~~~~~~~~~~~~~~~~~~~~~~~~... | python |
from pathlib import Path
from typing import List
def get_asset(name: str) -> Path:
try:
path = next(Path(__file__).parent.rglob(name))
except StopIteration:
raise FileNotFoundError(name)
return path
def find_asset(name: str) -> List[Path]:
paths = list(Path(__file__).parent.rglob(nam... | python |
import pandas as pd
import numpy as np
from scipy.stats import multivariate_normal
from sklearn.metrics import accuracy_score
def bayesiano(classes,x_train,y_train,x_test,y_test):
#### Realiza a classificacao ####
# Matriz que armazena as probabilidades para cada classe
P = pd.DataFram... | python |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from google.ads.google_ads.v3.proto.resources import bidding_strategy_pb2 as google_dot_ads_dot_googleads__v3_dot_proto_dot_resources_dot_bidding__strategy__pb2
from google.ads.google_ads.v3.proto.services import bidding_strategy_service... | python |
# coding: utf-8
# 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
# "... | python |
import re, sys, glob
from os.path import join
from tabulate import tabulate
indir = sys.argv[1]
outfile = join(indir, "xfold_eval.txt")
name2fold = {}
for fold in range(5):
if fold not in name2fold:
name2fold[fold] = {}
file = join(indir, f"fold{fold}/eval.txt")
with open(file, 'r') as f:
tuple_performance,... | python |
# coding: utf-8
__doc__ = """包含一些继承自默认Qt控件的自定义行为控件。"""
import os
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QLineEdit, QTextEdit
class QLineEditMod(QLineEdit):
def __init__(self, accept="dir", file_filter=set()):
super().__init__()
self.setContextMenuPolicy(Qt.NoContextMenu)
... | python |
"""
A collection of constants including error message
"""
ERROR_CLONE_TIMEOUT_EXPIRED = 'Timeout expired error'
ERROR_CLONE_FAILED = 'Cloning failed error'
| python |
##########################################################################
#
# Copyright (c) 2013, Image Engine Design Inc. 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... | python |
from fastapi import Request
from geobook.db.backends.mongodb import exceptions
from starlette.responses import JSONResponse
async def validation_exception_handler(
request: Request,
exc: exceptions.ValidationError,
) -> JSONResponse:
headers = getattr(exc, 'headers', None)
if headers:
return J... | python |
# Generated by Django 2.0.5 on 2018-06-12 17:31
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('webarchives', '0004_auto_20180609_1839'),
]
operations = [
migrations.AlterField(
model_name... | python |
from collections import deque
import numpy as np
from gym import spaces
from gym.envs.atari.atari_env import AtariEnv
from . import utils
class MultiFrameAtariEnv(AtariEnv):
metadata = {'render.modes': ['human', 'rgb_array']}
no_op_steps = 30
def __init__(self, game='pong', obs_type='image', buf_size=4, gr... | python |
from random import randint
from time import sleep
computador = randint(0, 5)
print('-=' * 20)
print('Vou pensar em um número entre 0 e 5.Tente adivinhar...')
print('-=' * 20)
jogador = int(input('Em que número eu pensei? '))
print('Processando...')
sleep(3)
if jogador == computador:
print('Parabéns! Você acertou!')... | python |
try:
from pycaret.internal.pycaret_experiment import TimeSeriesExperiment
using_pycaret=True
except ImportError:
using_pycaret=False
| python |
#! /usr/bin/env python
import json
import argparse
from dashboard.common import elastic_access
from dashboard.common import logger_utils
from dashboard.conf import config
from dashboard.conf import testcases
from dashboard_assembler import DashboardAssembler
from visualization_assembler import VisualizationAssembler
... | python |
#!/home/ubuntu/DEF/PG/project/venv3/bin/python3
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| python |
from .layers import *
| python |
import os
import json
class Config:
def __init__(self, configpath):
self._data = self._get_config_data(configpath)
self.client_id = self._data['client_id']
self.username = self._data['username']
self.account_id = self._data['account_id']
self.redirect = self._data['redirect... | python |
class OpenL3Error(Exception):
"""The root OpenL3 exception class"""
pass | python |
from aiogram.dispatcher.filters.state import State, StatesGroup
class AddStoreForm(StatesGroup):
city_id = State()
store_id = State()
class SearchSku(StatesGroup):
select_sku = State()
| python |
import os
import json
from flask import request, abort, jsonify, make_response, Response
from jsonschema import validate, ErrorTree, Draft4Validator as Validator
from app.properties import properties_bp
from .models import Property
from .repositories import PropertyRepository as Repository
from .utils import load
@pr... | python |
from .annotation_decorator import annotate
from .annotation_decorator import annotate_class
from .annotation_decorator import annotate_method
from .application import WinterApplication
from .component import Component
from .component import component
from .component import is_component
from .component_method import Com... | python |
import sys
printf = lambda fmt,*args: sys.stdout.write(fmt%args)
printf ("This is a %s of %is of possibilities of %s","test",1000,printf)
| python |
#!/usr/bin/python
import pickle
import pandas as pd
import numpy as np
def convert_and_clean_data(data_dict, fill_na = 1.e-5):
'''
Takes a dataset as a dictionary, then converts it into a Pandas DataFrame for convenience.
Replaces all NA values by the value specified in 'fill_na' (or None).
Cleans up... | python |
SIZE = (640,480)
TITLE = "Pipboy"
TEXT_COLOUR = (0,255,0)
TEXT_SIZE = 12
TEXT_FONT = '../resources/monofonto.ttf'
BOARDER_SPACE = 10
TOP_BOARDER = 6
BOX_SPACE = 20
| python |
import os
import sys
import copy
import argparse
from avalon import io
from avalon.tools import publish
import pyblish.api
import pyblish.util
from pype.api import Logger
import pype
import pype.hosts.celaction
from pype.hosts.celaction import api as celaction
log = Logger().get_logger("Celaction_cli_publisher")
p... | python |
# Copyright 2018 Canonical Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | python |
import numpy as np;
import numpy.matlib as npm;
import DataHelper;
# consume class is 0, 1, ..., discrete feature values is 0, 1, 2, ...
class NaiveBayes:
def __init__(self, smoothingFactor):
self.__smoothingFactor = smoothingFactor;
self.__discreteFeatureIndices = None;
self.__discreteFe... | python |
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
"""This module contains mixin classes for scoped nodes."""
from typing import TYPE_CHECKIN... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-07-14 12:19
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
depe... | python |
>>> 3
3
>>> _*_, _**0.5
(9, 1.7320508075688772)
>>>
| python |
import bson
import os, base64, zlib, random
from bson import BSONCoding, import_class
class Member(BSONCoding):
def __init__(self, username = "", code = "00", password = ""):
self.username = username
self.code = code
self.password = password
def __str__(self):
di... | python |
# library/package semantic version
__api_version__ = '1.4'
__generation__ = 1
| python |
from math import (
sin,
cos,
tan,
acos,
radians,
degrees,
)
from datetime import (
timedelta,
)
def earth_declination(n):
return 23.45 * sin(radians(360/365 * (284+n)))
def td(lat):
dec = earth_declination(119) #TODO Change this literal
cofactor = -(tan(radians(lat)) * tan(rad... | python |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Test app."""
from __future__ import absolute_import
import pytest
from flask imp... | python |
'''
Tests for the lookup module.
'''
import sys
import unittest
from io import StringIO
from unittest.mock import patch
from modules import rec_lookup
sys.path.insert(0, "0_1_0/")
class TestLookup(unittest.TestCase):
'''Lokup Tests'''
def setUp(self):
self.nodes_json = StringIO(
... | python |
# author: Artan Zandian
# date: 2022-02-18
import tensorflow as tf
from tensorflow.keras.layers import (
Input,
Conv2D,
MaxPooling2D,
Dropout,
Conv2DTranspose,
concatenate,
)
def encoder_block(inputs=None, n_filters=32, dropout=0, max_pooling=True):
"""
Convolutional e... | python |
##parameters=add='', edit='', preview=''
##
from Products.PythonScripts.standard import structured_text
from Products.CMFCore.utils import getUtilityByInterfaceName
from Products.CMFDefault.utils import decode
from Products.CMFDefault.utils import html_marshal
from Products.CMFDefault.utils import Message as _
atool =... | python |
import pytest
from django.urls import reverse
from google.auth.exceptions import GoogleAuthError
from crm.factories import UserSocialAuthFactory, ProjectMessageFactory
from crm.models import ProjectMessage
@pytest.mark.django_db
def test_project_message_index(admin_app,
project_message... | python |
"""
Copyright 2015 INTEL RESEARCH AND INNOVATION IRELAND LIMITED
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... | python |
from django.contrib.auth import authenticate
from django.test import TestCase
from django.urls import resolve
from .models import User
from .views import index_view, dashboard_view
from django.contrib.auth.views import LoginView, LogoutView
from django.contrib.auth.decorators import login_required
class UserLoggedInT... | python |
"""
Example Vis Receive workflow
"""
# pylint: disable=C0103
import logging
import ska_sdp_config
import os
# Initialise logging and configuration
logging.basicConfig()
log = logging.getLogger('main')
log.setLevel(logging.INFO)
config = ska_sdp_config.Config()
# Find processing block configuration from the configur... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.