content stringlengths 5 1.05M |
|---|
from __future__ import absolute_import, print_function
from django.conf import settings
from sentry.plugins import Plugin2
from .processor import SourceProcessor
def preprocess_event(data):
if data.get('platform') != 'javascript':
return
processor = SourceProcessor()
return processor.process(d... |
import json
import os
import random
import warnings
from argparse import Namespace
import numpy as np
import torch
warnings.simplefilter(action="ignore", category=DeprecationWarning)
def set_seed(seed=42):
random.seed(seed)
os.environ["PYTHONHASHSEED"] = str(seed)
np.random.seed(seed)
torch.manual_s... |
import torch
from torch import nn
from torch.utils.data import DataLoader
import wandb
from config import get_params
from dataset import DatasetNorm
from utils.read_data import parse_data
from utils import make_dataset
from utils.utils import set_random_seed, save_model, load_model, accuracy
from model.model... |
import numpy as np
import os
import sys
import math
import random
import glob
import cv2
import torch
from scipy import io
from opts import market1501_train_map, duke_train_map, get_opts
market_dict = {'age':[1,2,3,4], # young(1), teenager(2), adult(3), old(4)
'backpack':[1,2], # no(1), yes(2)
... |
from tkinter import *
import requests
from bs4 import BeautifulSoup
from tkinter.font import Font
from tkinter import ttk
import time
import threading
root = Tk()
root.title("COVID-19")
root.geometry("300x360")
root.resizable(0, 0)
root.iconbitmap("icon.ico")
label_frame_1 = LabelFrame(root, text="Detai... |
"""
백준 1967번 : 트리의 지름
"""
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
# dfs로 한 점 기준으로 거리를 잴 수 있다.
def dfs(start, weight):
for i in tree[start]:
node, w = i
if dist[node] == -1:
dist[node] = weight + w
dfs(node, weight + w)
node = int(input())
tree = ... |
# Copyright 2016: Mirantis Inc.
# 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 b... |
import time
from compute.process import dispatch_to_do
from compute.gpu import gpus_all_available
from comm.utils import CacheToResultFile
from algs.regularized_evolution.genetic.dag import DAG, DAGValidationError
from algs.regularized_evolution.utils import Utils
from algs.regularized_evolution.genetic.statusupdatetoo... |
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ---------------------... |
"""usgs_topo_tiler.usgs_topo: USGS Historical topo processing."""
import json
from typing import Any, List, Tuple
import numpy as np
import rasterio
from rasterio.crs import CRS
from rasterio.warp import transform_bounds
from rio_tiler import reader
from usgs_topo_tiler.cutline import get_cutline
from usgs_topo_tile... |
import numpy as np
class Solution(object):
def XXX(self, s):
maxLen = 0
maxStr = ""
s_len = len(s)
p = np.arange(0.5, s_len, 0.5)
for i in p:
if i % 1 == 0.5:
start = (int)(i - 0.5)
end = (int)(i + 0.5)
else:
... |
import pydicom
from PIL import Image, ImageQt
class Dicom:
def __init__(self, filename):
self.filename = filename
# Information related to image
self.data = pydicom.read_file(filename)
self.size = (self.data.Rows, self.data.Columns)
self.image = self.get_8bit_image()
... |
import numpy as np
import cv2
class Detection(object):
"""
This class represents a bounding box detection for a single image.
Parameters
----------
tlbr : array_like
Bounding box in format `(min x, min y, max x, max y)`.
class_id : int
Class id
confidence : float
D... |
""" Not fully examined in the latest version of code.. """
import os
import sys
from pathlib import Path
from typing import List
import torch
from torch import nn
from diffabs import DeeppolyDom, IntervalDom
sys.path.append(str(Path(__file__).resolve().parent.parent))
from art.acas import AcasNet, AcasProp
from ar... |
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from django import forms
class LoginForm(forms.Form):
username=forms.CharField(max_length=50, required=True)
password=forms.CharField(max_length=150, required=True)
back_url=forms.CharField(max_length=150, required=False)
class ResetPasswordForm(forms.Form):
username=forms.CharField(required=True,max_... |
#!/bin/python3
from mavlink_arbiter.singleton import singleton
import queue
class BCOLORS:
"""
Static class for OS
Constant use on headers.
"""
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC ... |
from __future__ import unicode_literals
from django.conf.urls import url
from . import views
from mezzanine.conf import settings
# Trailing slash for urlpatterns based on setup.
_slash = "/" if settings.APPEND_SLASH else ""
# patterns
urlpatterns = [
url("^/events/feeds/(?P<format>.*)%s$" % _slash,
vie... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2016, Silvio Peroni <essepuntato@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any purpose
# with or without fee is hereby granted, provided that the above copyright notice
# and this permission notice appear in all copies.
... |
import re
# import sys
import ast
import unicodedata
from decimal import Decimal
from fractions import Fraction
from collections import defaultdict, namedtuple
from apps.products.models import Unit, Product
from apps.recipes.models import Dish, DishLabel, Recipe, RecipeInstructions, Ingredient
# def print(s):
# ... |
import os
import numpy as np
import cv2
import json
from util.process_box import corner_to_yolo_box
def read_json_label(filename):
with open(filename) as fp:
str_json_data = fp.read()
json_data = json.loads(str_json_data)
label=[]
for shape in json_data['shapes']:
cls =... |
#print(ad) || total
#print(ad[0]) || Name
#print(ad[1]) || Passhashed sha3_512
#print(ad[2]) || Wins
#print(ad[3]) || Losses
#print(ad[4]) || Draws
#print(ad[5]) || Account type || 0/Standard | 1/SuperUser | 2/Admin | 3/Debug
#print(ad[6]) || Profile Picture Location
#Imports
import tkinter as tk
from tkint... |
import unittest
from formation import AppBuilder
from formation.tests.support import get_resource
class CanvasTestCase(unittest.TestCase):
builder = None
@classmethod
def setUpClass(cls) -> None:
cls.builder = AppBuilder(path=get_resource("canvas.xml"))
cls.canvas1 = cls.builder.canvas1
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import labyrinth
with open('requirements.txt') as f:
requires = f.read().split('\n')
setup(
name='nz-labyrinth',
version=3.6,
packages=find_packages(),
install_requires=requires,
author='Nico Zhan',... |
"""
file contains various functions used as subroutines by the spiders and crawler
"""
import os
import urlparse
# creates the project directory
def create_main_directory(path):
if not os.path.isdir(path):
os.makedirs(path)
# used as subroutine in create_directory
# splits the path into direct... |
from django.http import Http404
from awards.models import FilmAward, FilmAwardReceived
from awards.serializers import ExtendedFilmAwardSerializer
from movies.models import Film
from rest_framework.viewsets import ModelViewSet
from movie_geeks_django.mixins import SerializerDifferentiationMixin
from .models import Pe... |
from . import account_payment
from . import payment_acquirer
from . import payment_transaction
|
import re
from fabric.api import put, sudo, task, env, hide, settings, run
from fabric.contrib import files
def _read_lines_from_file(file_name):
with open(file_name) as f:
packages = f.readlines()
return map(lambda x: x.strip('\n\r'), packages)
def user_exists(username):
exists = False
wit... |
class DeviceType:
GENERIC = 'generic'
BUTTON = 'button'
DISPLAY = 'display'
SPEAKER = 'speaker'
CHOICES = (
(BUTTON, 'Button'),
(DISPLAY, 'Display'),
(SPEAKER, 'Speaker'),
)
|
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from .raymarching import AbsorptionOnlyRaymarcher, EmissionAbsorptionRaymarcher
from .raysampling import G... |
import sys
from PyQt5 import QtWidgets
def window():
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QWidget()
w.setWindowTitle('PYQt5 lesson 1')
w.show()
sys.exit(app.exec_())
window() |
from ggmodel_dev.graphmodel import GraphModel
from ggmodel_dev.utils import get_model_properties
PM25_nodes = {
"AEUi": {
"name": "Total agricultural energy use per type",
"type": "input",
"unit": "TWH"
},
"BMB": {
"name": "Total biomass burned",
"type": "input",
... |
import pygame
from pygame.locals import *
from pygame.event import wait
from deck import *
from game import *
from init import *
deck = Deck()
King = Game("Pit","Dotti","Lella","Rob")
giocata=0
position=[0,0,0,0]
carteGiocate=[[],[],[],[],[],[],[],[],[],[],[],[],[]]
timerScomparsa=0
timerGiocata=0
primaCarta = None
... |
import aws_cdk_lib as cdk
from constructs import Construct, IConstruct
|
import matplotlib.pyplot as plt
import numpy as np
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
n12 = [ 2.00000000000000000000, 2.00000000000000000000, 2.80735492205760410749, 2.80735492205760410749, 2.00000000000000000000, 1.00000000000000000000, 3.16992500144231236295, 1.0000000... |
'''
Created on Nov 2, 2014
@author: ehenneken
'''
import simplejson as json
from sqlalchemy import Column, Integer, String, DateTime, Boolean
from sqlalchemy.ext.declarative import DeclarativeMeta
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.dial... |
from django.conf.urls.defaults import *
from web_frontend.views import *
from web_frontend.condor_copasi_db import views as db
from web_frontend.condor_copasi_db.views import tasks as db_tasks
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
from django.conf import settings
admin.aut... |
# coding: utf-8
def test_default_state(printer):
assert printer.is_online is True
def test_online(printer):
printer.online()
assert printer.is_online is True
def test_offline(printer):
printer.offline()
assert printer.is_online is False
def test_online_after_offline(printer):
printer.onl... |
from core.portfolio.abstract_portfolio_handler import AbstractPortfolioHandler
from core.portfolio.portfolio import Portfolio
class PortfolioHandler(AbstractPortfolioHandler):
def __init__(self, exchange, capital, base_currency, events_queue,
price_handler, risk_manager):
super().__init_... |
import json
import os
from requests.auth import HTTPBasicAuth
import requests
_readme_api_url = "https://dash.readme.io/api/v1/"
class ReadMeSession:
# Passed for every API call
__headers = {"Accept": "application/json", "content-type": "application/json"}
# Map: <version string -> version info>
__v... |
from simple_array.m_kth_largest import KLargestElement
class TestKLargestElement:
def test_empty_array(self):
kl = KLargestElement()
ans = kl.find_bubble_sort(None, 2)
assert ans is None
def test_bubble_sort(self):
kl = KLargestElement()
nums = [3, 2, 1, 5, 6, 4]
... |
"""
A component that represents the cooling system in a refuelling station is
created through this class.
*****
Scope
*****
As part of the hydrogen refuelling station, a cooling system is required
to precool high pressure hydrogen before it is dispensed into the vehicle's
tank. This is in order to prevent the tank fro... |
from pycamara.base import BaseClient
class PropositionClient(BaseClient):
def all(self):
return self.safe(self._get('/proposicoes'))
def filter(self, **kwargs):
return self.safe(self._get('/proposicoes', **kwargs))
def get(self, proposition_id):
path = '/proposicoes/{}'.format(p... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸 (Blueking) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may... |
from flask_restful import Resource
class status(Resource):
def get(self):
return {'status':'OK'}, 200 |
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
try:
import sys
import subprocess
import re
import platform
from os import popen as pipe
except ImportError as e:
print("[!] Required module missing. %s" % e.args[0])
sys.exit(-1)
class ADB(object):
__adb_path = None
__output = None
... |
from unittest import TestCase
from registration.forms import UserRegistrationForm
class TestUserRegistrationForm(TestCase):
def test_register_user(self):
data = {
'email': 'test@email.com',
'password1': 'password',
'password2': 'password'
}
form = UserR... |
# AUTOGENERATED! DO NOT EDIT! File to edit: dev/02_data.datasets.ipynb (unless otherwise specified).
__all__ = ['get_cifar10']
# Cell
from ..imports import *
from .load import *
from ..vision.augmentations import *
# Cell
def get_cifar10(ds_dir: str, batch_size: int = None,
normalize: bool = False, p... |
# coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
import grpc
from qrl.generated import qrldebug_pb2_grpc, qrldebug_pb2
class StateValidator:
def __init__(self, debug_addresses):
self.debug_addresses = de... |
from enum import Enum
DEFAULT_CRF = 15
DEFAULT_PRESET = 'fast'
class Resolution(Enum):
# Width, height, auto bitrate
LOW_DEF = (360, 240, 500, 'auto_bitrate_240')
STANDARD_DEF = (720, 480, 1600, 'auto_bitrate_480')
MEDIUM_DEF = (1280, 720, 4500, 'auto_bitrate_720')
HIGH_DEF = (1920, 1080, 8000, '... |
import torch
import torch.nn as nn
"""
Generalized Matrix Factorization
NCF interpretation of MF. This part of framework
is used to endow model of linearity to learn interactions
between users and items
"""
class GMF(nn.Module):
def __init__(self, config):
super(GMF, self).__init__()
... |
import scipy.io
import numpy as np
import pickle
import os
import pandas as pd
BIRD_DIR = 'Data/birds'
def load_filenames(data_dir):
filepath = data_dir + '/filenames_flying_251.pickle'
with open(filepath, 'rb') as f:
filenames = pickle.load(f)
print('Load filenames from: %s (%d)' % (filepath, len... |
#! /usr/bin/env python
# Hi There!
# You may be wondering what this giant blob of binary data here is, you might
# even be worried that we're up to something nefarious (good for you for being
# paranoid!). This is a base64 encoding of a zip file, this zip file contains
# a fully functional basic pytest script.
#
# Pyt... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import time
import json
import hashlib
import string
import random
import requests
from .base import Map, WeixinError
__all__ = ("WeixinMPError", "WeixinMP")
DEFAULT_DIR = os.getenv("HOME_EP", os.getcwd())
class WeixinMPError(WeixinError)... |
"""Investigates how the optimal sweep distribution is dependent on lift coefficient."""
import optix
import json
import matplotlib
import numpy as np
import machupX as mx
import matplotlib.pyplot as plt
import scipy.optimize as opt
import multiprocessing as mp
from optimization import DragCase, grad, optimize
if _... |
"""
File for generating MAG data plots
"""
import heliopy.data.cassini as heliopydata
def base_mag_1min_plot(starttime, endtime, coords, ax=None):
"""
Plot spectrogram of MAG data
"""
magdata = heliopydata.mag_1min(starttime, endtime, coords)
for Baxis in ['Bx', 'By', 'Bz']:
ax.plot(magdat... |
# Copyright (c) 2015-2021 Agalmic Ventures LLC (www.agalmicventures.com)
#
# 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 u... |
## 1. Introducing Data Cleaning ##
# Read the text on the left, and then scroll to the bottom
# to find the instructions for the coding exercise
# Write your answer to the instructions below -- the list of
# lists is stored using the variable name `moma`
num_rows = len(moma)
## 2. Reading our MoMA Data Set ##
# imp... |
import pandas
import numpy as np
class SortinoRatioIndicator(object):
""" Sortino Ratio of a trading strategy KPI """
KPIdf: np.float64
def __init__(self, a_df: pandas.DataFrame, risk_free_rate: float = 0.022):
self.__setIndicator(a_df, risk_free_rate)
def __setIndicator(self, a_df: pandas.D... |
###
# Copyright (c) 2002-2005, Jeremiah Fincher
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of co... |
# SPDX-FileCopyrightText: 2019 Scott Shawcroft for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`adafruit_ssd1608`
================================================================================
CircuitPython `displayio` driver for SSD1608-based ePaper displays
* Author(s): Scott Shawcroft
Implementat... |
from nyr.interpreter.interpreter import Interpreter
from nyr.parser.parser import Parser
def testEmptyStatement():
ast = Parser().parse(";;")
env = Interpreter().interpret(ast)
assert env == dict()
def testInterpretMultiple():
parser = Parser()
interpreter = Interpreter()
for i in range(20):
ast = parser.... |
#!/usr/bin/env python
#
# Copying a pin is not representative of typical user behavior on Pinterest.
#
# This script is intended to demonstrate how to use the API to developers,
# and to provide functionality that might be convenient for developers.
# For example, it might be used as part of a program to generate an
# ... |
import uuid
from django.db import migrations, models
def get_token():
return str(uuid.uuid4())
def create_uuid(apps, schema_editor):
accounts = apps.get_model("account", "User").objects.all()
for account in accounts:
account.token = get_token()
account.save()
class Migration(migration... |
import sqlite3
import pathlib
import io
from PIL import Image
from get_caged.cage_image import CageImage
from get_caged.target_image import TargetImageSpec
base_path = pathlib.Path(__file__).resolve().parent
def connect():
return sqlite3.connect(base_path / "cage.db")
def dict_factory(cursor, row):
d = {... |
import time
from datetime import datetime, timedelta
import pandas as pd
import json
import datetime as dt
from dateutil.parser import parse
pd.set_option('mode.chained_assignment', None)
class Collector():
def __init__(self, src, des, table, src_type, date_format, selected_time, selected_columns="all", dcpm=Non... |
from unittest import TestCase
from src.leilao.dominio import Usuario, Lance, Leilao
from src.leilao.exception import LanceInvalido
class TestLeilao(TestCase):
def setUp(self): # método do framework para criar o cenário de teste
self.user = Usuario("Matheus", 500)
self.lance_matheus = ... |
#!/usr/bin/python3
"""Script to invoke emacs on currently branched files in a git repo.
Invokes Emacs on the current set of files in a private branch.
Sets GOROOT if this looks like a GO root repository.
"""
import getopt
import os
import re
import sys
import script_utils as u
# Echo command before executing
flag... |
import matplotlib
from PyQt5.QtWidgets import QHBoxLayout, QPushButton, QWidget, QVBoxLayout, QLabel, QCheckBox
from PyQt5.QtCore import Qt
from models.data_key import DataKey
import numpy as np
matplotlib.use('QT5Agg')
import matplotlib.pyplot as plt
from utils import ui_utils
class StandardLineWidget(QWidget):
... |
from FUNReader import read_fun_file_as_list_of_lists
from VARReader import read_var_file_as_dictionary
from BestsTool import create_best_fun_seq_files
from Medians import create_seq_with_values_on_median_files
def main():
fun = read_fun_file_as_list_of_lists("Resources/FUN.BB12044.tsv")
var = read_var_file_as... |
"""Cache management on Firebase Hosting.
Cloud Run response caching on Firebase Hosting.
https://firebase.google.com/docs/hosting/manage-cache
"""
from dataclasses import dataclass
@dataclass
class CacheControl:
"""Cache-Control header object.
"""
max_age: int = 0
s_maxage: int = 0
@property
... |
import tkinter
import sqlite3
from tkinter import *
from Welcome_ui import Welcome
from tkinter import messagebox
class CustomWelcome(Welcome):
print("Welcome Window Opened.")
pass
def about_command(self):
print("About Button Pressed.")
import aboutus
self.newwindow = tk... |
# Resource object code (Python 3)
# Created by: object code
# Created by: The Resource Compiler for Qt version 5.15.1
# WARNING! All changes made in this file will be lost!
from PySide2 import QtCore
qt_resource_data = b"\
\x00\x00\x07\xc5\
\x89\
PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\
\x00\x00\x0a\x00\x00\x00\x... |
from ..utils import TranspileTestCase
import unittest
def assertTokenizaton(self, source, expected):
self.assertJavaScriptExecution("""
import _compile
s = %s
tok = _compile.Tokenizer(s)
for i in range(10000):
t = tok.get_token()
if t is None:
... |
import numpy as np
import nibabel as nib
import struct
from scipy.ndimage.interpolation import zoom as zoom
from scipy.ndimage.interpolation import map_coordinates as map_coordinates
#import torch
#import torch.nn as nn
#import torch.nn.functional as F
import argparse
def main():
parser = argparse.ArgumentPar... |
import asyncio
from bot.bot import bot
from bot.constants import Client
if not Client.in_ci:
async def main() -> None:
"""Entry Async method for starting the bot."""
async with bot:
bot._guild_available = asyncio.Event()
await bot.start(Client.token)
asyncio.run(main()... |
import json
import sys
# Usage
# function run_bril -a opt_name test_name run_opt; bril2json < $test_name | if eval $run_opt; python3 ../$opt_name;
# else; cat; end | bril2txt | tee /tmp/bril_test.bril | bril2json | brili -p; cat /tmp/bril_test.bril; end
#
# function run_opt -a opt_name test_name; printf "OPT OFF:\n";... |
import speech_recognition as sr
import os
from .mute_shell import mute_on, mute_off
def recognize_speech_from_mic(recognizer, microphone):
with microphone as source:
recognizer.adjust_for_ambient_noise(source)
audio = recognizer.listen(source)
response = {
"success": True,
"erro... |
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from .models import IssueCommentLink, IssueLink
from .utils import get_backend_client
# Register your models here.
def sync_from_source(modeladmin, request, queryset):
gl = get_backend_client()
for x in queryset:
... |
# -*- coding: utf-8 -*-
import os
from django.db import models
from autenticar.models import Gauser
from entidades.models import Entidad
from gauss.funciones import pass_generator
class Categoria_objeto(models.Model):
categoria = models.CharField('Categoría', max_length=100, blank=True, null=True)
subcatego... |
import numpy as np
from array_creation import py_arrays
def number_of_axes(array):
"""
Parameters
----------
array Python array
Returns
-------
Number of axes (dimensions) of the array.
"""
return np.array(array).ndim
def shape(array):
"""
The dimension of the array is a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
"""
Alexa Config Flow.
For more details about this platform, please refer to the documentation at
https://community.home-assistant.io/t/echo-devices-alexa-as-media-player-testers-needed/58639
"""
from collections import OrderedDict
im... |
# pylint: disable=global-statement,redefined-outer-name
""" Module to wrap AWS Cognito APIs """
import json
import sys
from dataclasses import dataclass
import boto3
@dataclass(frozen=True)
class CognitoGroup:
""" Class for AWS Cognito group """
name: str
description: str
@dataclass(frozen=True)
class... |
import aspose.email
from aspose.email.clients.imap import ImapClient
from aspose.email.clients import SecurityOptions
def run():
#ExStart: SSLEnabledIMAPServer
client = ImapClient("imap.domain.com", 993, "user@domain.com", "pwd")
client.security_options = SecurityOptions.SSLIMPLICIT
#ExEnd:SSLE... |
import click
from do_cli.contexts import CTX
@click.command('flush-cache')
@CTX
def cli(ctx):
"""
clear the cache
"""
if ctx.verbose:
click.echo("clear the cache")
ctx.cache.flushdb()
if ctx.verbose:
click.echo('---- cmd_flush-cache done ----')
|
import sys, os
import params
#This sets the path in our computer to where the eyetracker stuff is located
#sys.path.append('/Users/Preetpal/desktop/ubc_4/experimenter_platform/modules')
#sys.path.append('E\\Users\\admin\\Desktop\\experimenter_platform\\modules')
sys.path.append(os.path.join(sys.path[0],'Modules'))
sys... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from .views import hello, inbound_route
urlpatterns = patterns('',
url(r'^hello$', hello),
url(r'^inbound$', inbound_route)
)
|
from model import exercise, exercise_step
from music_theory import chord, position
from practice import abstract_practice
class ScaleOnChord(abstract_practice.AbstractPractice):
_TITLE = "Scale on chord"
_SUBTITLE = "Play a scale on top of chord"
def get_exercise(self, quantity: int) -> exercise.Exercis... |
import torch
from torch import nn
def wrapmodel(model, loss_fn, sample_spec):
if isinstance(model, nn.DataParallel):
return nn.DataParallel(WrappedModel(
model.module, loss_fn, sample_spec)).cuda()
else:
return WrappedModel(model, loss_fn, sample_spec)
cla... |
#!/usr/bin/env python
"""Machine Learning Server Unit Testing."""
# System
import tempfile
import warnings
# Third Party
import unittest
from pqueue import Queue
class TestServerFailover(unittest.TestCase):
fake_requests = ["Not a real request", "Also not a real request"]
def queue_persistence(self, queue,... |
N = input()
print('SAME' if all(N[0] == n for n in N) else 'DIFFERENT')
|
#!/usr/bin/python
import sys, getopt
import argparse;
import time
import stl_path
from trex_stl_lib.api import *
H_VER = "trex-x v0.1 "
class t_global(object):
args=None;
import json
import string
ip_range = {'src': {'start': "16.0.0.1", 'end': "16.0.0.254"},
'dst': {'start': "48.0.0.1", '... |
#!/usr/bin/env python
import numpy as np
from numpy import *
import os
# pyyaml - https://pyyaml.org/wiki/PyYAMLDocumentation
import yaml
# ROS
import rospy
import rospkg
import std_msgs.msg
from std_msgs.msg import Bool
from std_msgs.msg import Header
import geometry_msgs.msg
from geometry_msgs.msg import P... |
"""Module holds tests for the orderCategory class"""
import unittest
from app.models import Database, User, orderCategory, order
from app import utilities
class orderCategoryTest(unittest.TestCase):
"""All tests for the orderCategory class"""
def setUp(self):
"""Initiates variables to be used i... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time
PATH = "/mnt/c/Users/pspan/OneDrive - Umich/Fall 2020/EECS 201/eecs201-web/test/chromedriver.exe"
DOMAIN = "https://philspan.github.io/eecs201-web/blog"
class InvalidPageError... |
"""Base module for validators."""
import abc
class ValidatorBase:
"""Base class for validators."""
@abc.abstractmethod
def validate_exists(self, config, header, directive=None, cookie=None):
"""Validates that a header, directive or cookie exists in a set of headers.
Args:
con... |
#!/usr/bin/env python
#Title: Module to facilitate Sub-Chandra processing and analysis (subchandra.py)
#Author: Adam Jacobs
#Creation Date: June 26, 2015
#Usage: load as a module
#Description: This module contains code utilized by the Sub-Chandra IPython notebooks and
# Sub-Chandra process... |
import random
import particle
def setup():
global Balls
Balls = []
for i in range (10):
Ball = particle.Particle()
Balls.append(Ball)
size(800,400)
background(0)
def draw():
background(0)
stroke(220,45,86)
global Balls
... |
"""Plugwise Climate (current only Anna) component for Home Assistant."""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.