content
stringlengths
4
20k
import calendar import hashlib import sys import time import urlparse import uuid from decimal import Decimal from urllib import urlencode from django import http from django.conf import settings from django.views.decorators.csrf import csrf_exempt import bleach import commonware.log from tower import ugettext as _ ...
"""Unit tests for NISBackend.""" from __future__ import unicode_literals import nis from django.contrib.auth.models import User from kgb import SpyAgency from reviewboard.accounts.backends import NISBackend from reviewboard.testing import TestCase class NISBackendTests(SpyAgency, TestCase): """Unit tests for ...
from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, EINVAL import eventlet from eventlet.green import socket import ssl from eventlet.queue import Queue import logging import os from threading import Event import time from six.moves import xrange from cassandra.connection import Connection, ConnectionShutdown, Time...
from typing import Optional from azure.core.exceptions import ResourceNotFoundError from azure.identity import DefaultAzureCredential from azure.keyvault.secrets import SecretClient from cached_property import cached_property from airflow.secrets import BaseSecretsBackend from airflow.utils.log.logging_mixin import L...
from unittest.mock import MagicMock, patch from zerver.lib.test_classes import WebhookTestCase from zerver.lib.webhooks.git import COMMITS_LIMIT class GogsHookTests(WebhookTestCase): STREAM_NAME = 'commits' URL_TEMPLATE = "/api/v1/external/gogs?&api_key={api_key}&stream={stream}" FIXTURE_DIR_NAME = 'gogs...
""" Basis terms Module Author: Panos Tsilifis Date: 7/10/2017 """ __all__ = ['PolyBasis', 'MonicPoly', 'Hermite1d', 'Legendre1d', 'Laguerre1d'] import numpy as np import math from scipy import misc import itertools as itls class Hermite1d(object): """ Class that constructs 1-dimensional Hermite polynomia...
#!/usr/bin/env python try: import mapnik2 as mapnik except: import mapnik import sys, os # Set up projections # spherical mercator (most common target map projection of osm data imported with osm2pgsql) merc = mapnik.Projection('+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +...
#!/usr/bin/env python3 import cv2 import numpy as np from time import sleep from time import time LowH=0 HighH=50 LowS=59 HighS=255 LowV=0 HighV=236 morph=11,3 '''LowH2=0 HighH2=0 LowS2=0 HighS2=19 LowV2=235 HighV2=255''' morph=(11,3) LowH2=0 HighH2=50 LowS2=10 HighS2=1 LowV2=0 HighV2=237 def imfill(img): ret...
import unittest from datetime import datetime from airflow.models import DAG, Connection, TaskInstance from airflow.utils import db from airflow.contrib.hooks.qubole_hook import QuboleHook from airflow.contrib.operators.qubole_operator import QuboleOperator try: from unittest import mock except ImportError: ...
print("Welcome to the Average Daily Temperature Program.") print("This program requires you to have the file: station_VL.txt"\ +" in the same folder") stationFilePresent = input("Do you have this file? [y/n]:") if stationFilePresent != "y": raise ValueError("Required file: station_VL.txt not present. Quitting.") ...
__metaclass__ = type import os, sys import pkg_resources from genshi.template import TemplateLoader def _absolute(path): "Compute the absolute path of path relative to the caller file" if os.path.isabs(path): return path caller_fname = sys._getframe(2).f_globals['__file__'] caller_dir = os.pa...
#!/usr/bin/env python import pytest import netmiko from DEVICE_CREDS import * def setup_module(module): module.EXPECTED_RESPONSES = { 'enable_prompt' : 'RP/0/0/CPU0:XRv-1#', 'base_prompt' : 'RP/0/0/CPU0:XRv-1', 'interface_ip' : '169.254.254.181', 'config_mode' : '(config)' ...
#! /usr/bin/env python """ Conversion from a berkeleyDB v0.1 BIGSI to v0.3 berkeleyDB and v0.3 rocksDB Requires v0.3 installed """ import sys import bsddb3.db as db import bitarray import pickle import bigsi.version from bigsi import BIGSI from bigsi.matrix import BitMatrix from bigsi.constants import DEFAULT_BERKELEY...
""" timedelta support tools """ import numpy as np import pandas as pd from pandas._libs import tslibs from pandas._libs.tslibs.timedeltas import (convert_to_timedelta64, parse_timedelta_unit) from pandas.core.dtypes.common import is_list_like from pandas.core.dtypes.generi...
""" Utilities used in testing of UrbanSim. """ import numpy as np import numpy.testing as npt import pandas as pd def assert_frames_equal(actual, expected, use_close=False): """ Compare DataFrame items by index and column and raise AssertionError if any item is not equal. Ordering is unimportant, it...
""" Created on Thu Sep 11 14:41:48 2014 @author: Natural Solutions (Thomas) """ from collections import OrderedDict from pyramid.view import view_config from sqlalchemy import select from ecorelevesensor.models import DBSession from ecorelevesensor.models.object import ObjectGsm route_prefix = 'transmitter/' @vie...
#!/usr/bin/env python """ Plots the RHS evaluations per timestep for the neutral-scan. """ import pickle import matplotlib.pylab as plt import numpy as np import os, sys # If we add to sys.path, then it must be an absolute path commonDir = os.path.abspath("./../../../common") # Sys path is a list of system paths sys...
"""Test zha binary sensor.""" from homeassistant.components.binary_sensor import DOMAIN from homeassistant.const import STATE_ON, STATE_OFF, STATE_UNAVAILABLE from .common import ( async_init_zigpy_device, make_attribute, make_entity_id, async_test_device_join, async_enable_traffic, ) async def te...
import sys import re test_case = open(sys.argv[1], "r") team_output = open(sys.argv[2], "r") int_pat = "^(0|[1-9][0-9]*)$" line = team_output.readline() assert re.match(int_pat, line) team_ans = int(line) line = team_output.readline() assert len(line) == 0 l, a, b, p = [int(x) for x in test_case.readline().split()] ...
import pdb import os, sys, time,types, signal, random, datetime, errno import subprocess # import safplusMgtDb if __name__ != '__main__': # called from inside the source tree sys.path.append("../../python") # Point to the python code, in source control import safplus as sp import clTest import amfctrl modelXML ...
""" GNOME-keyring intergration wrapper. Python GNOME-keyring automagically saves queries into secured memory. This implementation is mindful to not remove secrets into unsecured Python memory. quick search descriptions of keys loaded into secure memory http://developer.gnome.org/gnome-keyring/stable/gnome-keyring...
# Based from http://pythonhosted.org/setuptools/setuptools.html#automatic-script-creation from setuptools import setup, find_packages # Always prefer setuptools over distutils from codecs import open # To use a consistent encoding from os import path here = path.abspath(path.dirname(__file__)) # Get the long descr...
"""Deprecated APIs.""" IMPORTS = {} # pylint: disable=line-too-long IMPORTS[''] = """ # Deprecated imports are kept for backward compatiblity and to be removed in # future versions. Please refer to public APIs for replacement: # https://www.tensorflow.org/lite/api_docs/python/tflite_model_maker # pylint: disable=g-ba...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'Michael Liao' import asyncio, logging import aiomysql def log(sql, args=()): logging.info('SQL: %s' % sql) async def create_pool(loop, **kw): logging.info('create database connection pool...') global __pool __pool = await aiomysql.create_...
"""Sanity test for ansible-doc.""" from __future__ import absolute_import, print_function import collections import os import re from lib.sanity import ( SanityMultipleVersion, SanityFailure, SanitySuccess, SanitySkipped, SanityMessage, ) from lib.util import ( SubprocessError, display, ...
# encoding: utf-8 """ ifaceaddr.py Created by Evelio Vila on 2016-11-26. <EMAIL> Copyright (c) 2009-2017 Exa Networks. All rights reserved. License: 3-clause BSD. (See the COPYRIGHT file) """ from exabgp.protocol.ip import IP # https://tools.ietf.org/html/rfc5305#section-3.2 # This sub-TLV contains a 4-octet IPv...
from MorcoWrapper2D.mw2_GameObject import * from MorcoWrapper2D.mw2_Application import * from MorcoWrapper2D.mw2_Vector4 import * import pygame import math class mw2_Text(mw2_GameObject): def __init__(self, name, fileName, size, text, color, align): mw2_GameObject.__init__(self, name) self.mText = text self.mAl...
import numpy as np from menpo.image import Image, BooleanImage, MaskedImage from menpo.shape import PointCloud from menpo.testing import is_same_array def test_image_copy(): pixels = np.ones([1, 10, 10]) landmarks = PointCloud(np.ones([3, 2]), copy=False) im = Image(pixels, copy=False) im.landmarks['...
#!/usr/bin/env python # coding=utf-8 import mapreduce import os # This mapreducepy job upgrades one worker machine, if version of Worker was detected as # different one from JobTracker's class mapreducejob: # datasource contains the JobTracker's version number datasource = {0: mapreduce.VERSION} # Runnin...
import blenderfunc as bf from config import * from midiUtils import * import pythonmidi """ Copyright (C) 2015 Stephan Pieterse This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either ve...
import itertools import pytest from flex.constants import ( REQUEST_METHODS, ) from flex.exceptions import ( ValidationError, ) from flex.loading.schema.paths.path_item import ( path_item_validator, ) @pytest.mark.parametrize( 'method', REQUEST_METHODS, ) def test_operations_are_not_required(meth...
from eclcli.common import command from eclcli.common import utils from ..networkclient.common import utils as to_obj class ListVPNGateway(command.Lister): def get_parser(self, prog_name): parser = super(ListVPNGateway, self).get_parser(prog_name) return parser def take_action(self, parsed_arg...
from gi.repository import Gtk import ntpath from lib_sallybn.disc_bayes_net.BoxDiscreteBN import BoxDiscreteBN, FILE_EXTENSION import lib_sallybn.util.resources as res from lib_sallybn.util import ugraphic ## Class class MainWindowHandler(object): """ Manager for events such as: save as, save, open, and new...
from nbxmpp.namespaces import Namespace from nbxmpp.protocol import Iq from nbxmpp.protocol import JID from nbxmpp.modules.base import BaseModule from nbxmpp.errors import StanzaError from nbxmpp.errors import MalformedStanzaError from nbxmpp.task import iq_request_task from nbxmpp.structs import BlockingPush from nbxm...
from config import BEACON, DEACTIVATE, ATTACH, QUERY, ACTIVATE, \ BATCH_DELETE class URLBuilder(object): """ docstring for BeaconHelper """ def beacon_deactivation_url(self, beacon_details): """ Returns URL to deactivate the beacons """ return BEACON + beacon_detail...
from squadron.service import get_service_actions, get_reactions, react, _checkfiles import glob import os from squadron.fileio.dirio import makedirsp import shutil from helper import get_test_path import pytest test_path = os.path.join(get_test_path(), 'service_tests') def test_get_service_actions(): actions = ge...
"""PTP TLV Protocol""" import struct, dpkt, exceptions, IPy, json import bson_wrapper, bson import sys # Parameters PTP_VERSION = 1 PTP_MTU = 1400 PTP_BLOB_SIZE = 1024 # Protocol TLV types # General PTP_TYPE_PROTOVER = 0 PTP_TYPE_SERVERVER = 1 PTP_TYPE_CLIENTVER = 2 PTP_TYPE_SEQUENCE ...
"""Test multiple RPC users.""" from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, get_datadir_path, str_to_b64str, ) import os import http.client import urllib.parse import subprocess from random import SystemRandom import string import configpar...
"""Evolution Strategies for a Population. Evolver classes manage a population of individuals, and are responsible for taking care of the transition from one generation to the next. """ # standard modules from __future__ import print_function import sys class SteadyStateEvolver(object): """Evolve a population in...
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flask, request, jsonify, make_response, g,\ render_template, redirect, url_for import os from os import path from contextlib import closing import sqlite3 import socket import struct import time, datetime app = Flask(__name__) app.config.update(dict...
#!/usr/bin/env python __doc__ = """ Jingpeng Wu <<EMAIL>>, 2015 """ import numpy as np from front_end import znetio import shutil def parseIntSet(nputstr=""): """ Allows users to specify a comma-delimited list of number ranges as sample selections. Specifically, parses a string which should contain a co...
import logging from math import floor import dendropy class TreeSupport(): """Calculate support values for clades.""" def __init__(self): """Initialize.""" self.logger = logging.getLogger() def subset_taxa(self, input_tree, replicate_trees, output_tree): """Calcu...
#!/usr/bin/env python """ Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import re from lib.core.common import Backend from lib.core.common import Format from lib.core.common import getUnicode from lib.core.common import randomRange from lib.core....
from django import forms from django.contrib.auth.models import User from amcat.models import CodingJob, CodingSchema from amcat.models.coding.codingjob import _create_codingjob_batches from amcat.scripts.query import QueryAction from amcat.scripts.query.saveset import SaveAsSetForm from amcat.tools.keywordsearch impo...
""" Tests if vtkEnsembleSource works properly. """ import vtk from vtk.test import Testing class TestEnsemble(Testing.vtkTest): resolutions = [4, 8, 16, 32] npolys = [5, 9, 17, 33] def createSource(self): r = vtk.vtkEnsembleSource() aColumn = vtk.vtkIntArray() aColumn....
from setuptools import setup import tinyfasta # Importing the "multiprocessing" module is required for the "nose.collector". # See also: http://bugs.python.org/issue15881#msg170215 try: import multiprocessing except ImportError: pass # Define the test runner. # See also: # http://fgimian.github.io/blog/2014/0...
#!/usr/bin/env python3 class Solution: def circularArrayLoop(self, nums): l = len(nums) for i in range(l): print(f'i = {i}') head = slow = fast = i while True: slow = (slow+nums[slow])%l fast1 = (fast+nums[fast])%l ...
from django.utils.translation import ugettext_lazy as _ from rest_framework import relations from rest_framework.exceptions import ValidationError from rest_framework.reverse import reverse from rest_framework import serializers from ..models import Kind class KindRelatedField(relations.RelatedField): queryset ...
from functools import lru_cache from hashlib import md5 from itertools import product salt = b'qzyelonm' lookahead_distance = 1000 def get_hex_digest(b): return md5(b).hexdigest() def first_repeat_char(hash_str, l=3): matches = sorted((hash_str.find(c*l), c) for c in set(hash_str) if c*l in hash_str) r...
#!/usr/bin/env python3 """ Copyright (C) 2015 Petr Skovoroda <<EMAIL>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This pr...
import sys import os import pdb from datetime import date sys.path.append(os.getcwd() + '/../../') try: from salary_calculator import settings except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized t...
from oslo_utils import strutils from oslo_utils import uuidutils from oslo_versionedobjects import base as object_base from ironic.common import exception from ironic.common.i18n import _ from ironic.db import api as db_api from ironic.objects import base from ironic.objects import fields as object_fields REQUIRED_IN...
""" Python byte code operations. Very similar to the dis module, but dis does not exist in Jython, so recreate the small portion we need here. """ def LINE_NUM(op): return op == 127 def LOAD_GLOBAL(op): return op == 116 def LOAD_CONST(op): return op == 100 def LOAD_FAST(op): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson import argparse WATCHLIST_FILE = 'watchlist.json' class Watchlist(object): def __init__(self): """ Constructor for the Watchlist class This method will automatically load the watchlist.json file, if none exists it will be c...
from superdesk.resource import Resource, build_custom_hateoas from superdesk.services import BaseService from .common import aggregations from .archive import ArchiveResource import superdesk class UserContentResource(Resource): endpoint_name = 'user_content' item_url = ArchiveResource.item_url url = 'use...
""" Helper for testing. """ import sys import warnings import os.path import re import subprocess import threading import pytest import _pytest from joblib._compat import PY3_OR_LATER raises = pytest.raises warns = pytest.warns SkipTest = _pytest.runner.Skipped skipif = pytest.mark.skipif fixture = pytest.fixture ...
from odoo import models, fields, api, _ class PurchaseOrder(models.Model): _inherit = 'purchase.order' @api.multi def _prepare_invoice(self): result = super(PurchaseOrder, self)._prepare_invoice() result.update({'reference_coexiste': self.partner_ref, 'issuer': '0'}...
# -*- coding: utf-8 -*- from sqlalchemy import func from sqlalchemy.exc import IntegrityError from ..core import db from ..models import UserPermission def create(user_id, permission_id): user_permission = UserPermission( user_id=user_id, permission_id=permission_id, ) db.session.add(user_...
# Implementation of the Hidden Markov Model for discrete observations with Jax. # This file is based on https://github.com/probml/pyprobml/blob/master/scripts/hmm_lib.py from jax import lax import jax import jax.numpy as jnp class HMMDiscrete: def __init__(self, A, px, pi): """ This class simulate...
import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import heraclient import argparse import threading import atexit import termios import tty parser = argparse.ArgumentParser(description='Run shell.') parser.add_argument('template', help='use template') parser.add_a...
import json from urllib2 import Request, urlopen import sys import codecs sys.stdout = codecs.getwriter('utf8')(sys.stdout) api_token = 'secret' def make_request(api_call): "Makes a request to the Asana API" return Request( 'https://app.asana.com/api/1.0' + api_call, headers={'Authorization':...
from docopt import docopt import numpy as np from collections import defaultdict from representations.embedding import SVDEmbedding, Embedding from representations.explicit import PositiveExplicit from os.path import join, basename, normpath import pandas as pd import emotion_lexicons def main(): args = docopt(""...
from eve.utils import config from superdesk import get_resource_service from planning.common import ASSIGNMENT_WORKFLOW_STATE from copy import deepcopy from flask_babel import lazy_gettext def update_on_assign_id(item, **kwargs): assign_id = item.get("assignment_id") if assign_id: assignments_service ...
import webapp2_extras import wtforms from wtforms import validators, ValidationError class TaxiDriverForm(wtforms.Form): first_name = wtforms.StringField(validators=[ validators.Required(), validators.Length(min=3,max=25)]) last_name = wtforms.StringField(validators=[ validators.Required()...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_langevin_dynamics ---------------------------------- Tests for `langevin_dynamics` module. """ import sys, os import unittest from contextlib import contextmanager from click.testing import CliRunner from langevin_dynamics.langevin_dynamics import * from langevin...
import numpy as np import cv2 import time import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib import rcParams import SimpleITK as sitk from matplotlib.widgets import Slider, Button rcParams['font.family'] = 'serif' #ps aux | grep python # KILL python process ... #kill -9 inser...
from pyre.components.Component import Component import numpy # ---------------------------------------------------------------------- def N0(p): return -0.5*(p[0]+p[1]) def N0p(p): return -0.5 def N0q(p): return -0.5 def N1(p): return 0.5*(1.0+p[0]) def N1p(p): return 0.5 def N1q(p): return 0.0 def ...
import shlex import subprocess import sys import re import os env_var_rx = re.compile(r"^([a-zA-Z0-9_]+)=(\S+)$") def debug(message): print >> sys.stderr, message if sys.platform == 'win32': dev_null = open("NUL:", "w") else: dev_null = open("/dev/null", "w") def _open_out_file(filename): if filena...
"""The test for the NuHeat thermostat module.""" from datetime import timedelta from unittest.mock import patch from homeassistant.components.nuheat.const import DOMAIN from homeassistant.const import ATTR_ENTITY_ID import homeassistant.util.dt as dt_util from .mocks import ( MOCK_CONFIG_ENTRY, _get_mock_nuhe...
import copy from requests_mock.contrib import fixture from keystoneclient import session from openstackclient.api import object_store_v1 as object_store from openstackclient.object.v1 import container from openstackclient.tests.object.v1 import fakes as object_fakes class TestObjectAll(object_fakes.TestObjectv1): ...
from nose.tools import * from unittest import TestCase import alias as al from ast import literal_eval class LabellingCreationTests(TestCase): def test_blank_labelling_creation(self): af = al.ArgumentationFramework() af.add_attack(atts=[('a','b'), ('b','c'), ('c','d')]) l = af.generate_bla...
from pymongo import MongoClient import multiprocessing import threading import datetime import calendar import math import time db25 = MongoClient(host='10.8.8.111', port=27017, connect=False)['miner-prod25'] cache = MongoClient(host='10.8.8.111', port=27017, connect=False)['cache25'] points = db25['points'] users2...
"""Tests for query homozygosity_coefficient.sql. See https://github.com/verilylifesciences/analysis-py-utils for more details about the testing framework. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from jinja2 import Template import os import unit...
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Basket', fields=[ ('id', model...
from qingcloud.cli.misc.utils import explode_array from qingcloud.cli.iaas_client.actions.base import BaseAction class StopInstancesAction(BaseAction): action = 'StopInstances' command = 'stop-instances' usage = '%(prog)s -i "instance_id,..." [-f <conf_file>]' @classmethod def add_ext_arguments(c...
import pandas as pd from functions import * import numpy as np import matplotlib.pyplot as plt from johansen_test import coint_johansen from numpy.matlib import repmat if __name__ == "__main__": ########################################################################### # import data from ...
from io_scs_tools.consts import Mesh as _MESH_consts from io_scs_tools.internals.shaders.eut2.dif_spec import DifSpec from io_scs_tools.utils import material as _material_utils class DifSpecOclu(DifSpec): SEC_UVMAP_NODE = "SecUVMap" OCLU_TEX_NODE = "OcclusionTexture" OCLU_SEPARATE_RGB_NODE = "OcclusionSep...
"""Generator for Python target. This module consumes the YAML spec and generates some message class files. """ from sbpg.targets.templating import JENV, ACRONYMS import copy from construct import * TEMPLATE_NAME = "sbp_construct_template.py.j2" CONSTRUCT_CODE = { 'u8': 'ULInt8', 'u16': 'ULInt16', 'u32': 'UL...
import unittest from unittest import mock from tests import PluginTest from plugins import create_plugin from plugins.create_plugin import create_plugin_MAC from plugins.create_plugin import create_plugin_LINUX class create_pluginTest(PluginTest): def setUp(self): self.mac_module = self.load_plugin(creat...
#!/usr/bin/env python ''' ======================= ======================= ''' # Import/use system module import sys # Import/use OpenCV module import cv2 import numpy as np import cone_track #from drone_control import Drone SAFE_OFFSET = 50 # Print OpenCV version print "OpenCV version:", cv2.__version__ # # Setup...
from odoo import api, fields, models from odoo.addons import decimal_precision as dp class StockMove(models.Model): _inherit = 'stock.move' def _default_uom(self): uom_categ_id = self.env.ref('product.product_uom_categ_kgm').id return self.env['product.uom'].search([('category_id', '=', uom_...
import copy import json import logging import os import colorcet as cc import pandas as pd import pyproj import pytoml import tornado import tornado.escape import yaml from bokeh.layouts import row, widgetbox, layout from bokeh.models import Select, CustomJS, Jitter, DataTable, TableColumn, Slider, Button # noinspecti...
# -*- coding: utf-8 -*- # FOGLAMP_BEGIN # See: http://foglamp.readthedocs.io/ # FOGLAMP_END """FogLAMP Monitor module""" import asyncio import aiohttp import json from foglamp.common import logger from foglamp.common.audit_logger import AuditLogger from foglamp.common.configuration_manager import ConfigurationManage...
import abc import typing import pkg_resources from google import auth from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials # type: ignore from google.ads.googleads.v7.services.types import ( conversion_adjustment_upl...
from django.forms import Form, ModelForm from django.contrib import messages class EasyFormBase(object): """ An easier way of doing forms so that they take requests instead of blank data. Also handles creating a django message, and can be extended later to do other things like trigger signals. Usage...
"""europarl. Usage: dasem.europarl download [options] dasem.europarl get-all-sentence-words [options] dasem.europarl get-all-sentences [options] dasem.europarl get-all-tokenized-sentences [options] Options: --debug Debug messages. -h --help Help message --oe=encoding Output e...
#!/usr/bin/python import argparse import logging import os import subprocess import tarfile import urllib2 import uuid from picklable_itertools.extras import equizip TRAIN_DATA_URL = 'http://www.statmt.org/wmt15/training-parallel-nc-v10.tgz' VALID_DATA_URL = 'http://www.statmt.org/wmt15/dev-v2.tgz' PREPROCESS_URL = ...
"""Theme blueprint in order for template and static files to be loaded.""" from __future__ import absolute_import, print_function import re from flask import Blueprint, abort, jsonify, request from six.moves.urllib.parse import unquote from webargs import fields from ..permissions import cms_permission from ..search...
"""Maximum path sum I By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. [3] [7] 4 2 [4] 6 8 5 [9] 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom of the triangle below: 75 95 64 17 47 82 18 35 87 10 20 ...
from flask import Flask from flask.ext.appbuilder import SQLA from app.models import ContactGroup, Gender, Contact import random from datetime import datetime from app import db def get_random_name(names_list, size=1): name_lst = [names_list[random.randrange(0, len(names_list))].capitalize() for i in range(0, siz...
"""Module tests.""" from __future__ import absolute_import, print_function from copy import deepcopy import pytest from flask import Flask, render_template_string from invenio_records_rest import InvenioRecordsREST from invenio_records_rest.utils import PIDConverter from invenio_deposit import InvenioDeposit, Inven...
from pubnub import utils from pubnub.endpoints.endpoint import Endpoint from pubnub.errors import PNERR_PAM_NO_FLAGS from pubnub.exceptions import PubNubException from pubnub.enums import HttpMethod, PNOperationType from pubnub.models.consumer.access_manager import PNAccessManagerGrantResult class Grant(Endpoint): ...
import bpy from bpy.props import IntProperty, StringProperty, BoolProperty from sverchok.node_tree import SverchCustomTreeNode from sverchok.data_structure import (SvSetSocketAnyType, SvGetSocketAnyType, get_other_socket, updateNode) class SvSwitchNode(bpy.types.Node, SverchCustomTreeNode...
""" Renderers for various kinds of annotations that can be added to Bokeh plots """ from __future__ import absolute_import from ..enums import Orientation, SpatialUnits, RenderLevel from ..mixins import LineProps, FillProps, TextProps from ..properties import abstract from ..properties import (Int, String, Enum, Inst...
from spack import * class NnC(AutotoolsPackage): """nn: Natural Neighbours interpolation. nn is a C code for Natural Neighbours interpolation of 2D scattered data. It provides a C library and a command line utility nnbathy.""" homepage = "https://github.com/sakov/nn-c" git = "https://github....
# -*- encoding: utf-8 -*- from supriya.tools.ugentools.UGen import UGen class FBSineN(UGen): r'''A non-interpolating feedback sine with chaotic phase indexing. :: >>> fbsine_n = ugentools.FBSineN.ar( ... a=1.1, ... c=0.5, ... fb=0.1, ... frequency=2205...
def get_matplotlib_pyplot(server, raise_if_not_available=False): try: # noinspection PyUnresolvedReferences import matplotlib from distutils.version import LooseVersion if server: if LooseVersion(matplotlib.__version__) <= LooseVersion("3.1"): matplotlib.u...
import contextlib import os import pickle from cinder import units from cinder.volume.drivers.xenapi import tools class XenAPIException(Exception): def __init__(self, original_exception): super(XenAPIException, self).__init__(str(original_exception)) self.original_exception = original_exception ...
""" This file demonstrates the creation of a directed graph using the Python interface to VTK. """ from vtk import * xdim = 600 ydim = 600 #------------------------------------------------------------------------------ # Script Entry Point #----------------------------------------------------------------------------...
from __future__ import division import pygame import random from operator import mul class Game: agent_size = 5 max_motion = 4 board_width = 30 board_height = 15 block_size = 30 horizontal_direction = 0 num_drops = 40 def __init__(self): '''Generate a game instance that ...