code
stringlengths
1
199k
from __future__ import division, print_function, absolute_import import numpy as np from numpy import (abs, asarray, cos, exp, floor, pi, sign, sin, sqrt, sum, size, tril, isnan, atleast_2d, repeat) from numpy.testing import assert_almost_equal from .go_benchmark import Benchmark class CarromTable(Be...
import jwt from flask import url_for from app import db, bcrypt, app from sqlalchemy.dialects.postgresql import JSON from datetime import datetime, timedelta class Incident(db.Model): __tablename__ = "incidents" id = db.Column('id', db.Integer, primary_key=True) title = db.Column('title', db.Unicode) #stri...
""" kaoru.commands.hibernate ~~~~~~~~ /hibernate command implementation :copyright: (c) 2015 by Alejandro Ricoveri :license: MIT, see LICENSE for more details. """ import re from .. import config from .. import utils from ..procutils import proc_exec_async, proc_select from . import bot_command @bot_command def _cmd_ha...
""" Django settings for tv_show_fetcher project. Generated by 'django-admin startproject' using Django 1.8.7. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ import o...
current_n = '1113222113' for n in xrange(40): current_count = 0 next_n = '' prev_d = current_n[0] for i,d in enumerate(current_n): if d == prev_d: current_count += 1 if i == len(current_n)-1: next_n += str(current_count) + prev_d else: next_n += str(current_count) + prev_d current_count = 1 p...
from django import template from ..models import Content, Entry register = template.Library() @register.assignment_tag() def content(slug): return Content.objects.get(translations__slug=slug) @register.assignment_tag() def entries(): return Entry.objects.all() @register.assignment_tag() def random_item(items): ...
from setuptools import setup setup( name="witchcraft", version="0.2", description='', author='Peter Facka', author_email='pfacka@trackingwire.com', url='https://github.com/trackingwire/witchcraft', packages=[ 'witchcraft', ], zip_safe=False, install_requires=[ 'psycopg2>...
from game.ai.defence.yaku_analyzer.yaku_analyzer import YakuAnalyzer class YakuhaiAnalyzer(YakuAnalyzer): id = "yakuhai" def __init__(self, enemy): self.enemy = enemy def serialize(self): return {"id": self.id} def is_yaku_active(self): return len(self._get_suitable_melds()) > 0 ...
""" Access UCSC data stored locally. """ from Bio import SeqIO from Bio.Alphabet import generic_dna import gzip, os, logging logger = logging.getLogger(__name__) ucsc_data_dir = "/home/john/Data/UCSC" def full_path(filename): "@return: The full path for the filename." return os.path.join(ucsc_data_dir, filename...
""" gae-init ~~~~~~~~ Google App Engine with Bootstrap, Flask and tons of other cool features. https://github.com/gae-init http://gae-init.appspot.com Copyright (c) 2012-2015 by Panayiotis Lipiridis. License MIT, see LICENSE for more details. """ __version__ = '2.1.5'
from .. import Provider as PhoneNumberProvider class Provider(PhoneNumberProvider): # Currently this is my own work formats = ( '+62-##-###-####', '+62-0##-###-####', '+62 (0##) ### ####', '+62 (0##) ###-####', '+62 (##) ### ####', '+62 (##) ###-####', '+6...
""" Django settings for volttron project. Generated by 'django-admin startproject' using Django 1.10.2. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os BA...
import constants import time import requests state = 2 old_state = 2 def what_lights(): response = requests.get(constants.url, headers=constants.headers) sessions = response.json() children = sessions["_children"] for child in children: if child['_elementType'] == 'Video': subchildre...
"""Family module for OpenStreetMap wiki.""" from __future__ import absolute_import, division, unicode_literals from pywikibot import family class Family(family.SingleSiteFamily): """Family class for OpenStreetMap wiki.""" name = 'osm' domain = 'wiki.openstreetmap.org' code = 'en' def protocol(self, ...
import os from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy, Model from flask.ext.cache import Cache from flask.ext.sqlalchemy_cache import CachingQuery app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db' app.config['DEBUG'] = True app.config['CACHE_TYPE'] = 'memcached...
''' Created on Apr 14, 2017 @author: zheyuan ''' conf_left_joy = 0 conf_right_joy = 1 conf_xbox = 2 conf_rightFrontBaseTalon = 1 conf_rightRearBaseTalon = 3 conf_leftFrontBaseTalon = 2 conf_leftRearBaseTalon = 4 conf_shifterSolenoid1 = 0 conf_shifterSolenoid2 = 1 conf_liftSolenoid1 = 2 conf_liftSolenoid2 = 3 conf_esop...
import sys, os try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages install_requires=[ "TurboGears2 >= 2.1.4", "tgext.pluggable" ] here = os.path.abspath(os.path.dirname(__file__)) tr...
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class PaginationConfig(AppConfig): name = 'refarm_pagination' verbose_name = _('refarm_pagination')
import os import traceback def getTracebackStr(): lines = traceback.format_exc().strip().split('\n') rl = [lines[-1]] lines = lines[1:-1] lines.reverse() nstr = '' for i in range(len(lines)): line = lines[i].strip() if line.startswith('File "'): eles = lines[i].strip().split('"') basename = os.path.base...
""" This module contains the main execution functionality for Reaction Mechanism Generator (RMG). """ import os.path import sys import logging import time import shutil import numpy import gc import copy from copy import deepcopy from rmgpy.constraints import failsSpeciesConstraints from rmgpy.molecule import Molecule ...
from django.contrib import admin from models import * admin.site.register(OrganizacionEstudiantil) admin.site.register(Miembro) admin.site.register(DatosBancarios) admin.site.register(Comite)
''' Created by: Juan Sarria March 15, 2016 ''' import pandas as pd, numpy as np, fiona, timeit from geopy.distance import vincenty from shapely import geometry from utilities import utm_to_latlong, latlong_to_utm from __builtin__ import False from pandas.core.frame import DataFrame PROJECT_ROOT = '../' def main(): ...
import sys from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtGui import QPainter from PyQt5.QtGui import QPixmap from PyQt5.QtWidgets import * from PyQt5.QtCore import * windowSizeX = 440 windowSizeY = 250 userName = 'Aperture' fontMajor = "Arial" fontMinor = "Dotum" class Form(QWidget): # __init__ : 생성자 ...
import bcrypt from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.exc import OperationalError, ProgrammingError from sqlalchemy.pool import NullPool from scoring_engine.config import config from scoring_engine.models.base import Base def delete_db(session): B...
import requests class PublicClient(object): def __init__(self): super(PublicClient, self).__init__() self.base_url = "https://api.kraken.com/0/public" def _url_for(self, path): return "%s/%s" % (self.base_url, path) @classmethod def _get(cls, url, params=None): try: ...
from gcsa.reminders import Reminder, EmailReminder, PopupReminder from .base_serializer import BaseSerializer class ReminderSerializer(BaseSerializer): type_ = Reminder def __init__(self, reminder): super().__init__(reminder) @staticmethod def _to_json(reminder: Reminder): return { ...
from inspect import getmro from io import BytesIO from xml.etree.ElementTree import Element, ElementTree, fromstring, SubElement from iris_sdk.models.maps.base_map import BaseMap from iris_sdk.utils.rest import HTTP_OK from iris_sdk.utils.strings import Converter BASE_MAP_SUFFIX = "Map" BASE_PROP_CLIENT = "client" BASE...
''' Dummy NFC Provider to be used on desktops in case no other provider is found ''' from electrum_dgb_gui.kivy.nfc_scanner import NFCBase from kivy.clock import Clock from kivy.logger import Logger class ScannerDummy(NFCBase): '''This is the dummy interface that gets selected in case any other hardware interfa...
import datetime from beancount.loader import load_string from fava.core.misc import sidebar_links from fava.core.misc import upcoming_events def test_sidebar_links(load_doc): """ 2016-01-01 custom "fava-sidebar-link" "title" "link" 2016-01-02 custom "fava-sidebar-link" "titl1" "lin1" """ entries, _,...
import unittest import time from should_dsl import should from fluidity import StateMachine, transition, state class FluidityState(unittest.TestCase): def test_it_defines_states(self): class MyMachine(StateMachine): state('unread') state('read') state('closed') ...
import os import subprocess import time import sys from lib.core.revision import getRevisionNumber VERSION = "1.0" REVISION = getRevisionNumber() VERSION_STRING = "zerosacn/%s%s" % (VERSION, "-%s" % REVISION if REVISION else "-nongit-%s" % time.strftime("%Y%m%d", time.gmtime(os.path.getctime(__file__)))) IS_WIN = subpr...
from OpenGL import GL from cocos.director import director from .node import GUINode def _anchor_to_position_a(anchor, window_size, self_size): abs_anchor = abs(anchor) if isinstance(abs_anchor, int): result = abs_anchor elif isinstance(abs_anchor, float): result = int(window_size * abs_anchor) # TODO px...
from __future__ import unicode_literals import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('classes', '0005_auto_20160915_1227'), ] operations = [ migrations.AddField( model_name='classsession', name='sess...
from ...maths import Vector2D from ...core import globalSystem from ..utils import getDirectionOrAngle from ..core import * from .core import PathElement from .common import * _INF = float('inf') class LinearPathElement(AcceleratableElement): """ A PathElement that represents linear motion. """ def initialize(sel...
import logging import os import sys import pkg_resources import shutil from threading import Timer from device import Device from app import App from env_manager import AppEnvManager from input_manager import InputManager from droidbox_scripts.droidbox import DroidBox class DroidBot(object): """ The main class ...
""" This module contains data-types and helpers which are proper to the SNMP protocol and independent of X.690 """ from typing import Any, Iterator, Union from x690.types import ObjectIdentifier, Type # type: ignore from puresnmp.typevars import PyType ERROR_MESSAGES = { 0: "(noError)", 1: "(tooBig)", 2: "...
import cv2 from matplotlib import pyplot as plt img_file_path = "./img/Lenna.png" img = cv2.imread(img_file_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # para converter para GRAY <<<<<<<<<<<<<<<<<< img_blur = cv2.blur(img, (3,3)) img_gauss = cv2.GaussianBlur(img,(11,11), 1) sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,k...
import re AS = open('corpus/pre-identification/Amar-Suen_6/Amar-Suen-6_cdli.txt', 'r') SH = open('corpus/pre-identification/Shulgi_42/Shulgi_42_cdli.txt', 'r') years = open('yearsList.txt', 'w') asyears = set([]) shyears = set([]) year = re.compile(r'^[0-9]+\. (mu[#| ].*)') for line in SH: s = year.search(line) if s:...
import argparse import concurrent.futures import datetime import json import boto3 SFN = boto3.client('stepfunctions') def format_date_fields(obj): for key in obj: if isinstance(obj[key], datetime.datetime): obj[key] = obj[key].isoformat() return obj def get_execution_details(execution_arn):...
from setuptools import setup, find_packages import visitingTimes setup( name='visitingTimes', version=visitingTimes.__version__, author='', author_email='', packages=find_packages(exclude=['test']), description='Museum Visiting Times', long_description=open('README.md').read(), url='', )
import argparse import pdb import traceback from typing import List, Tuple def test_ip(ip: int, rules: List[Tuple[int, int]], max_addr: int) -> bool: for (start, end) in rules: if start <= ip <= end: break else: if ip < max_addr: return True return False def solve(rul...
from Classes import * def test_ia(): f1 = FichedeScore() cpu1 = CPU() cpu1.jouer(f1) def repeat(times): for i in range(times): test_ia() repeat(100)
import cgt, numpy as np class ParamCollection(object): """ A utility class containing a collection of parameters which makes it convenient to write optimization code that uses flat vectors """ def __init__(self,params): #pylint: disable=W0622 """ params should be a list of cgt nodes ...
''' There are some scripts and utilities out there which can't handle genes with multiple mRNA children. This script splits each of these (and children) and instead creates new gene features. The ID of the newly-generated gene feature duplicates the source one but with the suffix "_N" added, where N increases from 2.....
"""Test cltk.stem.""" __author__ = 'Kyle P. Johnson <kyle@kyle-p-johnson.com>' __license__ = 'MIT License. See LICENSE.' from cltk.corpus.utils.importer import CorpusImporter from cltk.stem.latin.j_v import JVReplacer from cltk.stem.latin.stem import Stemmer from cltk.stem.lemma import LemmaReplacer from cltk.stem.lati...
""" Program : checkData.py Author : Jigar R. Gosalia Verion : 1.0 Course : CSC-620 - Programming Language Theory Prof. : Richard Riele Validates given data against pre-defined validators using regular expressions. """ import re import os from datetime import datetime """ Very crude level of regular expressio...
"""Color cycles for maximum contrast/viewability. Author: Seth Axen E-mail: seth.axen@gmail.com""" from collections import OrderedDict MAX_CONTRAST_COLORS = OrderedDict([ # best colors to use ((1.000, 0.702, 0.000), 'vivid_yellow'), ((0.502, 0.243, 0.459), 'strong_purple'), ((1.000, 0.408, 0.000), 'vivi...
""" Create a new users file. To use this, run the code and then use the `newusers` command to add these to an AWS instance. """ import argparse from random import shuffle __author__ = 'Rob Edwards' if __name__ == "__main__": parser = argparse.ArgumentParser(description=' ') parser.add_argument('-b', '--base', h...
import chainer import chainer.functions as F import chainer.links as L from chainer import cuda def init_conv(array): xp = cuda.get_array_module(array) array[...] = xp.random.normal(loc=0.0, scale=0.02, size=array.shape) def init_bn(array): xp = cuda.get_array_module(array) array[...] = xp.random.normal...
from nose.tools import raises import unittest from victor.exceptions import FieldRequiredError from victor.transform import Transformer from victor.vector import StringField, Vector class TransformerTestCase(unittest.TestCase): def test_transformer_name(self): """ Test that a transformer can return ...
from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * def get_unspent(listunspent, amount): for utx in listunspent: if utx['amount'] == amount: return utx raise AssertionError('Could not find unspent with amount={}'.format(amount)) class RawTransact...
''' Author: Robert Post This class encompases the functionality to run a Deep Q Network agent as outlined in: Human-level control through deep reinforcement learning. Nature, 518(7540):529-533, February 2015 ''' import sys import copy import os import cPickle import time import logging import random import numpy as np ...
import requests class PushPipeline(object): """ Notify to the push service that a new strip so pushd will notify to all the interested users """ def process_item(self, item, spider): key = item['comic'] msg = "There is a new strip " + key data = { "msg": msg, ...
import os import pprint import shutil import sys import tempfile import webbrowser import ioJSON from networkx.readwrite.json_graph import node_link_data _excluded_node_data = set([ 'pa_object', ]) _excluded_link_data = set([ 'sexpr', 'dexpr', ]) _excluded_tooltip_data = set([ 'short', 'comp', '...
import ConfigParser import os import skysurvey from skysurvey.new_config import SYS_CFG_FNAME __ALL__ = ['plot_dir', 'grid_dir', 'table_dir'] _sysConfig_fh = os.path.join(os.path.dirname( os.path.realpath(skysurvey.__file__)), SYS_CFG_FNAME) _SysConfig = ConfigParser.ConfigParser() _SysConfig.read(_sysConfig_fh) co...
""" invdisttree.py: inverse-distance-weighted interpolation using KDTree fast, solid, local """ from __future__ import division import numpy as np from scipy.spatial import cKDTree as KDTree # http://docs.scipy.org/doc/scipy/reference/spatial.html __date__ = "2010-11-09 Nov" # weights, doc class Invdisttree: ...
import ts3 #teamspeak library import time #time for sleep function import re #regular expressions import TS3Auth #includes datetime import import sqlite3 #Database import os #operating system commands -check if files exist import datetime #for date strings import configparser #parse in configuration import ast #eval a ...
""" Implements a feature set based off of dictionary lookup. .. autoclass:: revscoring.languages.features.Dictionary :members: :member-order: bysource Supporting classes ------------------ .. autoclass:: revscoring.languages.features.dictionary.Revision :members: :member-order: bysource .. autoclass:: r...
from insulaudit.log import io, logger as log from insulaudit import lib, core import time STX = 0x02 ETX = 0x03 TIMEOUT = 0.5 RETRIES = 3 """ Bit 7 Unused Bit 6 Unused Bit 5 Unused Bit 4 More Bit 3 Disconnect Bit 2 Acknowledge Bit 1 E Bit 0 S """ def ls_long( B ): B.reverse( ) return lib.BangLong( B...
import random from unittest.mock import patch from nose.tools import assert_equal from pyecharts import options as opts from pyecharts.charts import Scatter3D from pyecharts.faker import Faker @patch("pyecharts.render.engine.write_utf8_html_file") def test_scatter3d_base(fake_writer): data = [ [random.randi...
import sys import os import errno from datetime import datetime from enum import Enum from threading import current_thread import re from occacc.config import ERROR_DIR class ErrorMessage(object): def __init__(self, src, short, long): self.src = src self.short = short self.long = long class ...
class SearchOption(object): """a class to encapsulate a specific command line option""" __slots__ = ['shortarg', 'longarg', 'desc', 'func'] def __init__(self, shortarg: str, longarg: str, desc: str, func): self.shortarg = shortarg self.longarg = longarg self.desc = desc self....
import logging import ovh from adapter import Adapter log = logging.getLogger(__name__) class OvhAdapter(Adapter): def __init__(self): self.endpoint = None self.application_key = None self.application_secret = None self.consumer_key = None self.client = None def setup(sel...
import random class distance(): def __init__(self): self.distances = { 1:0, 2:0, 3:0, 4:0 } def setup(self): pass def get_distance_all(self): for sensor in range(1,5): distance = random.randint(1,50) ...
from django.contrib import admin from .models import Autotag class AutotagAdmin(admin.ModelAdmin): list_display = ("pk", "owner",) search_fields = ["pattern"] admin.site.register(Autotag, AutotagAdmin)
""" WSGI config for holidays project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` ...
""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ import pytest import simplesqlite as sqlite from tabledata import TableData @pytest.fixture def database_path(tmpdir): p = tmpdir.join("tmp.db") db_path = str(p) con = sqlite.SimpleSQLite(db_path, "w") con.create_table_from_tabledat...
"""Module to monitor installed napps.""" import logging import re from pathlib import Path from watchdog.events import RegexMatchingEventHandler from watchdog.observers import Observer log = logging.getLogger(__name__) class NAppDirListener(RegexMatchingEventHandler): """Class to handle directory changes.""" re...
import generate def encrypt(path,key,outfile): print("\n-------Encrypting-------") plain_text = open(str(path),"r") encoding = open("./encode/"+"C_en","r") duration = open("./encode/duration","r") cipher_text = open("c_text","w") cipher_dur = open("c_dur","w") #Getting plain text for lin...
import os import sys import cv2 import numpy as np sys.path.insert(0, "..") from models import Image FRONT = "front/" BACK = "back/" SEGMAP = "segmap/" NUM_INTERVALS = [40, 45, 40, 50, 40, 50, 40] DOB_INTERVALS = [25, 13, 27, 22, 13, 25, 25, 25] class Program(): def __init__(self, img_folder): self.images = [] nam...
import random from PyQt5.QtWidgets import QDialog import common import world import qt_fight_dialog config = { "run_chance": 20 } class FightDialog(QDialog): def __init__(self, parent): super(QDialog, self).__init__(parent.window) self.parent = parent self.ui = qt_fight_dialog.Ui_Dialog(...
class Team: """Defines a Keeper Team """ def __init__(self, team_uid='', restrict_edit=False, restrict_view=False, restrict_share=False, name=''): self.team_uid = team_uid self.restrict_edit = restrict_edit self.restrict_view = restrict_view self.restrict_share = restrict_share ...
import io import os import sys import unittest class Test_TestProgram(unittest.TestCase): def test_discovery_from_dotted_path(self): loader = unittest.TestLoader() tests = [self] expectedPath = os.path.abspath(os.path.dirname(unittest.test.__file__)) self.wasRun = False def _...
import _plotly_utils.basevalidators class FamilyValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="family", parent_name="heatmapgl.colorbar.tickfont", **kwargs ): super(FamilyValidator, self).__init__( plotly_name=plotly_name, parent...
from django.http import Http404 from django.shortcuts import render, get_object_or_404 from django.views.decorators.http import require_http_methods from projects.models import Project from .models import Entry @require_http_methods(["GET"]) def blog_entries(request): """ Blog main page. """ projectList...
import uuid from unittest.mock import MagicMock from app.data_model.answer_store import AnswerStore, Answer from app.questionnaire.completeness import Completeness from app.questionnaire.location import Location from app.questionnaire.navigation import Navigation from app.utilities.schema import load_schema_from_params...
"""Module for storing coinchoose data in the database.""" import coinchoose from datetime import datetime from datetime import timedelta from decimal import Decimal import os import psycopg2 as pg2 import psycopg2.extras as pg2ext import random import unittest batchLimit = 1000 tables = { "currency": "currency", ...
import _plotly_utils.basevalidators class AlignsrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__( self, plotly_name="alignsrc", parent_name="sunburst.hoverlabel", **kwargs ): super(AlignsrcValidator, self).__init__( plotly_name=plotly_name, parent_name...
class Board(object): def __init__(self): self.squares = [ " ", " ", " ", " ", " ", " ", " ", " ", " " ] def showBoard(self): """Converts the board to a string for displaying purposes.""" brd = "\n | | \n" + \ " " + self.squares[0] + " | " + self.squares[1] + " | " + s...
from mass_api_client.schemas import DroppedBySampleRelationSchema, ResolvedBySampleRelationSchema, \ RetrievedBySampleRelationSchema, ContactedBySampleRelationSchema, SsdeepSampleRelationSchema from .base_with_subclasses import BaseWithSubclasses from .sample import Sample class SampleRelation(BaseWithSubclasses): ...
from django.db import models from datetime import datetime class Entry(models.Model): name = models.CharField(max_length=200, blank=True) phone1 = models.CharField(max_length=50, blank=True) phone2 = models.CharField(max_length=50, blank=True) email = models.CharField(max_length=100, blank=True) cur...
import json import urllib from dateutil import parser from kaha import models import os class KahaImport: """ {u'active': u'true', u'description': {u'contactname': u'--', u'contactnumber': u'--', u'detail': u'Binayak Basti Balaju Alongside Bishnumati River', ...
from django.contrib.auth.models import User from django.db import models class Invitation(models.Model): user = models.ForeignKey(User) token = models.CharField(max_length=40) valid_from = models.DateTimeField() valid_until = models.DateTimeField()
Test.describe('Example Tests') Test.assert_equals(sum_mul(0, 0), 'INVALID') Test.assert_equals(sum_mul(2, 9), 20) Test.assert_equals(sum_mul(3, 13), 30) Test.assert_equals(sum_mul(4, 123), 1860) Test.assert_equals(sum_mul(4, -7), 'INVALID')
__author__ = 'Tirth Patel <complaints@tirthpatel.com>' import requests import re import shutil import os def get_img_links(url): req = requests.get(url) if req.status_code != 200: return [] return clean_up(re.findall(r'data-src="//(.*?)"', req.text)) def clean_up(coarse_urls): clean_urls = [] ...
import re from collections import defaultdict, namedtuple from collections.abc import Iterable from functools import lru_cache from sanic.exceptions import NotFound, InvalidUsage from sanic.views import CompositionView Route = namedtuple( 'Route', ['handler', 'methods', 'pattern', 'parameters', 'name', 'uri']) ...
import unittest from azure.communication.sms._shared.policy import HMACCredentialsPolicy from devtools_testutils import AzureTestCase class HMACTest(AzureTestCase): def setUp(self): super(HMACTest, self).setUp() def test_correct_hmac(self): auth_policy = HMACCredentialsPolicy("contoso.communicat...
from sqlalchemy.testing import expect_deprecated_20 from sqlalchemy.testing import fixtures from sqlalchemy.util.compat import import_ class DeprecationWarningsTest(fixtures.TestBase): __backend__ = False def test_deprecate_databases(self): with expect_deprecated_20( "The `database` package ...
from setuptools import setup tests_require = [ 'coveralls', 'mock', 'testtools' ] setup( name='SpreadFlowDelta', version='0.0.1', description='Common SpreadFlow processors for delta-type messages', author='Lorenz Schori', author_email='lo@znerol.ch', url='https://github.com/znerol/sp...
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline i...
OPERATION_NAMES = ("conjunction", "disjunction", "implication", "exclusive", "equivalence") def boolean(x, y, operation): return { "conjunction": x & y, "disjunction": x | y, "implication": (not x) | y, "exclusive": x ^ y, "equivalence": x == y }.get(operation, None) if _...
""" A simple way of interacting to a ethereum node through JSON RPC commands. """ import logging import time import warnings import json import gevent from ethereum.abi import ContractTranslator from ethereum.tools.keys import privtoaddr from ethereum.transactions import Transaction from ethereum.utils import denoms, i...
import logging import unittest """Dominator (https://codility.com/demo/take-sample-test/dominator/) Analysis: - Find leader in O(N) and count_of_leader (https://codility.com/media/train/6-Leader.pdf) - Validate if it's more than half, return index """ __author__ = 'au9ustine' logging.basicConfig(format='%(messa...
from django.conf import settings from django.contrib.auth.models import User from django.test import TestCase from django.core.exceptions import SuspiciousOperation from django.core.urlresolvers import reverse from pyspreedly import api from spreedly.models import Plan, Subscription from django.utils.unittest import sk...
import config import urllib import json import access_token import user def object_decoder(obj): Token = access_token.AccessToken() if "refresh_token" in obj: Token.set(obj["access_token"], obj['expires_in'],obj["token_type"],obj["refresh_token"]) return Token else: Token.set(obj["ac...
import megazord hello = megazord \ .Target(["test/cpp/hello.cpp"], output="test/cpp/lib/libhello.so") \ .add_support("root") main = megazord.Target('test/cpp/main.cpp', output='test/cpp/bin/main.a')\ .depends_on(hello) main.assembly() main.deploy_to('./', exclude=hello) ja...
import os import argparse import struct from collections import deque from statistics import mean from cereal import log import cereal.messaging as messaging if __name__ == "__main__": parser = argparse.ArgumentParser(description='Sniff a communication socket') parser.add_argument('--addr', default='127.0.0.1') a...
from server import Server
from setuptools import setup with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ 'attrs==16.3.0', 'six==1.10.0', 'contextlib2==0.5.4', ] test_requirements = [ # TODO: put package test require...
from msrest.serialization import Model class DatasetReference(Model): """Dataset reference type. Variables are only populated by the server, and will be ignored when sending a request. :ivar type: Dataset reference type. Default value: "DatasetReference" . :vartype type: str :param reference_nam...