code
stringlengths
1
199k
import logging import sys import datamapper from devil.mappers.xmlmapper import XmlMapper from devil.mappers.jsonmapper import JsonMapper from devil.resource import Resource from devil.docs import DocumentedResource from devil.fields import Representation __all__ = ( Resource, Representation, DocumentedReso...
from __future__ import division, print_function print(""" This tutorial explains the usage of trigonometric polynomials and relating operators for the use in FFT-based homogenization. The basic classes, which are implemented in module "homogenize.matvec", are listed here along with their important characteristics: Grid...
import io from setuptools import setup, find_packages import sys install_requires = [] if (sys.version_info[0], sys.version_info[1]) < (3, 2): install_requires.append('futures>=2.1.3') setup( name='django-pipeline', version='1.6.9', description='Pipeline is an asset packaging library for Django.', l...
""" Check the status of our ISUSM sites being offline or online run from RUN_40_AFTER.sh """ import datetime import pytz from pyiem.tracker import TrackerEngine from pyiem.network import Table as NetworkTable from pyiem.util import get_dbconn def main(): """Go Main Go""" NT = NetworkTable("ISUSM") IEM = get...
""" Tests for L{twisted.application} and its interaction with L{twisted.persisted.sob}. """ from __future__ import absolute_import, division import copy import os import pickle from twisted.application import service, internet, app, reactors from twisted.internet import interfaces, defer, protocol, reactor from twisted...
for i in range(int(raw_input())): a, b, c = [float(x) for x in raw_input().split()] print '%.1f' % ((a * 2 + b * 3 + c * 5) / 10)
from icalendar import Calendar, Event, vDDDTypes from datetime import date INPUT_RACE_DATE = date(2015,04,26) NEW_RACE_DATE = date(2015,04,26) DT_DELTA = NEW_RACE_DATE - INPUT_RACE_DATE def date_add(dt, delta=DT_DELTA): if not isinstance(dt, date): raise ValueError('Value passed must be an object of type da...
from __future__ import division import matplotlib.pyplot as plt import matplotlib from scipy import constants as const from pylab import * from numpy import * def solutions(r_in,r_out,step,alfa,M_16,m_1,R_hv): #defining lists list_function = arange(r_in,r_out,step) R_10_l, temperature_l= ([] for i in range(2)) #com...
def OMNIORBMinorCode(c): return 0x41540000 | c def OMGMinorCode(c): return 0x4f4d0000 | c UNKNOWN_UserException = OMGMinorCode(1) UNKNOWN_SystemException = OMGMinorCode(2) UNKNOWN_PythonException = OMNIORBMinorCode(98) UNKNOWN_OmniThreadException = OMNIORBMinorCode(123) BAD_PARAM_ValueFactoryFailure = OMGMinorC...
""" Module for testing. Copyright (c) 2014 Kenn Takara See LICENSE for details """
import plivo from tests.base import PlivoResourceTestCase from tests.decorators import with_response class AccountTest(PlivoResourceTestCase): @with_response(200) def test_get(self): account_details = self.client.account.get() self.assertResponseMatches(account_details) # Verifying the e...
from argparse import Namespace from copy import deepcopy import numpy as np from scipy.special import gamma, gammainc from ..models.transforms import logsfr_ratios_to_masses from ..sources.constants import cosmo from .corner import quantile __all__ = ["params_to_sfh", "parametric_pset", "parametric_cmf", "pa...
import logging as _logging _logr = _logging.getLogger(__name__) _logr.addHandler(_logging.NullHandler()) import traitlets as tr from .menu import Menu, _BaseTraits from collections import namedtuple as _namedtuple from itertools import chain as _chain from copy import copy def link_trait(source, target): """ Th...
"""empty message Revision ID: 57128d66cc33 Revises: 324666fdfa8a Create Date: 2016-08-09 12:52:17.791059 """ revision = '57128d66cc33' down_revision = '324666fdfa8a' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(u'tag...
import re import logging import numpy as np import preprocessor as p from nltk.corpus import stopwords from nltk.tokenize import TweetTokenizer from scipy.spatial.distance import cosine from src.features import google_word2Vec_model, surpriseList, doubtList, noDoubtList def remove_stopwords_and_tokenize(tweet): """...
from GameLayer import GameLayer from pylash.core import init, addChild, removeChild, stage from pylash.display import Sprite, Bitmap, BitmapData, TextField, TextFormatWeight from pylash.loaders import LoadManage from pylash.events import MouseEvent from pylash.ui import LoadingSample2 dataList = {} beginningLayer = Non...
import os import sys sys.path.insert(0, os.path.abspath('../')) extensions = ['sphinx.ext.autodoc'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'ios-build-versions-python' copyright = u'2017, Mike Herold' author = u'Mike Herold' version = u'0.2.2' release = u'0.2.2' language =...
import os from Bio import SeqIO import io from ..nucleotide import to_seq from ..nucleotide.alignment import make_alignment from ..nucleotide.cpg import bisulfite_conversion, c2t_conversion from ..nucleotide.primer import Primer from ..util import report from ..view.baseseq_renderer import BaseseqRenderer from ..format...
import platform import os import sys import threading import tkinter as tk import tkinter.ttk as tkk from PIL import Image, ImageTk from weather_backend import Report from controller import Controller if getattr(sys, 'frozen', False): # The application is frozen app_root = os.path.dirname(os.path.abspath(sys.ex...
import time import sys import threading import cv2 import pygame import numpy from ps_drone import Drone from flightController import P3N15Controller as controller class P3N15(Drone): FRONTCAM = 0 GROUNDCAM = 1 def __init__(self): Drone.__init__(self) self.flightController = controller(self)...
import unittest try: from unittest.mock import patch except ImportError: from mock import patch import onedrivesdk from onedrivesdk.http_response import HttpResponse from onedrivesdk.request.children_collection import ChildrenCollectionRequest from onedrivesdk.model.children_collection_page import ChildrenColle...
import sys try: from setuptools import setup, Extension except ImportError: from distutils.core import setup, Extension classifiers = \ [ 'Development Status :: 4 - Beta', 'Environment :: Plugins', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System...
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'PracticasProductivas.anio' db.add_column(u'promotores_practicasproductivas', 'anio', self.gf('dja...
from flask import Flask from flask import request from flask_sqlalchemy import SQLAlchemy from flask_restful import Resource, Api import os, json app = Flask(__name__) api = Api(app) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) VAL...
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 asyncio import os import sys import time from asyncio.streams import StreamWriter, FlowControlMixin from uz.interface.telegram.bot import UZTGBot class StdOutBot(UZTGBot): _encoding = 'utf-8' _reader = None async def get_reader(self): if self._reader is None: self._reader = asynci...
import time, os, fnmatch, shutil while 1: #set up timestamp t = time.localtime() timestamp = time.strftime('%b-%d-%Y_%H%M', t) #buffy backup directory with timestamp bu_dir = os.path.join(r'.\Folder_Backup', timestamp) #set up local backup directory proj_dir = os.getcwd() local_dir = os....
""" Mnemonic condition code selector (eg. ``JAE`` / ``JNB`` / ``JNC``) """ from typing import List AE: int = 0 """ ``JAE``, ``CMOVAE``, ``SETAE`` """ NB: int = 1 """ ``JNB``, ``CMOVNB``, ``SETNB`` """ NC: int = 2 """ ``JNC``, ``CMOVNC``, ``SETNC`` """ __all__: List[str] = []
"""Tests for the tests package.""" from __future__ import absolute_import, division, unicode_literals from tests.aspects import unittest, TestCase class HttpServerProblemTestCase(TestCase): """Test HTTP status 502 causes this test class to be skipped.""" sites = { '502': { 'hostname': 'http:...
from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('wagtailcore', '__latest__'), ] operations = [ migrations.CreateModel( name='HomePage', fields=[ ('page_ptr', models.OneToOneField(on_delete=models.CASCAD...
import os.path as op import psutil def _abspath(path): return op.abspath(op.expanduser(path)) def gather_notebooks(): """ Gather processes of IPython Notebook Return ------ notes : list of dict each dict has following keys: "pid", "cwd", and "port" Raises ------ RuntimeError ...
import os from os import environ try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse CSRF_ENABLED = True if os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'local_config.py')): from wlmetricsweb.local_config import * else: SECRET_KEY = environ...
import sys verbose = False def set_v(v): global verbose verbose = v def print_v(s): if verbose: print(s) def write_v(s): if verbose: sys.stdout.write(s)
from __future__ import unicode_literals import frappe, unittest import requests from frappe.model.delete_doc import delete_doc from frappe.utils.data import today, add_to_date from frappe import _dict from frappe.limits import update_limits, clear_limit from frappe.utils import get_url from frappe.core.doctype.user.use...
import enum import time import atexit import os import pprint import numpy as np import pybullet as p import pybullet_data GRAVITY = -9.81 atexit.register(p.disconnect) try: p.disconnect() except Exception: pass p.connect(p.GUI) p.setAdditionalSearchPath(pybullet_data.getDataPath()) p.resetSimulation() p.resetD...
from functools import partial import threading from PyQt5.QtCore import Qt, QEventLoop, pyqtSignal from PyQt5.QtWidgets import (QVBoxLayout, QLabel, QGridLayout, QPushButton, QHBoxLayout, QButtonGroup, QGroupBox, QDialog, QLineEdit, QRadioButton, QCheckBox, QWid...
"""Test tabular environments and tabular MCE IRL.""" import gym import numpy as np import pytest from imitation.algorithms.tabular_irl import ( LinearRewardModel, MLPRewardModel, mce_irl, mce_occupancy_measures, mce_partition_fh, ) from imitation.envs.examples.model_envs import RandomMDP from imitat...
from smisk.test import * import smisk.core.xml as xml class XMLTests(TestCase): def setUp(self): pass def test_encode(self): #Encode/escape unsafe character in XML encoded = xml.escape('Some <document> with strings & characters which should be "escaped"') expected = 'Some &lt;document&gt; with strin...
import os from contextlib import suppress import mock import pytest from graphql import build_ast_schema, parse from gql import Client, gql from gql.transport import Transport from gql.transport.exceptions import TransportQueryError with suppress(ModuleNotFoundError): from urllib3.exceptions import NewConnectionErr...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=...
from django.conf import settings from django.contrib.auth.models import User from timebank import get_notifications def timebank_notifications(request): notifications=get_notifications(request.user) return {"notifications":notifications}
class Node: """ A node is an object that may be contained in the stack defined below. """ def __init__(self, value): """ Initialize the node with a provided value. """ self.value = value self.next = None class Stack: """ A stack is an abstract data type th...
""" No mocks! Ensure that hooks work by extending them and overriding methods with emulated side-effects. """ from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from django.test.testcases import TestCase from .. import hooks from .base import TestHookMix...
import os import typing from cauldron import cli from cauldron import environ from cauldron.session import projects from cauldron.session.writing import file_io from cauldron.session.writing.components import definitions from cauldron.session.writing.components.definitions import COMPONENT from cauldron.session.writing...
import collections import inspect import itertools import os import sys from functools import wraps from inspect import * from spiralx import Props __all__ = [] def exported(f): __all__.append(getattr(f, "__name__", f.func_name)) return f def export_names(*names): newnames = set(__all__) - set(names) __all__.ex...
""" This is an example of pyCardDeck, it's not meant to be complete poker script, but rather a showcase of pyCardDeck's usage. """ import pyCardDeck import random import requests arena_deck = pyCardDeck.Deck(reshuffle=False, name="Awesome arena deck!") rarity = {"Common": 100, "Rare": 50, "Epic": 15, "Legendary": 1} de...
import webbrowser import os import re main_page_head = ''' <!DOCTYPE HTML> <html> <head> <title>Movie Store | Recent Movies</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="application/x-javascript"> addEvent...
""" [example_weight_ignored] $ vwoptimize.py -d simple_w.csv --columnspec y,drop,text,text --metric acc 2>&1 | egrep 'weighted|acc' weighted example sum = 3.000000 weighted label sum = 4.000000 acc = 0.666667 [example_weight] $ vwoptimize.py -d simple_w.csv --columnspec y,weight,text,text 2>&1 --metric acc | egrep 'wei...
import logging import notify2 import subprocess import config logger = logging.getLogger('notify') def init(program): notify2.init(program) def send(title, message): logger.info('send notify "{}" "{}"'.format(title, message)) notify2.Notification(title, message).show() if config.sounds and config.sound_...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf mnist = input_data.read_data_sets('MNIST_data/', one_hot=True) sess = tf.InteractiveSession() x = tf.placeholder(tf.float32, sha...
from __future__ import generators import copy, time from wxPython.wx import * from PyPlotter import Gfx, wxGfx, Graph, Colors import Induction #importiert das Induktionsprogramm """Teichnen einen MatLabähnlichen SchwarzweissPlot. ist nur am InstitutsPC installiert- das ist nun numpy matplotlib in sitepackages in Lib v...
from pymongo import MongoClient from pymongo import ReadPreference import os import mysql.connector as mysql metrics_mysql_password = os.environ["METRICS_MYSQL_PWD"] mongoDB_metrics_connection = os.environ["MONGO_PATH"] sql_host = os.environ["SQL_HOST"] query_on = os.environ["QUERY_ON"] to_workspace = os.environ["WRK_S...
from __future__ import unicode_literals from functools import reduce, wraps import operator import threading import django from django.db import models from django.db.models.base import ModelBase from django.db.models.query import Q from django.utils import six from django.utils.translation import ugettext as _ from mp...
import logging import ConfigParser from IGWrapper import IGWrapper import DeepThaw from urllib import urlencode config = ConfigParser.RawConfigParser() config.read('config.cfg') logging.basicConfig(level=config.getint('logs', 'level')) print "Using client id: " + config.get('API', 'client_id') print "Using access token...
from utils import get_url from utils import SupplyResult subreddit = 'disneyvacation' t_channel = '@r_disneyvacation' def send_post(submission, r2t): what, url, ext = get_url(submission) title = submission.title link = submission.shortlink text = '{title}\n\n{link}\n{channel}'.format( title=title, link=link, chan...
""" test_pyperi ---------------------------------- Tests for `pyperi` module. """ import requests import httpretty import pytest # noqa from unittest import mock from pyperi import Peri, PyPeriConnectionError @httpretty.activate def test_request_api(): mock_url = ( 'https://api.periscope.tv/api/v2/testEndp...
from django.shortcuts import render from django.http import HttpResponse, Http404, HttpResponseBadRequest from django.contrib.gis.measure import Distance from pprint import pformat; from voxel_globe.world.models import WorldBorder import voxel_globe.world.tasks as tasks def index(request): return HttpResponse(('Reque...
from __future__ import absolute_import, print_function import Live from ableton.v2.base import listens, forward_property, clamp, listenable_property, depends, task, liveobj_valid, liveobj_changed from ableton.v2.control_surface import Component from ableton.v2.control_surface.control import ButtonControl, ToggleButtonC...
''' The Project's object provides a basic interface for interacting with the project database used by the GUI. ''' import os.path import sqlite3 import sys from datetime import datetime from openmdao.gui.util import ensure_dir, print_dict def get_user_dir(): user_dir = os.path.expanduser("~/.openmdao/gui/") ens...
chars = """08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 ...
from hamming_distance import hamming_distance def immediate_neighbors(pattern): neighborhood = [pattern] pattern_length = len(pattern) for i in range(0, pattern_length): symbol = pattern[i:i + 1] nucleodits = ["A", "C", "G", "T"] nucleodits.remove(symbol) for x in nucleodits: neighbor = patt...
from app.notify_client import NotifyAdminAPIClient class BillingAPIClient(NotifyAdminAPIClient): # Fudge assert in the super __init__ so # we can set those variables later. def __init__(self): super().__init__("a" * 73, "b") def init_app(self, application): self.base_url = application.co...
from setuptools import setup, find_packages from genologics.version import __version__ import sys, os import subprocess import glob try: version = subprocess.Popen(["git", "describe", "--abbrev=0"],stdout=subprocess.PIPE, universal_newlines=True).communicate()[0].rstrip() version = version.decode("utf-8") excep...
__author__ = 'AprocySanae' __date__ = '15/4/4' from ..evaluations import Base class If(Base): def __init__(self): super(If, self).__init__() self.instant_eval = False self.result = None def set_result(self, value): self.result = value def eval(self, env): if_node = ty...
import random import twitter import os EAT_OPTIONS_FILE = "eat_options.txt" PLAY_OPTIONS_FILE = "play_options.txt" def get_all_eat_options(): eat_options = [line.strip() for line in open(EAT_OPTIONS_FILE)] return eat_options def get_all_play_options(): play_options = [line.strip() for line in open(PLAY_OPTI...
import os, sys, math import numpy as np import numpy.ma as ma import matplotlib.pyplot as plt import pyspeckit from scipy.optimize import curve_fit from astropy.io import fits from astropy.units import Quantity c = 299792.458 # [km/s] there should be a way to get 'c' from astropy.units ? vlsr = None na = len(sys.ar...
"""Iterable query results. """ import pydocumentdb.backoff_retry_utility as backoff_retry_utility import pydocumentdb.errors as errors import pydocumentdb.http_constants as http_constants class QueryIterable(object): """Represents an iterable object of the query results. """ def __init__(self, options, retr...
"""A simple script to download all Gmail emails with a given label. This script will write a CSV file with the name passed to '--output-file'. The CSV file will have the format: <sender domain name>,<email subject>,<email text> The label you wish to download all emails from is provided with '--label' and is the labe...
import time, os, sys, transpositionEncrypt, transpositionDecrypt def main(): inputFilename = 'frankenstein.txt' # BE CAREFUL! If a file with the outputFilename name already exists, # this program will overwrite that file. outputFilename = 'frankenstein.encrypted.txt' myKey = 10 myMode = 'encrypt...
''' tests/test_waf_parser.py ''' from catalog_harvesting.waf_parser import WAFParser from unittest import TestCase class TestWAFParser(TestCase): def test_maracoos_waf(self): maracoos_waf = 'http://sos.maracoos.org/maracoos-iso/' parser = WAFParser(maracoos_waf) # Just care about the links, ...
import numpy as np import numexpr as ne '''Numpy implimantation of lomb-scargle periodgram''' def lombscargle_num(x, y, freqs): # Check input sizes if x.shape[0] != y.shape[0]: raise ValueError("Input arrays do not have the same size.") # Create empty array for output periodogram pgram = np.empt...
import logging from django.db import models from django.utils.functional import cached_property from django.utils.translation import ugettext_lazy as _ from reviewboard.attachments.models import FileAttachment from reviewboard.reviews.models.base_comment import BaseComment logger = logging.getLogger(__name__) class Fil...
import subprocess import json import vim import re import os import sys from sys import platform enclosing_types = [] # nothing to see here current_enclosing = -1 atom_bound = re.compile('[a-z_0-9A-Z\'`.]') re_wspaces = re.compile("[\n ]+") re_spaces = re.compile(" +") re_spaces_around_nl = re.compile(" *\n *") protoco...
""" @copyright: 2007-2014 Quotemaster cc. See LICENSE for details. """ from twisted.trial.unittest import TestCase from entropy.errors import UnknownHashAlgorithm, DigestMismatch class ExceptionTests(TestCase): """ Tests for exception classes. """ def test_unknownHashAlgorithm(self): """ ...
''' Defines functions which are called by the PyGeoNS executables. These are the highest level of plotting functions. There is a vector plotting function and a strain plotting function. Both take data dictionaries as input, as well as additional plotting parameters. ''' from __future__ import division import numpy as n...
from confutil import rprint, assert_request import confutil from skitai import testutil from skitai.handlers import vhost_handler import skitai import os def test_websocket_handler (wasc, app, client): @app.route ("/echo") def echo (was, message): if was.wsinit (): return was.wsconfig (skitai.WS_SIMPLE, 60) el...
from search_engine import TSearchEngine from utils import TCustomCounter from lib.collect_bigrams_map import collect_bigrams_map from lib.collect_bigrams_reduce import collect_bigrams_reduce from datetime import datetime import sys import os books_dir = sys.argv[1] intermid_results_dir = sys.argv[2] bigrams_indices_dir...
from flask import Flask app = Flask(__name__, template_folder="templates") from app import controllers
from qrl.core.Transaction_subtypes import TX_SUBTYPE_STAKE, TX_SUBTYPE_TX, TX_SUBTYPE_COINBASE from collections import OrderedDict, namedtuple from pyqrllib.pyqrllib import getHashChainSeed, bin2hstr from qrl.core import config, logger from qrl.core.ChainBuffer import ChainBuffer from qrl.core.Transaction import Transa...
''' Work of Cameron Palk ''' import sys import pandas as pd def getDifferenceMatrix( csv ): df = pd.read_csv( csv ) all_labels = sorted(df.Label.unique()) RF_matrix = { label: [0 for _ in all_labels] for label in all_labels } P_matrix = { label: [0 for _ in all_labels] for label in all_labels } KNN_matrix = { labe...
import os import hashlib import stat def symbolic_notation(path): # TODO: Assert no ACL-s, SELinux context or extended attributes are present attribs = os.lstat(path) mode = attribs.st_mode # Derived from /usr/include/bits/stat.h m = "?fc?d?b?-?l?s?"[mode >> 12] m += "-r"[mode >> 8 & 1] m +=...
import scrapy from scrapy import Request class PWResults(scrapy.Spider): name = "pw-results" def start_requests(self): if self.endpoint=='archive': urls = [ 'https://web.archive.org/web/20160823114553/http://eciresults.nic.in/PartyWiseResultS03.htm?st=S03', 'h...
from __future__ import unicode_literals import codecs from os import path import unittest from self_descriptive_sentence.chinese import Chinese class TestChineseNumber(unittest.TestCase): RESOURCES_PATH = path.join(path.dirname(path.abspath(__file__)), 'resources') def setUp(self): self.number_data_path...
from nose.tools import * from dateutil.parser import parse as time_parse import yawhois class TestWhoisCentralnicComUkComStatusRegistered(object): def setUp(self): fixture_path = "spec/fixtures/responses/whois.centralnic.com/uk.com/status_registered.txt" host = "whois.centralnic.com" ...
from __future__ import unicode_literals import json import os import time from pgoapi.utilities import f2i from pokemongo_bot import inventory from pokemongo_bot.constants import Constants from pokemongo_bot.human_behaviour import sleep from pokemongo_bot.worker_result import WorkerResult from pokemongo_bot.base_task i...
"""Performs face alignment and calculates L2 distance between the embeddings of two images.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from scipy import misc import tensorflow as tf import numpy as np import sys import os import argparse import facene...
''' Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (including target) will be positive integers....
import ast import sys import os UP = 'U' DOWN = 'D' LEFT = 'L' RIGHT = 'R' TEAM_NAME = "Improved closest v2" allMoves = [UP, UP, UP, UP, UP, RIGHT, UP, RIGHT, UP, RIGHT, RIGHT, RIGHT, RIGHT, UP, RIGHT, RIGHT] def debug (text) : # Writes to the stderr channel sys.stderr.write(str(text) + "\n") sys.stderr.flu...
""" invo - An Inverse Optimization Library invo is a Python package intended to simplify the use of inverse optimization as a model fitting practice. Our goal is to provide a general framework for formulating and solving inverse optimization problems, as well as implement a collection of inverse methods. As additional ...
''' Creates surfaces based on defined node-sets on parts in Abaqus. For each node set defined for a part, a seperate surface containing all the nods is created. ''' from abaqus import * import mesh def defineAllPartSurfaces(model): ''' Define all surfaces for all parts. For each node set, a surface that cov...
from fractions import Fraction def solve() -> int: multiplied = Fraction(1, 1) for i in range(1, 10): for j in range(1, 10): for k in range(1, 10): if Fraction(i, k) == Fraction(i * 10 + j, j * 10 + k): multiplied *= Fraction(i, k) return multiplied.de...
""" Exception Syntax: try: #You do your oprations here. except ExceptionI: #If the is ExceptionI, then execute this block except ExceptionII: #If the is ExceptionI, then execute this block ...................... else: If there is no exception then execute this block. ...
from sys import argv import webbrowser import praw import yaml import datetime import time def main(subreddit, daysaftercreated): # Convert daysaftercreated to an integer blurts error if doesn't. daysaftercreated = int(daysaftercreated) # Load reddit configuration as dictionary yamlfile = yaml.load(open...
: from .admintemplate import page : from .. import table_args, caption_args : def authtemplate title, ctx, requestlist : using page title, ctx, lang="en" <div class='container'> <div class='row'> <div class='span12'> <form id='loginform' class='form-horizontal' action='/admin/a...
print "Enter numbers to be sorted (seperated by space)" iplist = map(int, raw_input().split()) for index in xrange( 1, len(iplist) ): currentvalue = iplist[index] position = index while ( position > 0 and iplist[position-1] > currentvalue ): iplist[position] = iplist[position-1] position = p...
import urllib from bs4 import BeautifulSoup as Soup import lxml class InvalidLinkException(Exception): def __init__(self, value): self.parameter = value def __str__(self): return repr(self.parameter) class xkcd(object): def __init__(self): try: xkcdHtml = urllib.urlopen("http://xkcd.com/archive").read() ...
"""Serves static content for "static_dir" and "static_files" handlers.""" import base64 import errno import httplib import mimetypes import os import os.path import re import zlib from google.appengine.api import appinfo from google.appengine.tools import augment_mimetypes from google.appengine.tools.devappserver2 impo...
import sys import redis import argparse parser = argparse.ArgumentParser( description='Pushes data from stdin to redis channels' ) parser.add_argument('channels', metavar='channel', nargs='+', help='the channels/lists to publish the data on') parser.add_argument('--host', ...
""" Provides test-related code that can be used by all tests. """ import os import pystache from pystache import defaults from pystache.tests import examples _DEFAULT_TAG_ESCAPE = defaults.TAG_ESCAPE _TESTS_DIR = os.path.dirname(pystache.tests.__file__) DATA_DIR = os.path.join(_TESTS_DIR, 'data') # i.e. 'pystache/test...
from supriya.tools.ugentools.Filter import Filter class MoogFF(Filter): r''' :: >>> source = ugentools.In.ar(bus=0) >>> moog_ff = ugentools.MoogFF.ar( ... frequency=100, ... gain=2, ... reset=0, ... source=source, ... ) >>> moog...