content
stringlengths
5
1.05M
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by Jiawei Liu on 2018/06/18 import os import logging import random import argparse import numpy as np import pandas as pd import tensorflow as tf import xgboost as xgb import csv from bert import optimization from qwk import * from util import * Logger = loggin...
from alpine import APIClient from alpine.exception import * from alpine.workspace import * from .alpineunittest import AlpineTestCase class TestWorkspace(AlpineTestCase): def setUp(self): super(TestWorkspace, self).setUp() # Creating Alpine Client in setUp Function for tests global alpin...
# -*- coding: utf-8 -*- from .zappa_async import task_sns import logging logger = logging.getLogger(__name__) @task_sns def process(message): pass
# encoding=utf-8 import logging import pytest import requests from brunns.matchers.data import json_matching from brunns.matchers.html import has_title from brunns.matchers.object import between from brunns.matchers.response import is_response from contexttimer import Timer from hamcrest import assert_that, contains_s...
# -*- coding: utf-8 -*- """ Created on Sun Mar 6 15:27:04 2016 @author: alex """ from AlexRobotics.dynamic import Hybrid_Manipulator as HM from AlexRobotics.planning import RandomTree as RPRT from AlexRobotics.control import RminComputedTorque as RminCTC import numpy as np import matplotlib.pyplot a...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'object_recognition_mainwindow_ui.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWin...
# -*- coding: utf-8 -*- """ app ~~~~~ This module initializes flask app instance. Registers blueprints. """ from flask import Flask from config import config from lib import FlaskSqlSession from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative imp...
from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render, redirect from django.urls import reverse_lazy from django.views.generic import DetailView, CreateView, UpdateView from django.views import generic as views from petstagram.main.models import PetPhoto class PetPhotoDetailsVi...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django import forms from django.contrib import auth from django.contrib.auth import get_user_model from app.models import User class LoginUserForm(forms.Form): username = forms.CharField(label=u'用户名', error_messages={'required': u'用户名不能为空'}, ...
from boto.sqs.connection import SQSConnection from boto.sqs import SQSRegionInfo from django.conf import settings from django.core.cache import cache from django.core.exceptions import PermissionDenied from django.shortcuts import render_to_response from django.template import RequestContext from datetime import date...
#!/usr/bin/env python """ Usage: splitfiles.py [options] FOLD_SPEC_PREFIX STORIES_DIR OUT_FOLDER Options: -h --help Show this screen. --debug Enable debug routines. [default: False] """ import os import nltk from docopt import docopt from typing import Iterab...
# -*- coding: utf-8 -*- list1 = ["a", "b" , "c"] list2 = [1, 2, 3] list1.extend(list2) print(list1)
# -*- coding: utf-8 -*- import json from sample import constants from sample.utils.test import CustomAsyncHTTPTestCase class TestHelloHandler(CustomAsyncHTTPTestCase): def test_invalid_json(self): response = self.fetch( '/hello', method='POST', body='{[]: []}' ...
from nvdb_segment import * from geometry_basics import calc_way_length import logging _log = logging.getLogger("tags") def merge_tags(seg, src, data_src_name): way = seg.way dst = seg.tags src_date = src.get("FRAN_DATUM", 0) fixmes = [] for k, v in src.items(): if k in NVDB_GEOMETRY_TAGS ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A monkey patch to fix auto complete failed when inputs contains unicode words in zsh See https://github.com/kislyuk/argcomplete/issues/228 for the discussions """ import argcomplete from argcomplete import * def hacked_call(self, argument_parser, always_complete_optio...
from unittest import TestCase, TestSuite, TextTestRunner from cryptoMath.finiteField import FieldElement class FieldElementTest(TestCase): def test_ne(self): a = FieldElement(2, 31) b = FieldElement(2, 31) c = FieldElement(15, 31) self.assertEqual(a, b) self.assertTrue(a !...
import pytest from aoc_cqkh42.year_2019 import day_01 @pytest.mark.parametrize( 'data, answer', [('12', 2), ('14', 2), ('1969', 654), ('100756', 33583)] ) def test__fuel_needed(data, answer): assert day_01._fuel_needed(data) == answer @pytest.mark.parametrize( 'data, answer', [('14', 2), ('1969', 966),...
from collections import defaultdict from urllib.parse import quote_plus from sys import platform from time import sleep import numpy as np from selenium import webdriver from selenium.common.exceptions import WebDriverException from tspy import TSP from tspy.solvers import TwoOpt_solver addresses = """ DTU bygning 10...
# Copyright 2021 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. """Calls a function defined in rpc_client.py, which will forward the request to the test service. This command assumes the updater test service is already i...
from queue import Queue from typing import Callable, Optional from blessed import Terminal from blessed.keyboard import Keystroke from src.commands import ChangeSection, EndGame from src.sections.base import GameSection class Debug(GameSection): """A game section for debugging purposes""" def __init__(self...
"""Module door keys.""" __author__ = 'Joan A. Pinol (japinol)' from codemaster.config.constants import BM_DOOR_KEYS_FOLDER from codemaster.models.actors.actor_types import ActorCategoryType, ActorType from codemaster.models.actors.actors import ActorItem from codemaster.models.stats import Stats from codemaster.utils...
# # 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, software # distributed under ...
import PartFunc as pfunc import DaemonDownload as daemonDnl import Function as func import Search as src import FileStruct as fs import Package as pack import SocketFunc as sfunc import threading from threading import * import TextFunc as tfunc import Constant as const import os import time ###### DOWNLOAD FILE class...
#!/usr/bin/env python # # Copyright 2015 Google 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 requir...
"""Tools for loading student-submitted, maybe-invalid code from source files.""" import importlib.util import os from os.path import join as pathjoin from types import ModuleType from typing import Any, TypeVar from dill import Unpickler # type: ignore from .core import Problem Output = TypeVar("Output") class I...
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-09-21 02:37 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('questions', '0003_question_values'), ] operations = [ migrations.RemoveField( ...
import shutil import random from ngslite import read_genbank, write_genbank from locus_hunter.template import Settings from locus_hunter.add_color import ColorDictGenerator, AddColor from .tools import TestCase, setup_dir, remove_genbank_date_str class TestColorDictGenerator(TestCase): def test_set_key...
from ..constraint import AbstractConstraint import sublime class IsInSvnRepoConstraint(AbstractConstraint): """Check whether this file is in a SVN repo.""" def test(self, view: sublime.View) -> bool: view_info = self.get_view_info(view) # early return so that we may save some IO operations ...
import pytest from telegrambot.bot import ( get_user_first_name, get_chat_id, prepare_welcome_text) @pytest.fixture def update_with_expectedkey(): """ function to return an object that simulates json update po...
""" This example shows two ways to redirect flows to another server. """ from mitmproxy import http, ctx def request(flow: http.HTTPFlow) -> None: # pretty_host takes the "Host" header of the request into account, # which is useful in transparent mode where we usually only have the IP # otherwise. # if fl...
"""Module contains email handling.""" import email.message import smtplib class EmailError(Exception): """Error during email handling occurred.""" pass def send_email(conf, url): """Send the email reminder.""" try: with smtplib.SMTP(url) as s: msg = email.message.EmailMessage() ...
import itertools import os import math import random PROCESS_PER_SCRIPT = 1 def template_file(texts): text = "".join(texts) out = f"""#!/bin/bash #$ -cwd #$ -e ./logs/ #$ -o ./logs/ #$ -l vf=4G source /data/nlp/lunar_pilot_env/bin/activate echo 'Starting job' mkdir -p data mkdir -p output mkdir -p ./logs/ m...
import pymongo import os jsonfolder = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../data") def getMongoDb(): client = pymongo.MongoClient('localhost', 27017) return client.md
READY = 'READY' # Channels CHANNEL_CREATE = 'CHANNEL_CREATE' CHANNEL_UPDATE = 'CHANNEL_UPDATE' CHANNEL_DELETE = 'CHANNEL_DELETE' CHANNEL_PINS_UPDATE = 'CHANNEL_PINS_UPDATE' # Guild GUILD_CREATE = 'GUILD_CREATE' GUILD_UPDATE = 'GUILD_UPDATE' GUILD_DELETE = 'GUILD_DELETE' GUILD_BAN_ADD = 'GUILD_BAN_ADD' GUILD_BAN_REMOVE...
import sys, os import numpy as np import matplotlib.pyplot as plt from sympy import Symbol from sympy.solvers import solve from scipy.optimize import linprog x1 = np.linspace(-1, 20, 100) f1 = lambda x1: 12.0 - 6.0 * x1 f2 = lambda x1: 7.0 - 1.5 * x1 x = Symbol("x") y1, = solve(f1(x) - f2(x)) y2, = solve(f2(...
class Solution: def reverse(self, x: int) -> int: if x > 0: rev = int(str(x)[::-1]) elif x < 0: rev = -1 * int(str(x * -1)[::-1]) upper_bound = 2**31 - 1 lower_bound = -2**31 if rev not in range(lower_bound, upper_bound): ...
#! /usr/bin/env python import os, sys, glob from os.path import join, isdir, basename from optparse import OptionParser if __name__=='__main__': if len(sys.argv) < 3: print 'usage: %s <patterns separated by file seps> <dir paths separated by file seps>' \ % basename(sys.argv[0]) sys.exit(1) patterns = sys.ar...
import hashlib from io import StringIO from functools import lru_cache from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from pdfminer.pdfpage import PDFPage from unidecode import unidecode from .Cache import cachedR...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import dataset_utils as du from skmultilearn.adapt import MLkNN import numpy as np from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences import os import sys MAX_NB_WORDS =20000 def tokenize_data(X): tokenizer = Token...
""" THIS IS A MORE FEATUREFUL CUSTOM ALGORITHM to provide a skeleton to develop your own custom algorithms. The algorithm itself, although viable, is not recommended for production or general use, it is simply a toy algorithm here to demonstrate the structure of a more complex custom algorithm that has ``algorithm_par...
# Ctrl+K+C to comment a line, Ctrl+K+U to uncomment a line # input function always returns strings # To get current date and time we need to use the datetime library from datetime import datetime, timedelta # The now cuntion returns a datetime object Today = datetime.now() print("Today is " + str(Today)) one_day = time...
#!/usr/bin/python """ *Very* simple tool to pretty-print JSON data. It's primary use is to pipe in the output of ``curl``. For example:: curl -H "Accept: application/json" -X GET http://url/ | jsonf or, with headers:: curl -i -H "Accept: application/json" -X GET http://url/ | jsonf Handling headers is *very*...
from scheme.exceptions import * from scheme.field import * __all__ = ('Boolean',) class Boolean(Field): """A field for boolean values.""" basetype = 'boolean' equivalent = bool errors = [ FieldError('invalid', 'invalid value', '%(field)s must be a boolean value'), ] def _validate_va...
""" This example demonstrates SQL Schema generation for each DB type supported. """ from tortoise import fields from tortoise.fields import SET_NULL from tortoise.models import Model class Tournament(Model): tid = fields.SmallIntField(pk=True) name = fields.CharField(max_length=100, description="Tournament n...
from arrays.max_consecutive_ones import max_consecutive_ones def test_max_consecutive_ones(): assert max_consecutive_ones([1, 1]) == 2 assert max_consecutive_ones([1, 1, 0, 1, 1, 1]) == 3 assert max_consecutive_ones([1, 1, 0, 0, 1, 1]) == 2 assert max_consecutive_ones([0, 1, 1, 1, 1, 0, 1, 1, 1, 0]) ...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # OpenStack Monitoring # Copyright (C) 2015 Tobias Urdin # 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...
# -*- coding: utf-8 -*- import os from dotenv import load_dotenv class Config: def __init__(self, dotenv_path=".env"): load_dotenv(dotenv_path) def get(self, key): value = os.environ.get(key) if value is None: raise Exception return value
# Copyright (c) 2018 Ultimaker B.V. # Cura is released under the terms of the LGPLv3 or higher. import json import math import os import unicodedata from typing import Dict, List, Optional, TYPE_CHECKING from PyQt5.QtCore import QObject, pyqtSignal, pyqtProperty, pyqtSlot from UM.Logger import Logger from UM.Qt.Dura...
# Copyright (c) 2019-2021 CRS4 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribut...
# Getting Started # Try typing print('this is a test, this is only a test') # in the REPL and you should see it printed as a reply. #You can type math - try 2 + 2 # If you type more than one line, spaces are important - for instance if you define a function: def Tell(): print('more testing') # and then call th...
#!/usr/local/bin/python from mqtt_fiware_bridge import MFB class MockBridge(MFB.MqttFiwareBridge): def __init__(self, **kwargs): super(MockBridge, self).__init__(**kwargs) def do_something(self, message): self.log.info(f"Printing validated message from {__name__}") print(f"Voila: {m...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Ajusta as isntru��es SQL dos programas COBOL convertido pelo EASY2COB para todos os programs do diret�rio no properties ['DIRSOUPGM'] com a exten��o ['EXTSOU'] 'pathProp.txt' default do diret�io do properties ''' import os import ConfigParser from collections import ...
from collections import Counter, defaultdict class Solution: def frequencySort(self, s: str) -> str: return self.counter_soln(s) def defaultdict_soln(self, s: str) -> str: """ Runtime: O(nlogn) Space: O(n) """ scounter = defaultdict(int) for char in s: ...
# # Copyright 2020 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...
from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse from google_address.models import Address from jobboard.handlers.oracle import OracleHandler from users.utils import company_member_role class Company(models.Model): contract_address = models.CharField(max...
from proto import FieldType, Message, serializable, field @serializable() @field('message', FieldType.String) class ErrorMessage(Message): def __init__(self, message=''): self.message = message def repr(self): return '%s(%s)' % (self.__class__.__name__, self.message)
from keras.layers import GlobalAveragePooling2D, Multiply, Dense from keras import backend as K def SqueezeExcite(x, ratio=16, name=''): nb_chan = K.int_shape(x)[-1] y = GlobalAveragePooling2D(name='{}_se_avg'.format(name))(x) y = Dense(nb_chan // ratio, activation='relu', name='{}_se_dense1'.format(name)...
import pytest from lib.utils.merge_dict import merge_dict def test_merge_dict(): dict1 = {1: 'apple', 2: 'ball'} dict2 = {'name':'Jack', 'age': 26, 'phone': ['number1', 'number2']} output_dict = merge_dict(dict1, dict2) expected_dict = {'name':'Jack', 'age': 26, 'phone': ['number1', 'number2'], 1: 'app...
from .utils.fixtures import user_validator from .utils.validator_functions import TestValidators def test_field_validator_functions(user_validator): """ This test makes sure that the defined functions are present. Note: Unfortunately for our dynamic functions like `is_gt_than` we can't ch...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ DEVELOPMENT SERVER ------------------ Simple development server. Copyright (c) 2014 Teun Zengerink Licensed under MIT License. See: https://raw.github.com/Mytho/groceries/master/LISENCE.md """ import os import sys sys.path.append(os.path.abspat...
from mrhttp import app @app.route('/') def hello(r): if r.file == None: return "No file uploaded" #for f in r.files: #print(f) name = r.file['name'] typ = r.file['type'] body = r.file['body'] return name app.run(cores=4) # curl -i -X POST -F "data=@14_upload.py" http://localhost:8080/
from binaryninja import * import base64 import copy import json def falcon_export(bv) : filename = interaction.get_save_filename_input("Filename for Binja export") segments = [] for segment in bv.segments : segments.append({ 'address': segment.start, 'bytes': base64.b64enc...
from OpenGL.raw.osmesa._types import * from OpenGL.raw.osmesa.mesa import *
import schedules import weather import email_handler def main(): # introduce our variables from our modules emails = email_handler.get_emails() schedule = schedules.get_schedule() forecast = weather.get_weather_forecast() # send the emails with schedule and forecast included. try: ...
# Generated by Django 3.0.5 on 2020-05-02 06:46 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('app_backend', '0010_businessmodel_code'), ('app_sme12', '0007_auto_20200428_1731'), ] operations = [ ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ .. Licence MIT .. codeauthor:: Jan Lipovský <janlipovsky@gmail.com>, janlipovsky.cz """ import pytest @pytest.mark.parametrize("text, expected", [ (r"{\url{http://www.google.com}}", ["http://www.google.com"]), (r"{\url{http://www.google.com/file.pdf}}", ...
#!/usr/bin/env python3 # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import logging import click import json from services import PredictDoc from dotenv import load_dotenv load_dotenv() @click.command() @click.option('-d','--doctype', prompt='Document Type Label', ...
from talon.mac import applescript from talon import Context, Module import os mod = Module() @mod.action_class class SystemPreferencesActions: def bluetooth_focus(): """Focuses on Bluetooth preferences""" applescript.run(r"""tell application "System Preferences" reveal pane "com.apple.pr...
#coding:utf-8 import numpy as np from scipy.linalg import norm import cvxopt import cvxopt.solvers from pylab import * """ 非線形SVM cvxoptのQuadratic Programmingを解く関数を使用 """ N = 100 # データ数 P = 3 # 多項式カーネルのパラメータ SIGMA = 5.0 # ガウスカーネルのパラメータ # 多項式カーネル def polynomial_kernel(x, y): return (1 + np.d...
# Copyright (c) 2021 PPViT 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 applicable ...
import click from mlsteam import version from .api import MyelindlApi, MyelindlApiError @click.command() def info(): try: api = MyelindlApi() server_ver = api.version() click.echo("Version: {}".format(version.__version__)) click.echo("Server: {}".format(api.host)) click.ech...
# -*- coding: utf-8 -*- import json, os README_URL = os.environ['CLLNMBR__DOCS_URL'] # LEGIT_USER = os.environ['CLLNMBR__LEGIT_USER'] # LEGIT_USER_PASSWORD = os.environ['CLLNMBR__LEGIT_USER_PASSWORD'] # LEGIT_GROUPER_GROUPS = json.loads( os.environ['CLLNMBR__LEGIT_GROUPS_JSON'] ) # LEGIT_EPPNS = json.loads( os.en...
from flask import render_template, redirect, url_for, flash, request from werkzeug.urls import url_parse from flask_login import login_user, logout_user, current_user from flask_babel import _ from app import db from app.auth import bp from app.auth.forms import LoginForm, RegistrationForm, \ ResetPasswordRequestFo...
# This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey has `on_delete` set to the desired behavior. # * Remove `managed = False` lines if ...
from channels.routing import route from OpsManage.djchannels import wssh,notices,chats # The channel routing defines what channels get handled by what consumers, # including optional matching on message attributes. In this example, we route # all WebSocket connections to the class-based BindingConsumer (the consumer #...
""" Amatino API Python Bindings Global Unit Module Author: hugh@amatino.io """ from amatino.session import Session from amatino.denomination import Denomination from amatino.internal.url_target import UrlTarget from amatino.internal.url_parameters import UrlParameters from amatino.internal.api_request import ApiRequest...
import time from collections import Counter, defaultdict from math import ceil start = time.time() with open("14.txt") as f: rawInput = f.read().splitlines() # part 1 curTemplate = list(rawInput[0]) rules = {} for rule in rawInput[2:]: k, v = rule.split(" -> ") rules[k] = v for _ in range(10): new...
import threading, time, config, measure, readht, readdust, requests, json, Queue from datetime import datetime #import urllib2 class Scheduler: SENSOR = 22 PIN = 4 interval = 0 lock = "" config_obj = "" measure_obj = "" def __init__(self, interval): self.interval...
import os import sys sys.path.append(os.path.abspath(os.path.join(__file__, "../../.."))) import argparse import json import parameters import utils.log as log FAILED_COUNT = 0 PASSED_COUNT = 0 FAILED_COMMANDS = [] PASSED_COMMANDS = [] def exec_cmd(args): rc = cli.rbd.exec_cmd(args) if rc is False: ...
# System documented in https://zulip.readthedocs.io/en/latest/subsystems/logging.html from django.utils.timezone import now as timezone_now from django.utils.timezone import utc as timezone_utc import hashlib import logging import re import traceback from typing import Optional from datetime import datetime, timedelt...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ """ from click.testing import CliRunner from BioCompass import cli def test_importcli(): runner = CliRunner() result = runner.invoke(cli.main) assert result.exit_code == 0 #assert 'BioCompass.cli.main' in result.output help_result = runner.invoke(c...
#!/usr/bin/env python import argparse import numpy as np # parse command line options parser = argparse.ArgumentParser(description="Creates a body with uniform segment lengths from a given body input", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--ds", type=float, dest="ds", help="segm...
"""Test agrirouter/revoking/parameters.py""" from agrirouter import RevokingParameter from tests.constants import application_id class TestRevokingParameter: content_type = "json" account_id = "111" endpoint_ids = "endpoint_1" time_zone = "+03:00" utc_timestamp = "01-01-2021" test_object = Re...
# Mathias Punkenhofer # code.mpunkenhofer@gmail.com # from .board import GuiBoard
# Copyright 2019 Google LLC. 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 applicable law or a...
import io import os import logging import datetime from mproxy.core.model import CmdResult from .throttle import ThrottlableMixin, throttle from .job_status import JobStatus from subprocess import Popen, PIPE import tempfile log = logging.getLogger(__name__) class OpenSSHMachineConnection(ThrottlableMixin): """Pe...
import requests import bs4 from .notloggedinexception import NotLoggedInException class Session: BASE_URL = 'https://sds.smus.ca/index.php' PAGE_PARAMS = { 'login': {'next_page': 'login.php'}, 'student_information': {'next_page': 'student_sds/student_information.php'}, 'course_summar...
from mypy import moduleinfo from mypy.myunit import ( Suite, assert_equal, assert_true, assert_false ) class ModuleInfoSuite(Suite): def test_is_in_module_collection(self) -> None: assert_true(moduleinfo.is_in_module_collection({'foo'}, 'foo')) assert_true(moduleinfo.is_in_module_collection({'...
from app.doc import JWT_ACCESS_TOKEN, parameter FACILITY_REPORT_POST = { 'tags': ['Report'], 'description': '시설고장신고', 'parameters': [ JWT_ACCESS_TOKEN, parameter('room', '호실 번호', type_='int'), parameter('content', '시설 고장 신고 내용') ], 'responses': { '201': { ...
# Copyright 2017 <thenakliman@gmail.com> # # 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...
from unittest.mock import patch from django.test import TestCase from django.contrib.auth import get_user_model from core import models def sample_user(email='testuser@gmail.com',password='user1234'): """create a sample user""" return get_user_model().objects.create_user(email,password) class ModelTests(Tes...
from collections import OrderedDict import torch import torch.nn as nn from torch.optim import lr_scheduler from torch.optim import Adam from torch.nn.parallel import DataParallel # , DistributedDataParallel from models.select_network import define_G from models.model_base import ModelBase from models.network_sr impo...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ annom.errors This module holds project defined errors Author: Jacob Reinhold (jacob.reinhold@jhu.edu) Created on: Mar 11, 2018 """ class AnnomError(Exception): pass
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """FAT and BPB parsing for files.""" import errno import itertools import math import struct import threading import warnings from contextlib import contextmanager from io import BufferedReader, open from typing import Union from pyfatfs import FAT_OEM_ENCODING, _init...
from django.views.generic import base from rest_framework import routers from api.base.auth.viewsets import ( RegisterViewsets, LoginViewsets ) from api.base.products.viewsets import ( ProductViewsets ) router = routers.DefaultRouter() router.register('auth/register', RegisterViewsets, basename='register-v...
import argparse import os import cv2 from CountsPerSec import CountsPerSec from VideoGet import VideoGet from VideoShow import VideoShow def putIterationsPerSec(frame, iterations_per_sec): """ Add iterations per second text to lower-left corner of a frame. """ cv2.putText(frame, "{:.0f} iterations/sec...
import json import logging import os from curation_utils import scraping logging.basicConfig( level=logging.DEBUG, format="%(levelname)s:%(asctime)s:%(module)s:%(lineno)d %(message)s") configuration = {} with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'local_config.json'), 'r') as handle:...
#! /usr/bin/env python2 ''' Register a mDNS/DNS-SD alias name for your computer using the Avahi daemon This script will register an alternate CNAME alias besides your hostname, which could be useful for ex. when serving several http virtual hosts to your ffriends on the local network and you don't want to make them c...
default_app_config = 'workflow.apps.WorkflowAppConfig'
from twilio.rest import TwilioRestClient # put your own credentials here ACCOUNT_SID = 'ACCOUNT DATA' AUTH_TOKEN = 'ACOUNT DATA' client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) client.messages.create( to = 'TO_NUMBER', from_ = 'FROM_NUMBER', body = 'MESSAGE', )