code
stringlengths
1
199k
""" This file tests some of the YAML files in the maxout paper """ import os import pylearn2 from pylearn2.datasets import control from pylearn2.datasets.mnist import MNIST from pylearn2.termination_criteria import EpochCounter from pylearn2.testing.skip import skip_if_no_gpu from pylearn2.utils.serial import load_trai...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gcp_healthcheck version_added: "2.4" short_description: Create,...
import re import subprocess def remove_long_path(): path = 'mtrand.c' pat = re.compile(r'"[^"]*mtrand\.pyx"') code = open(path).read() code = pat.sub(r'"mtrand.pyx"', code) open(path, 'w').write(code) def main(): subprocess.check_call(['cython', 'mtrand.pyx']) remove_long_path() if __name__ ...
_all_integer_type_bitwidths = [8, 16, 32, 64] int_max_bits = max(_all_integer_type_bitwidths) def int_max(bits, signed): bits = bits - 1 if signed else bits bits = max(bits, 0) return (1 << bits) - 1 def int_min(bits, signed): return (-1 * int_max(bits, signed) - 1) if signed else 0 class SwiftIntegerTy...
from __future__ import print_function, division from .cartan_type import Standard_Cartan from sympy.core.compatibility import range from sympy.matrices import eye class TypeB(Standard_Cartan): def __new__(cls, n): if n < 2: raise ValueError("n can not be less than 2") return Standard_Car...
def func(): import module module
from __future__ import unicode_literals from ctypes import windll, Structure, byref, c_uint from ctypes.wintypes import HWND, UINT, LPCWSTR, BOOL import os.path as op from .compat import text_type shell32 = windll.shell32 SHFileOperationW = shell32.SHFileOperationW class SHFILEOPSTRUCTW(Structure): _fields_ = [ ...
from __future__ import unicode_literals import datetime import itertools import tempfile from django.core.files.storage import FileSystemStorage from django.db import models from django.utils.encoding import python_2_unicode_compatible callable_default_counter = itertools.count() callable_default = lambda: next(callabl...
from django.conf import settings from django.core.handlers.base import get_path_info from django.core.handlers.wsgi import WSGIHandler from django.utils.six.moves.urllib.parse import urlparse from django.utils.six.moves.urllib.request import url2pathname from django.contrib.staticfiles import utils from django.contrib....
import fnmatch import json from webkitpy.common.editdistance import edit_distance from webkitpy.common.memoized import memoized from webkitpy.common.system.filesystem import FileSystem class Contributor(object): def __init__(self, name, email_or_emails, irc_nickname_or_nicknames=None): assert(name) ...
from openerp.osv import fields, osv class mrp_workcenter_load(osv.osv_memory): _name = 'mrp.workcenter.load' _description = 'Work Center Load' _columns = { 'time_unit': fields.selection([('day', 'Day by day'),('week', 'Per week'),('month', 'Per month')],'Type of period', required=True), 'mea...
""" pygments.styles.vs ~~~~~~~~~~~~~~~~~~ Simple style with MS Visual Studio colors. :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ ...
import socket import subprocess import sys import time import h11 import pytest import requests @pytest.fixture def turq_instance(): return TurqInstance() class TurqInstance: """Spins up and controls a live instance of Turq for testing.""" def __init__(self): self.host = 'localhost' # Test i...
import os import pexpect import re import string import subprocess import sys import time import urllib import urlparse __version__='1.43' netbsd_mirror_url = "ftp://ftp.netbsd.org/pub/NetBSD/" arch_qemu_map = { 'i386': 'qemu-system-i386', 'amd64': 'qemu-system-x86_64', 'sparc': 'qemu-system-sparc', 'ev...
from django.contrib.auth.decorators import login_required from django.core.exceptions import PermissionDenied, ValidationError from django.core.urlresolvers import reverse_lazy from django.http import HttpResponseRedirect from django.utils.decorators import method_decorator from django.views.generic import DetailView f...
from django.db import models from django.core.urlresolvers import reverse from eforge.models import Project from eforge.update.models import Update, register_update_type from eforge.vcs import project_repository class Revision(models.Model): id_no = models.AutoField(primary_key=True) id =...
from argparse import ArgumentParser import socket import struct import sys import threading import time from ._fakeds import FakeDS __all__ = ["Netconsole", "main", "run"] def _output_fn(s): sys.stdout.write( s.encode(sys.stdout.encoding, errors="replace").decode(sys.stdout.encoding) ) sys.stdout.wr...
import sys import os import shlex sys.path.insert(0, os.path.abspath('..')) extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.napoleon', ] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = 'girc' copyright = '2015, Daniel Oaks' author = 'Daniel Oaks' version = '0.1' release = ...
from funktional.layer import Layer, Dense, StackedGRU, StackedGRUH0, Convolution1D, \ Embedding, OneHot, clipped_rectify, sigmoid, steeper_sigmoid, tanh, CosineDistance,\ last, softmax3d, params, Attention from funktional.rhn import StackedRHN0 import funktiona...
def sum(*args): total = 0 for number in args: if isinstance(number, int): total += number return total print(sum(1,5))
""" File: base.py Author: Me Email: yourname@email.com Github: https://github.com/yourname Description: """ from datetime import timedelta from django.contrib.auth.models import User from django.test import TestCase from django.urls import reverse from django.utils import timezone from django.utils.crypto import get_ra...
from __future__ import print_function import numpy as np import turtle from argparse import ArgumentParser from base64 import decodestring from zlib import decompress try: _input = raw_input except NameError: _input = input '''TODO: * add a matplotlib-based plotter * add a path export function (for pasting back i...
"""Test cltk.prosody.""" __license__ = 'MIT License. See LICENSE.' from cltk.prosody.latin.scanner import Scansion as ScansionLatin from cltk.prosody.latin.clausulae_analysis import Clausulae from cltk.prosody.greek.scanner import Scansion as ScansionGreek from cltk.prosody.latin.macronizer import Macronizer import uni...
from .. import __description__ from ..defender import VkRaidDefender, data, update_data LOGO = '''\ _ _ _ _ __ _ __ _| | __ _ __ __ _(_) __| | __| | ___ / _| ___ _ __ __| | ___ _ __ \ \ / / |/ / | '__/ _` | |/ _` | / _` |/ _ \ |_ / _ \ '_ \ / _` |/ _ \ '__| ...
''' GameData.py Last Updated: 3/16/17 ''' import json, os import numpy as np import pygame as pg from GameAssets import GameAssets as ga class GameData(): """ GameData class is used to stores game state information. """ def __init__(self): ''' Method initiates game state variables. ...
"Usage: unparse.py <path to source file>" import sys import ast import cStringIO import os INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1) def interleave(inter, f, seq): """Call f on each item in seq, calling inter() in between. """ seq = iter(seq) try: f(next(seq)) except StopIteration:...
""" Setup file for youtube_podcaster. This file was generated with PyScaffold 2.4.2, a tool that easily puts up a scaffold for your new Python project. Learn more under: http://pyscaffold.readthedocs.org/ """ import sys from setuptools import setup def setup_package(): needs_sphinx = {'build_sphinx'...
"""Module for generating lexicon using Rao and Ravichandran's method (2009). """ from __future__ import unicode_literals, print_function from blair_goldensohn import build_mtx, seeds2seedpos from common import POSITIVE, NEGATIVE, NEUTRAL from graph import Graph from itertools import chain from scipy import sparse impor...
"""Astroid hooks for scipy.signal module.""" import astroid def scipy_signal(): return astroid.parse( """ # different functions defined in scipy.signals def barthann(M, sym=True): return numpy.ndarray([0]) def bartlett(M, sym=True): return numpy.ndarray([0]) def blackman(M, s...
import re import syslog from logging import Handler from logging.handlers import SysLogHandler class LocalSysLogHandler(Handler): """ Logging handler that logs to the local syslog using the syslog module """ facility_names = { "auth": syslog.LOG_AUTH, "cron": syslog.LOG_CRON, ...
""" Q4- Write a Python function, odd, that takes in one number and returns True when the number is odd and False otherwise. You should use the % (mod) operator, not if. This function takes in one number and returns a boolean """ def odd( number ): return number % 2 == 1 number = int( input( "Enter a number: ") ) print...
"""Client for interacting with the Google BigQuery API.""" from google.cloud.client import ClientWithProject from google.cloud.bigquery._http import Connection from google.cloud.bigquery.dataset import Dataset from google.cloud.bigquery.job import CopyJob from google.cloud.bigquery.job import ExtractTableToStorageJob f...
""" Rules system. """ import copy from operator import itemgetter class RuleBase(object): """ All rules inherit from RuleBase. All rules needs a condition, a response. RuleBase is the base model to all rules. with this class, the rules will can to access to the main class (Gozokia), the sentence (the in...
import functools from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar, Union import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline impo...
import os import sys import numpy as np from basic.common import checkToSkip def process(options): overwrite = options.overwrite inputeFile = options.inputeFile weightFile = options.weightFile resultFile = options.resultFile weightFile = os.path.join('result', weightFile) weight = open(weightFil...
""" functions for evaluating spreadsheet functions primary function is parse, which the rest revolves around evaluate should be called with the full string by a parent program A note on exec: This uses the exec function repeatedly, and where possible, use of it should be minimized, but the intention of this is ...
import sys PY2 = sys.version_info[0] == 2 if PY2: long = long unicode = unicode basestring = basestring from urllib import quote_plus, unquote_plus, quote, unquote from urlparse import parse_qsl else: long = int unicode = str basestring = str from urllib.parse import (quote_plus, unq...
import axiom_rules import fact_groups import instantiate import pddl import sas_tasks import simplify import sys import PrecosatSolver import copy import os import SASE_helper import SolverAdapter from SASE_helper import * from SASE_base import * import math import signal PRINT_OUT_CLAUSES = False PRINT_ALL_OP_AX = F...
default_app_config = 'bespeak_meal.apps.Bespeak_meal_config'
""" Restores the uplifted horizons while restricting slip along the fault to the specified azimuth. """ import numpy as np import matplotlib.pyplot as plt from fault_kinematics.homogeneous_simple_shear import invert_slip import data import basic def main(): azimuth = data.fault_strike + 90 def func(*args, **kwa...
from itertools import product from demos.auction_model import demo def test02(): sellers = [4] buyers = [100] results = demo(sellers, buyers, time_limit=False) expected_results = {100: 4, 4: 100} for k, v in results.items(): assert expected_results[k] == v, "Hmmm... That's not right {}={}".f...
import time,os,sys,shutil,itertools for which in ["unrar","p7zip"]: if not shutil.which(which): print("ERROR:",which,"isn't installed.\nExiting...") sys.exit(-1) def rc(rf): alphabet="aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ1234567890" start=time.time() tryn=0 for a in range(1,len(alphabet)+1): f...
import asyncio import websockets import duplex rpc = duplex.RPC("json") @asyncio.coroutine def echo(ch): obj, _ = yield from ch.recv() yield from ch.send(obj) rpc.register("echo", echo) @asyncio.coroutine def do_msgbox(ch): text, _ = yield from ch.recv() yield from ch.call("msgbox", text, async=True) rp...
import json from app.api import bp from app.easyCI.scheduler import GitlabCIScheduler from flask import current_app, url_for, make_response, request from werkzeug.local import LocalProxy logger = LocalProxy(lambda: current_app.logger) @bp.route('/dashboard/', methods=['GET']) def dashboard(): url = url_for('api.das...
"""Tests for Vizio config flow.""" from __future__ import annotations from contextlib import asynccontextmanager from datetime import timedelta from typing import Any from unittest.mock import call, patch import pytest from pytest import raises from pyvizio.api.apps import AppConfig from pyvizio.const import ( APPS...
''' Copyright 2015-2020 HENNGE K.K. (formerly known as HDE, Inc.) Licensed under MIT. ''' import json def read_event(path): with open(path) as event: data = json.load(event) return data
import numpy as np import matplotlib.pyplot as plt import pymc as pm def main(): sample_size = 100000 expected_value = lambda_ = 4.5 N_samples = range(1, sample_size, 100) for k in range(3): samples = pm.rpoisson(lambda_, size=sample_size) partial_average = [samples[:i].mean() for i in N...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('productdb', '0024_auto_20161227_1015'), ] operations = [ migrations.AlterField( model_name='productcheck', name='input_product_id...
""" This file includes commonly used utilities for this app. """ from datetime import datetime today = datetime.now() year = today.year month = today.month day = today.day def front_image(instance, filename): # file will be uploaded to MEDIA_ROOT/product_imgs/owner_<id>/product_<id>/Y/m/d/front/<filename> retur...
import pytest from freezegun import freeze_time import demistomock as demisto integration_params = { 'url': 'http://test.com', 'credentials': {'identifier': 'test', 'password': 'pass'}, 'fetch_time': '3 days', 'proxy': 'false', 'unsecure': 'false', } @pytest.fixture(autouse=True) def set_mocks(mocke...
""" Run this file to run bots as a standalone application, detached from the webapp """ from snoohelper.utils.teams import SlackTeamsController TESTING = False def main(): if not TESTING: SlackTeamsController("teams.ini", 'snoohelper_master.db') else: SlackTeamsController("teams_test.ini", 'snoo...
f = open("io/data/file1") print(f.read(5)) print(f.readline()) print(f.read())
from subprocess import check_call, call, Popen, PIPE import os import textwrap import glob os.putenv("DEBIAN_FRONTEND", "noninteractive") def get_output(cmd, **kwargs): check = kwargs.pop("check", True) kwargs["stdout"] = PIPE p = Popen(cmd, **kwargs) stdout, stderr = p.communicate() if check and p....
import omniORB, _omnipy from omniORB import CORBA, PortableServer _0_CORBA = CORBA _omnipy.checkVersion(4,2, __file__, 1) try: property except NameError: def property(*args): return None import corbaidl_idl _0_CORBA = omniORB.openModule("CORBA") _0_CORBA__POA = omniORB.openModule("CORBA__POA") import bo...
from direction import Direction, Pivot XMovement = { Direction.left: -1, Direction.up: 0, Direction.right: 1, Direction.down: 0, Direction.up_left: -1, Direction.up_right: 1, Direction.down_left: -1, Direction.down_right: 1 } YMovement = { Direction.left: 0, Direction.up: -1, ...
from rich.console import Console from rich.markdown import Markdown from rich.syntax import Syntax def process_syntax(code, lang, theme, line_numbers, code_width, word_wrap): syntax = Syntax( code, lang, theme=theme, line_numbers=line_numbers, code_width=code_width, w...
""" Sorted input and output. """ from collections import deque from operator import itemgetter from .buffer import _ReaderBuffer from .buffer import _WriterBuffer __all__ = "SortReader", "SortWriter" class _Sorter(object): """ Abstract base class for SortReader and SortWriter. """ def __init__(self, key, gr...
from configurables_akeeton_desktop import * import hashlib import java.awt.Toolkit import json import os import shutil import time Settings.ActionLogs = True Settings.InfoLogs = True Settings.DebugLogs = True Settings.LogTime = True Settings.AutoWaitTimeout = AUTO_WAIT_TIMEOUT_SECONDS TEMP_DIR...
import logging from logging.handlers import RotatingFileHandler import os from appdirs import user_cache_dir def configure_logging(): cache_dir = user_cache_dir(appname='spoppy') LOG_FILE_NAME = os.path.join( cache_dir, 'spoppy.log' ) LOG_LEVEL = getattr( logging, os.getenv('SPOP...
from locale import gettext as _ import logging logger = logging.getLogger('remarkable') from remarkable_lib.AboutDialog import AboutDialog class AboutRemarkableDialog(AboutDialog): __gtype_name__ = "AboutRemarkableDialog" def finish_initializing(self, builder): # pylint: disable=E1002 """Set up the abou...
""" SoftLayer.tests.CLI.modules.file_tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :license: MIT, see LICENSE for more details. """ from SoftLayer import exceptions from SoftLayer import testing import json import mock class FileTests(testing.TestCase): def test_access_list(self): result = self....
""" Module with simplex (Nelder-Mead) optimization for defining the flux and position of a companion using the Negative Fake Companion. """ from __future__ import print_function import numpy as np import matplotlib.pyplot as plt from scipy.optimize import minimize from .simplex_fmerit import chisquare from ..var import...
import unittest import syzoj import hashlib from random import randint class TestRegister(unittest.TestCase): def md5_pass(self, password): md5 = hashlib.md5() md5.update(password) return md5.hexdigest() def test_register(self): user = "tester_%d" % randint(1, int(1e9)) p...
import pyrfa p = pyrfa.Pyrfa() p.createConfigDb("./pyrfa.cfg") p.acquireSession("Session3") p.createOMMConsumer() p.login() p.directoryRequest() p.dictionaryRequest() RIC = "0#BMD" symbolList = p.getSymbolList(RIC) print("\n=======\n" + RIC + "\n=======") print(symbolList.replace(" ","\n"))
def RGB01ToHex(rgb): """ Return an RGB color value as a hex color string. """ return '#%02x%02x%02x' % tuple([int(x * 255) for x in rgb]) def hexToRGB01(hexColor): """ Return a hex color string as an RGB tuple of floats in the range 0..1 """ h = hexColor.lstrip('#') return tuple([x /...
from _pydev_runfiles import pydev_runfiles_xml_rpc import pickle import zlib import base64 import os from pydevd_file_utils import canonical_normalized_path import pytest import sys import time try: from pathlib import Path except: Path = None py_test_accept_filter = None def _load_filters(): global py_test...
from __future__ import print_function import time import numpy as np from mpi4py import MPI from python_compat import range comm = MPI.COMM_WORLD def r_print(*args): """ print message on the root node (rank 0) :param args: :return: """ if comm.rank == 0: print('ROOT:', end=' ') f...
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: readme = f.read() requirements = [ 'prov>=1.5.3', ] test_requirements = [ 'pydot>=1.2.0' ] setup( name='vop...
import pandas as pd from sklearn import model_selection from sklearn.ensemble import RandomForestClassifier url = "https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data" names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class'] df = pd.read_csv...
from __future__ import print_function import sys import os import warnings sys.path.insert(0, os.path.abspath('sphinxext')) from github_link import make_linkcode_resolve import sphinx_gallery import chainladder as cl extensions = ['sphinx.ext.autodoc', 'numpydoc', 'sphinx_gallery.gen_gallery', 'sphinx.ext...
from python.equal import Equal def count_steps_test(): equal_instance = Equal() array_a = [2, 2, 3, 7] array_b = [53, 361, 188, 665, 786, 898, 447, 562, 272, 123, 229, 629, 670, 848, 994, 54, 822, 46, 208, 17, 449, 302, 466, 832, 931, 778, 156, 39, 31, 777, 749, 436, 138, 289, ...
from textwrap import dedent from pprint import pformat from collections import OrderedDict import attr from . import sentinel from .ordering import Ordering def no_default_vals_in_repr(cls): """Class decorator on top of attr.s that omits attributes from repr that have their default value""" defaults = Order...
import os import random import json import collections from PIL import Image def getRGBstring( (r, g, b) ): s = "#" s = s + format(r, '02x') s = s + format(g, '02x') s = s + format(b, '02x') return s def do_compute(): # Open the image origImgFile = 'res/bryce.jpg' origImg = Image.open(origImgFile) # Proc...
import pygame black = ( 0, 0, 0) white = ( 255, 255, 255) green = ( 0, 255, 0) red = ( 255, 0, 0) pygame.init() size=[700,500] screen=pygame.display.set_mode(size) pygame.display.set_caption("My Game") done=False clock=pygame.time.Clock() while done==False: for event in pygame.event.get(...
import os if "READTHEDOCS" in os.environ: import sys import tempfile # put us on the sys.path MAKEENV_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, MAKEENV_ROOT) # to silence a warning from the makefile os.environ.setdefault("PIP_DOWNLOAD_CACHE", tempf...
from .Commerce import Commerce from .Transaction import Transaction
"""sandbox URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-bas...
from django.db import models from tweets.models import Tweet class Tag(models.Model): name = models.CharField(max_length=255, unique=True, db_index=True) is_hashtag = models.BooleanField(default=False) tweets = models.ManyToManyField(Tweet, related_name='tags') class Meta: db_table = 'tags'
'''A module containing a class for storing Creature objects in a SQLite database.''' import csv import sqlite3 __all__ = ['CreatureDB'] class CreatureDB(object): '''Class for storing Creature objects in a SQLite database.''' def __init__(self, name='creature.db', use_nominal_cr=False): self.min_cr = 0.0...
salarioXhoras = float(input('Quanto voce ganha por hora? ')) horas = float(input('Quantas horas trabalhadas? ')) salario = horas * salarioXhoras print('Voce ganhará %2.f de salario esse mes' %(salario))
from django_group_by import GroupByMixin from django.db.models.query import QuerySet class BookQuerySet(QuerySet, GroupByMixin): pass
import gtk import gobject class PyApp(gtk.Window): def __init__(self): super(PyApp, self).__init__() self.set_title("Alignment") self.set_size_request(260, 150) self.set_position(gtk.WIN_POS_CENTER) vbox = gtk.VBox(False, 5) hbox = gtk.HBox(True, 3) valign = g...
__revision__ = "test/QT/up-to-date.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog" """ Validate that a stripped-down real-world Qt configuation (thanks to Leanid Nazdrynau) with a generated .h file is correctly up-to-date after a build. (This catches a bug that was introduced during a signature refactoring...
from concurrent.futures import ThreadPoolExecutor import os import re import gzip try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import logging import mimetypes from collections import defaultdict from flask import url_for as flask_url_for from flask import current_app, re...
import os import unittest import zope.testrunner from zope import component from sparc.testing.fixture import test_suite_mixin from sparc.testing.testlayer import SPARC_INTEGRATION_LAYER from sparc.db.splunk.testing import SPARC_DB_SPLUNK_INTEGRATION_LAYER from zope import schema from zope.interface import Interface cl...
from __future__ import unicode_literals import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('operation_finance', '0020_auto_20170711_1429'), ] operations = [ migrations.AlterField( model_name='invoice', nam...
from setuptools import setup setup( name="linked list, stack, double linked list, queue, deque implementation", description="This package implements a linked list", version=0.1, license='MIT', author="Steven Than, Tatiana Weaver", author_email="email@email.com", py_modules=['linked_list', 's...
import collections CmdArgs = collections.namedtuple('CmdArgs', ['split_channels', 'merge', 'image', 'prefix', 'list', 'layer'])
class Solution: # @param A a list of integers # @param elem an integer, value need to be removed # @return an integer def removeElement(self, A, elem): if not A: return len(A) curr_idx = 0 total_array_len = len(A) while (curr_idx <= total_array_...
import unittest import pentai.base.human_player as h_m import pentai.base.rules as r_m import pentai.base.game as g_m import pentai.ai.priority_filter as pf_m import pentai.ai.utility_calculator as uc_m from pentai.ai.ab_state import * def get_black_line_counts(ab_game_state): return ab_game_state.get_utility_stats...
""" Created on Feb 09, 2018 @author: Tyranic-Moron """ from twisted.plugin import IPlugin from pymoronbot.moduleinterface import IModule from pymoronbot.modules.commandinterface import BotCommand, admin from zope.interface import implementer import re from collections import OrderedDict from pymoronbot.response import ...
DATA_DIR = '/media/d/ssd2/dstl/'
import pygame, math pygame.init() window = pygame.display.set_mode((600, 600)) pygame.display.set_caption("Fractal Tree") screen = pygame.display.get_surface() def drawTree(x1, y1, angle, depth): if depth: x2 = x1 + int(math.cos(math.radians(angle)) * depth * 10.0) y2 = y1 + int(math.sin(math.radian...
import time from os import system import bot as cleanBot def pp(message, mtype='INFO'): mtype = mtype.upper() print '[%s] [%s] %s' % (time.strftime('%H:%M:%S', time.gmtime()), mtype, message) def ppi(channel, message, username): print '[%s %s] <%s> %s' % (time.strftime('%H:%M:%S', time.gmtime()), channel, u...
from kaleidoscope.event import DataEvent from kaleidoscope.options.option_query import OptionQuery class OptionChainIterator(object): def __init__(self, data): self.data = data # get all quote dates that can be iterated self.dates = sorted(data['quote_date'].unique()) # turn list of ...
''' While x is less than 10 it will print x and add 1 to that number, then print it and so on until that condition is false, which is when x equals 10 ''' condition = input('Enter number: ') x = int(condition) print (' ') print ('While loop:') while x <= 10: print (x) x += 1 # will stop adding 1 whe...
import balanced balanced.configure('ak-test-2eKlj1ZDfAcZSARMf3NMhBHywDej0avSY') debit = balanced.Debit.fetch('/debits/WD5EW7vbyXlTsudIGF5AkrEA') debit.description = 'New description for debit' debit.meta = { 'facebook.id': '1234567890', 'anykey': 'valuegoeshere', } debit.save()
import re def getText(data): res = [] resString = "" pattern = re.compile(r"\(?M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})\)(.*?)\. *\n", re.I) iteratable = pattern.finditer(data) newPattern = re.compile(r"\(?M{0,4}CM|CD|D?C{0,3}XC|XL|L?X{0,3}IX|IV|V?I{0,3}\)", re.I) checkPattern = re.compile(r"\(?M{0,...
from lxml import etree import unicodecsv import sys import os def segment_file(prefix, filename, output_directory): print "Segmenting file", filename doc=etree.parse(os.path.join(filename)) extorgs = set(doc.xpath("//iati-activity/reporting-org/@ref")) print "Found orgs", list(extorgs) out = {} ...
import math """ The Purpose of this Program is to automate the task of Ventilation Surveying in Underground Mining Engineering. This program can accept input of tabulated values (in csv file) for Leapfrogging and Roving-Base Altimeter Indirect Method Surveys and provide data analysis and calculation output to a csv fil...