code
stringlengths
1
199k
"""A dummy module with no effect for use on systems without readline.""" def get_completer(): """An empty implementation of readline.get_completer.""" def get_completer_delims(): """An empty implementation of readline.get_completer_delims.""" def parse_and_bind(unused_command): """An empty implementation of...
import mxnet as mx import numpy as np import json def check_metric(metric, *args, **kwargs): metric = mx.metric.create(metric, *args, **kwargs) str_metric = json.dumps(metric.get_config()) metric2 = mx.metric.create(str_metric) assert metric.get_config() == metric2.get_config() def test_metrics(): c...
import random from nose.tools import * import networkx as nx from networkx import convert_node_labels_to_integers as cnlti from networkx.algorithms.simple_paths import _bidirectional_shortest_path from networkx.algorithms.simple_paths import _bidirectional_dijkstra def test_all_simple_paths(): G = nx.path_graph(4) ...
try: from setuptools import setup except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup setup( name='django-tastypie', version='0.12.2-dev', description='A flexible & capable API layer for Django.', author='Daniel Lindsley', author_emai...
import sys, os from optparse import OptionParser option_parser = OptionParser() option_parser.add_option('--install-root',default='/opt/graphite/', help="The base directory of the graphite installation") option_parser.add_option('--libs',default=None, help="The directory where the graphite python package is install...
import sys from os.path import abspath, dirname, join if sys.getdefaultencoding() != 'utf-8': reload(sys) sys.setdefaultencoding('utf-8') PREFIX = abspath( join( dirname(abspath(__file__)), '../' ) ) if PREFIX not in sys.path: sys.path.append(PREFIX)
from django.core.management.base import BaseCommand from optparse import make_option from crits.dashboards.dashboard import SavedSearch class Command(BaseCommand): """ Script Class. """ help = 'Creates the default dashboard.' def handle(self, *args, **options): """ Script Execution. ...
"""Debugger Wrapper Session Consisting of a Local Curses-based CLI.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tempfile from tensorflow.python.client import session from tensorflow.python.debug.wrappers import dumping_wrapper from ten...
from sympy.external import import_module from sympy.utilities.pytest import raises, SKIP from sympy.core.compatibility import range theano = import_module('theano') if theano: import numpy as np ts = theano.scalar tt = theano.tensor xt, yt, zt = [tt.scalar(name, 'floatX') for name in 'xyz'] else: #b...
{ "name": "Stock - Packaging information", "version": "1.0", "depends": [ "stock", "product_packaging_through_attributes", ], "author": "OdooMRP team," "AvanzOSC," "Serv. Tecnol. Avanzados - Pedro M. Baeza", "website": "http://www.odoomrp.com", "co...
""" Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved. This program and the accompanying materials are made available under the terms of the 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 ht...
""" Locking functionality when launching things from the command line. Uses a pidfile. This prevents multiple identical workflows to be launched simultaneously. """ from __future__ import print_function import hashlib import os from luigi import six def getpcmd(pid): """ Returns command of process. :param p...
"""Utility functions for writing decorators (which modify docstrings).""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys def get_qualified_name(function): # Python 3 if hasattr(function, '__qualname__'): return function.__qualname__ # Py...
""" requests.adapters ~~~~~~~~~~~~~~~~~ This module contains the transport adapters that Requests uses to define and maintain connections. """ import os.path import socket from urllib3.poolmanager import PoolManager, proxy_from_url from urllib3.response import HTTPResponse from urllib3.util import Timeout as TimeoutSau...
"""Tests for the JuiceNet component."""
"""Neural nets utility for L2HMC compatible with TensorFlow's eager execution. Reference [Generalizing Hamiltonian Monte Carlo with Neural Networks](https://arxiv.org/pdf/1711.09268.pdf) Code adapted from the released TensorFlow graph implementation by original authors https://github.com/brain-research/l2hmc. """ from ...
from coalib.bearlib.languages.Language import Language @Language class Java: extensions = '.java', comment_delimiter = '//' multiline_comment_delimiters = {'/*': '*/'} string_delimiters = {'"': '"'} multiline_string_delimiters = {} indent_types = {'{': '}'} encapsulators = {'(': ')', '[': ']...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: os_keystone_domain_facts short_description: Retrieve facts abou...
""" Created on Tue Nov 08 22:28:48 2011 @author: josef """ from statsmodels.compat.python import zip import numpy as np from numpy.testing import assert_equal, assert_almost_equal, assert_ from statsmodels.tools.eval_measures import ( maxabs, meanabs, medianabs, medianbias, mse, rmse, stde, vare, aic, aic_sigma...
import grpc channel = grpc.insecure_channel('localhost:1000') del channel print 'Success!'
import httplib import json import logging import pprint import time logger = logging.getLogger('proximity_auth.%s' % __name__) _GOOGLE_APIS_URL = 'www.googleapis.com' _REQUEST_PATH = '/cryptauth/v1/%s?alt=JSON' class CryptAuthClient(object): """ A client for making blocking CryptAuth API calls. """ def __init__(sel...
import numpy as np def rainbow(n): """ Returns a list of colors sampled at equal intervals over the spectrum. Parameters ---------- n : int The number of colors to return Returns ------- R : (n,3) array An of rows of RGB color values Notes ----- Converts from ...
{ 'name' : 'eInvoicing & Payments', 'version' : '1.0', 'author' : 'OpenERP SA', 'summary': 'Send Invoices and Track Payments', 'description': """ Invoicing & Payments by Accounting Voucher & Receipts ===================================================== The specific and easy-to-use Invoicing system ...
from django.conf import settings def is_solr_supported(): try: return 'Solr' in settings.HAYSTACK_CONNECTIONS['default']['ENGINE'] except (KeyError, AttributeError): return False def is_elasticsearch_supported(): try: return 'Elasticsearch' in settings.HAYSTACK_CONNECTIONS['default']...
import time import openerp from openerp.report.interface import report_rml from openerp.tools import to_xml from openerp.report import report_sxw from datetime import datetime from openerp.tools.translate import _ class report_custom(report_rml): def create_xml(self, cr, uid, ids, datas, context=None): numb...
""" Test cases for codeop.py Nick Mathewson """ import unittest from test.support import run_unittest, is_jython from codeop import compile_command, PyCF_DONT_IMPLY_DEDENT import io if is_jython: import sys def unify_callables(d): for n,v in d.items(): if hasattr(v, '__call__'): ...
""" Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved. This program and the accompanying materials are made available under the terms of the 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 ht...
import _codecs_iso2022, codecs import _multibytecodec as mbc codec = _codecs_iso2022.getcodec('iso2022_jp_1') class Codec(codecs.Codec): encode = codec.encode decode = codec.decode class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): codec = codec cl...
""" Python Character Mapping Codec based on gsm0338 generated from './GSM0338.TXT' with gencodec.py. With extra sauce to deal with the 'multibyte' extensions! """#" import codecs import re def _encode(input,errors='strict'): # split to see if we have any 'extended' characters runs=unicode_splitter.split(inp...
""" termcolors.py """ from django.utils import six color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white') foreground = {color_names[x]: '3%s' % x for x in range(8)} background = {color_names[x]: '4%s' % x for x in range(8)} RESET = '0' opt_dict = {'bold': '1', 'underscore': '4', 'blink': ...
import numpy as np from scipy.ndimage import label def generate_test_vecs(infile, strelfile, resultfile): "test label with different structuring element neighborhoods" def bitimage(l): return np.array([[c for c in s] for s in l]) == '1' data = [np.ones((7, 7)), bitimage(["1110111", ...
""" pygments.filters ~~~~~~~~~~~~~~~~ Module containing filter lookup functions and default filters. :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.token import String, Comment, Keyword, Name, Error, Whitespa...
microcode = ''' def macroop INS_M_R { # Find the constant we need to either add or subtract from rdi ruflag t0, 10 movi t3, t3, dsz, flags=(CEZF,), dataSize=asz subi t4, t0, dsz, dataSize=asz mov t3, t3, t4, flags=(nCEZF,), dataSize=asz zexti t2, reg, 15, dataSize=8 mfence ld t6, intseg,...
import base64 iconstr = """\ iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAAG0OVFdAAAABGdBTUEAANbY1E9YMgAAABl0RVh0 U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAFoHSURBVHjaYvz//z8DJQAggFhu3LiBU1JI SOiPmJgYM7IYUD0jMh8ggFhAhKamJuOHDx/+8fPz4zQsMTGRYf78+RjiAAHEBCJOnTr1HZvmN2/e MDAyQiycOXMmw5MnTxhmzZoViqwGIIAYrl+/DqKM/6OBNWvWgOmvX7/+37Rp...
from __future__ import unicode_literals import getpass from django.contrib.auth import get_user_model from django.contrib.auth.password_validation import validate_password from django.core.exceptions import ValidationError from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_D...
import os, sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import syscall_name usage = "perf script -s syscall-counts-by-pid.py [comm]\n"; for_comm = None for_pid = None if len(sys.argv) > 2: sys.exit(...
import os try: import ConfigParser as configparser py2 = True except ImportError: import configparser py2 = False class GSRTConfig(object): """ Quick module to handle a normalized config pull. Will search environment sections. To use environment varibles for invidual settings, the ENV should...
""" Tool to cleanup site pins JSON dumps. This tool has two behaviors. This first is to rename site names from global coordinates to site local coordinates. The second is remove the tile prefix from node names. For example CLBLM_L_X8Y149 contains two sites named SLICE_X10Y149 and SLICE_X11Y149. SLICE_X10Y149 becomes ...
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('products', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ ...
"""Family module for Meta Wiki.""" from pywikibot import family class Family(family.WikimediaOrgFamily): """Family class for Meta Wiki.""" name = 'meta' interwiki_forward = 'wikipedia' cross_allowed = ['meta', ] category_redirect_templates = { 'meta': ( 'Category redirect', ...
from office365.runtime.client_value import ClientValue class ServicePlanInfo(ClientValue): """Contains information about a service plan associated with a subscribed SKU. The servicePlans property of the subscribedSku entity is a collection of servicePlanInfo.""" def __init__(self, _id=None, name=None, provi...
from django.views.generic import TemplateView from googleapiclient.discovery import build from .utils import SearchResults from . import * class SearchView(TemplateView): template_name = "googlesearch/search_results.html" def get_context_data(self, **kwargs): context = super(SearchView, self).get_contex...
''' RP_extract: Rhythm Patterns Audio Feature Extractor @author: 2014-2015 Alexander Schindler, Thomas Lidy Re-implementation by Alexander Schindler of RP_extract for Matlab Matlab version originally by Thomas Lidy, based on Musik Analysis Toolbox by Elias Pampalk ( see http://ifs.tuwien.ac.at/mir/downloads.html ) Main...
""" Script used to convert data into sparse matrix format that can easily be imported into MATLAB. Use like this python convertToSparseMatrix.py ../../../../../data/train_triplets.txt 1000 ../../../../../data/eval/year1_test_triplets_visible.txt ../../../../../data/eval/year1_test_triplets_hidden.txt 100 """ import sys...
import os import subprocess running = os.system("nc -u -l -p 5001 | mplayer -cache 1024 -")
from CIM14.IEC61970.Core.IdentifiedObject import IdentifiedObject class LimitSet(IdentifiedObject): """Specifies a set of Limits that are associated with a Measurement. A Measurement may have several LimitSets corresponding to seasonal or other changing conditions. The condition is captured in the name and descript...
""" EOSS catalog system external catalog management package """ __author__ = "Thilo Wehrmann, Steffen Gebhardt" __copyright__ = "Copyright 2016, EOSS GmbH" __credits__ = ["Thilo Wehrmann", "Steffen Gebhardt"] __license__ = "GPL" __version__ = "1.0.0" __maintainer__ = "Thilo Wehrmann" __email__ = "twehrmann@eoss.cloud" ...
import _plotly_utils.basevalidators class SizesrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__( self, plotly_name="sizesrc", parent_name="scattermapbox.hoverlabel.font", **kwargs ): super(SizesrcValidator, self).__init__( plotly_name=plotl...
class Solution: def crackSafe(self, n: int, k: int) -> str: result = ['0'] * n visited = set([''.join(result)]) for i in range(k ** n): prev = result[len(result) - n + 1:] for j in range(k - 1, -1, -1): curr = ''.join(prev) + str(j) if ...
from __future__ import absolute_import from __future__ import print_function from __future__ import division import tensorflow as tf class DCGAN(object): """ Tensorflow implementation of DCGAN, with four CNN layers. We assume the input images are of size 32x32. """ def __init__(self): ...
from datetime import datetime, date import six def fix_number(target_type): return lambda value: None if isinstance(value, (str, six.text_type)) and len(value) == 0 else target_type(value) fixed_datetime = lambda time_str: datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S') fixed_date = lambda time_str: date.fromtimes...
import pymake.data, pymake.functions, pymake.util import unittest import re def multitest(cls): for name in cls.testdata.keys(): def m(self, name=name): return self.runSingle(*self.testdata[name]) setattr(cls, 'test_%s' % name, m) return cls class SplitWordsTest(unittest.TestCase): ...
from botapi.settings import * DEBUG = True ALLOWED_HOSTS = ['*']
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import caffe2.python.serialized_test.serialized_test_util as se...
import unittest converter = __import__("obj-to-sm-conversion") model = """ mtllib object.mtl o Cube v 1.000000 -1.000000 -1.000000 v 1.000000 -1.000000 1.000000 v -1.000000 -1.000000 1.000000 v -1.000000 -1.000000 -1.000000 v 1.000000 1.000000 -0.999999 v 0.999999 1.000000 1.000001 v -1.000000 1.000000 1.000000 v -1.00...
import argparse import binascii import datetime import gzip import json import magic import os import pymongo import sys def read_gzip(filename): with gzip.open(filename) as file: content = file.read() return content def read_plain(filename): with open(filename) as file: content = file.read(...
"""Translate cli commands to non-cli code.""" import logging from urllib.error import HTTPError, URLError import requests from kytos.utils.config import KytosConfig LOG = logging.getLogger(__name__) class WebAPI: # pylint: disable=too-few-public-methods """An API for the command-line interface.""" @classmethod...
from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('blog', '0025_auto_20170626_0008'), ] operations = [ migrations.AlterModelOptions( name='category', options={'ordering': ['-id'], 'verbose...
import string import unittest import datetime import collections from unittest import mock from flumine.order.order import ( BaseOrder, BetfairOrder, ExchangeType, OrderTypes, OrderStatus, VALID_BETFAIR_CUSTOMER_ORDER_REF_CHARACTERS, LIVE_STATUS, COMPLETE_STATUS, ) from flumine.exception...
print "Numeros inteiros:" x = 10 y = 3 print x, "+", y, "=", x + y print x, "+", y, "=", x - y print x, "+", y, "=", x*y print x, "+", y, "=", x/y # repare como o resultado eh um inteiro print x, "+", y, "=", x % y # esse eh o resto da divisao print x, "+", y, "=", x**y # esse eh o operador potencia, x elevado a potenc...
import os import time import yaml import logging import threading from ybk.lighttrade.sysframe import Client as SysframeClient log = logging.getLogger('trader') configfile = open(os.path.join(os.path.dirname(__file__), 'trading.yaml'), encoding='utf-8') config = yaml.load(configfile) try: accountfile = open( ...
import command_line import ast import os import traceback from operator import attrgetter import settings from execution_tree_builder import build_execution_tree class DataCollectorCall(object): def __init__(self, var_name="", indentation=0, line_position=0, need_stacktrace=False, is_return_operator=False): ...
from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from app import app, db migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run()
def add_native_methods(clazz): def getVMTemporaryDirectory____(): raise NotImplementedError() clazz.getVMTemporaryDirectory____ = staticmethod(getVMTemporaryDirectory____)
"""An example of using a middleware to require HTTPS connections. requires https://github.com/falconry/falcon-require-https to be installed via pip install falcon-require-https """ import hug from falcon_require_https import RequireHTTPS hug.API(__name__).http.add_middleware(RequireHTTPS()) @hug.get() def my_en...
import sys from .space_delimited import SpaceDelimited try: from nltk.stem.snowball import SnowballStemmer stemmer = SnowballStemmer("french") except ValueError: raise ImportError("Could not load stemmer for {0}. ".format(__name__)) try: from nltk.corpus import stopwords as nltk_stopwords stopwords ...
import netaddr name = 'netaddr' version = netaddr.__version__ description = 'Pythonic manipulation of IPv4, IPv6, CIDR, EUI and MAC network addresses' keywords = [ 'Networking', 'Systems Administration', 'IANA', 'IEEE', 'CIDR', 'IP', 'IPv4', 'IPv6', 'CIDR', 'EUI', 'MAC', 'MAC-48', 'EUI-48', 'EUI-64' ] download_...
import model as Model NODES_PER_ROBOT = 6 ROBOT_CPU_CAPACITY = 100 SERVER_CAPACITY = 400 # for greedy_2 the value must be 0 ALGORITHM = 'greedy_1' # greedy_2 def generate(num_computers, num_robots, num_cameras): msgs_robot = 0 for x in range(1, num_robots + 1): msgs_robot += 8 + num_robots - x # Co...
import numpy as np import scipy.linalg as la def calculate_vertex_normals(verts, tris): v_array = np.array(verts) tri_array = np.array(tris, dtype=int) tri_pts = v_array[tri_array] n = np.cross( tri_pts[:,1] - tri_pts[:,0], tri_pts[:,2] - tri_pts[:,0]) v_normals = np.zeros(v_array....
""" 问题描述:给定一个矩阵matrix,其中的值有正、负和0,返回子矩阵的最大累加和. 例如,矩阵matrix为 -90 48 78 64 -40 64 -81 -7 66 其中,最大累加和的子矩阵为: 48 78 -40 64 -7 66 所以返回累加和209. 例如,matrix为: -1 -1 -1 -1 2 2 -1 -1 -1 其中,最大累加和的子矩阵为: 2 2 所以返回累加和为4. """ import sys from arrandmatrix.q16 import MaxSum class MaxMatrixSum: @classmethod def get_ma...
""" Created on Mon Sep 19 11:45:20 2016 @author: johnguttag """ import random, pylab, numpy pylab.rcParams['lines.linewidth'] = 4 pylab.rcParams['axes.titlesize'] = 20 pylab.rcParams['axes.labelsize'] = 20 pylab.rcParams['xtick.labelsize'] = 16 pylab.rcParams['ytick.labelsize'] = 16 pylab.rcParams['xtick.major.size'] =...
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("account", "0018_auto_20190309_1153"), ] operations = [ migrations.AddField( model_name="taggeduser", name="count", field=mod...
import sys import os extensions = [] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'Jetlibs' copyright = u'2015, Marius Messerschmidt' version = '1.0' release = '1.0' exclude_patterns = [] pygments_style = 'sphinx' html_theme = 'default' html_static_path = ['_static'] htmlhelp_b...
"""engine.SCons.Tool.msvc Tool-specific initialization for Microsoft Visual C/C++. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os.path imp...
import fresh_tomatoes import media toy_story = media.Movie("Toy Story", "A story of a boy and his toys that come to life", "http://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg", "https://www.youtube.com/watch?v=vwyZH85NQC4") avatar = media....
import os, sys, shutil if "SGE_ROOT" not in os.environ: print "scramble(): Please set SGE_ROOT to the path of your SGE installation" print "scramble(): before scrambling DRMAA_python" sys.exit(1) if os.path.dirname( sys.argv[0] ) != "": os.chdir( os.path.dirname( sys.argv[0] ) ) scramble_lib = os.path.j...
def length_of_last_word(str_): split_str = str_.split(" ") if not split_str: return 0 return len(split_str[-1]) if __name__ == '__main__': result = length_of_last_word("hello world") print(result)
from distutils.core import setup from setuptools import find_packages LONGDOC = """ A very simple python library, used to format datetime with *** time ago statement. Install pip install timeago Usage import timeago, datetime d = datetime.datetime.now() + datetime.timedelta(seconds = 60 * 3.4) print (timeago.format...
import subprocess import os """ What are the differences and similarities between ffmpeg, libav, and avconv? https://stackoverflow.com/questions/9477115 ffmeg encoders high to lower quality libopus > libvorbis >= libfdk_aac > aac > libmp3lame libfdk_aac due to copyrights needs to be compiled by end user on MacOS brew i...
import os import io import stat import time import threading import sublime import sublime_plugin TAILF_VIEWS = set() STATUS_KEY = 'tailf' class TailF(sublime_plugin.TextCommand): ''' Start monitoring file in `tail -f` line style. ''' def __init__(self, *args, **kwargs): super(TailF, self).__ini...
import logging from json import loads, dumps from datetime import datetime, timedelta from redis import Redis, RedisError from thumbor.storages import BaseStorage from thumbor.utils import on_exception from tornado.concurrent import return_future logger = logging.getLogger('thumbor') class Storage(BaseStorage): sto...
import re import string import nltk from bs4 import BeautifulSoup __author__ = 'nolram' class NewsItem: def __init__(self, news, stop_words): self.all_words = [] self.stop_words = stop_words self.regex = re.compile('[%s]' % re.escape(string.punctuation)) if "titulo" in news and "cate...
AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ) LOGIN_REDIRECT_URL = 'reviews' ACC...
import re from six.moves import zip def check_tag(root, expected): pattern = re.compile(r"{.*}([a-zA-Z]+)") for tag, el in zip(expected, root.iter()): m = pattern.match(el.tag) assert m is not None assert m.group(1) == tag, "Expect tag=%s, get %s" % (tag, m.group(1))
""" Format and compress XML documents """ import getopt import re import sys import xml.parsers.expat __version__ = "0.2.4" DEFAULT_BLANKS = False DEFAULT_COMPRESS = False DEFAULT_SELFCLOSE = False DEFAULT_CORRECT = True DEFAULT_INDENT = 2 DEFAULT_INDENT_CHAR = " " DEFAULT_INLINE = True DEFAULT_ENCODING_INPUT = None DE...
import os import sys import django def main(): """ Standalone django model test with a 'memory-only-django-installation'. You can play with a django model without a complete django app installation. http://www.djangosnippets.org/snippets/1044/ """ sys.path.append(os.path.abspath(os.path.dirname(...
import Network from time import sleep from threading import Thread CALL_ROOMLIST = 0 CALL_WEAPLIST = 1 CALL_PLAYERLIST = 2 CALL_NEWPLAYER = 3 CALL_PLAYERLEFT = 4 CALL_CHAT = 5 CALL_PLAYERDAT = 6 CALL_ROOMSTAT = 7 CALL_LEAVEROOM = 8 CALL_SHOOT = 9 CALL_SCORE = 10 class GameClient(Network.Client): CONNECTING = 0 ...
import functools import itertools import json import multiprocessing import os import shutil import sys import time import cv2 import numpy import utility.config import utility.cv import utility.geometry import utility.gui import utility.image import utility.log cv2.ocl.setUseOpenCL(False) pool = multiprocessing.Pool()...
import os from tsc.models import * def test_get_new_reservable_schedules(): old = [ Schedule(1, datetime.datetime(2015, 11, 1, 22, 00), ScheduleStatus.reservable), Schedule(1, datetime.datetime(2015, 11, 1, 23, 00), ScheduleStatus.reservable), ] new = [ Schedule(1, datetime.datetime(...
"""The application's model objects""" from zope.sqlalchemy import ZopeTransactionExtension from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base maker = sessionmaker( autoflush = True, autocommit = False, extension = ZopeTransactionExtension...
from osgeo import gdal, ogr, gdalconst import sys gdal.UseExceptions() gdal.AllRegister() src_filename = "../../aineisto/Clc2012_FI20m.tif" dstPath = "../../output" berries = ["mustikka", "puolukka", "karpalo", "vadelma"] if len(sys.argv) > 1: berries = [sys.argv[1]] corineToBerryIndex = dict() corineToBerryIndex["mus...
DEPS = [ 'git', 'recipe_engine/context', 'recipe_engine/path', 'recipe_engine/platform', 'recipe_engine/properties', 'recipe_engine/raw_io', 'recipe_engine/step', ] def RunSteps(api): url = 'https://chromium.googlesource.com/chromium/src.git' # git.checkout can optionally dump GIT_CURL_VERBOSE traces ...
from collections import defaultdict from zipfile import ZipFile from datetime import datetime from itertools import izip import logging import sys import shelve from backtest import constants def main(): PRICES_DATA = constants.PRICES_DATA performances = shelve.open(constants.CACHE_PERFS, protocol=2) ...
from functools import partial def build_tag_filter(args): """ Returns a filter which selects entries with all of the given tags only. @param list(str) args, e.g. ["+tag1", "unrelated"] @return (callable filter, list remaining_args) """ remaining_args = [] tags = set() for arg in args...
from collections import Counter from .filter import at_trigrams, with_words def count_trigrams(interactions: list, minimum: int = 1, n: int = None, include_unknown: bool = False) -> list: """Returns the n most common trigrams in the interactions given. :param interactions: The interactions to check. :type i...
import functools import tensorflow as tf import matplotlib as mpl mpl.use('TkAgg') import matplotlib.pyplot as plt import numpy as np import params as prm import matplotlib.pyplot as plt import tensorflow.contrib.slim as slim from tensorflow.examples.tutorials.mnist import input_data def doublewrap(function): """ ...
""" File: twitter_analyse.py Author: Me Email: 0 Github: 0 Description: Analyse tweets. For the detail, please refer to the document ```twitter_analyse.notes``` """ from __future__ import division import json import os from math import log import numpy from nltk.classify import NaiveBayesClassifier from textblob import...
"""Module providing views for the folderish content page type""" import json import urllib from Acquisition import aq_inner from Products.Five.browser import BrowserView from plone import api from plone.i18n.normalizer.interfaces import IIDNormalizer from zope.component import getUtility from newe.sitecontent import ut...
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from forecastiopy import * import datetime import sys from ubidots import ApiClient import time import webbrowser from threading import Thread import numpy as np import skfuzzy as fuzz from skfu...
"""Store various constants here""" from enum import Enum MAX_CONTENT_LENGTH = 1 * 1024 * 1024 * 1024 PWD_HASH_ALGORITHM = 'pbkdf2_sha256' SALT_SIZE = 24 MIN_USERNAME_LENGTH = 2 MAX_USERNAME_LENGTH = 32 MIN_PASSWORD_LENGTH = 8 MAX_PASSWORD_LENGTH = 1024 HASH_ROUNDS = 100000 PWD_RESET_KEY_LENGTH = 32 PWD_RESET_KEY_EXPIRA...