code
stringlengths
1
199k
__version__ = "0.4.4" """ Publish the a python package as AWS lambdas functions. """ import logging import os import pprint import shutil import types import boto3 from unix_dates import UnixDate logger = logging.getLogger(__name__) def aws_lambda(role_arn, timeout=60, memory=128, description="", vpc_config=None): ...
import qctests.EN_constant_value_check import util.testingProfile import numpy import util.main as main class TestClass(): parameters = { "table": 'unit' } def setUp(self): # this qc test will go looking for the profile in question in the db, needs to find something sensible main.fak...
from collections import namedtuple import collections import email import json import sqlite3 import sys import urllib.request as urlreq import esi_load CHUNK_SIZE = 100 ITEM_LIST = 'items' EVECENTRAL_HOURS = 48 MARKET_HUB = 'Jita' ColumnProperties = namedtuple('ColumnProperties', ['display_name', 'is_numeric']) column...
import cv2 import os import numpy as np from plantcv.plantcv._debug import _debug from plantcv.plantcv import apply_mask from plantcv.plantcv import fatal_error from plantcv.plantcv import params def _hist(img, hmax, x, y, h, w, data_type): hist, bins = np.histogram(img[y:y + h, x:x + w], bins='auto') max1 = np...
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "torchmed.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
from __future__ import division, print_function import numpy as np import matplotlib.pyplot as plt import pdb plt.ion() def rotate_mat(theta): #Clockwise rotation of vectors. mat = np.array([[np.cos(theta), np.sin(theta)],[-np.sin(theta),np.cos(theta)]]) return mat mount_sep = 30. bandpass_sep = 0.024*160 p...
import os import json import tempfile import subprocess from subprocess import PIPE class DictJsonEncoder( json.JSONEncoder ): def default( self, obj ): return obj.__dict__ class Config( object ): def __init__( self, driveFile=None ): self.driveFile = driveFile def newConfigFromDict( dct ): ...
import sublime import sublime_plugin import os from .rust import (messages, rust_proc, rust_thread, util, target_detect, cargo_settings, semver) from pprint import pprint """On-save syntax checking. This contains the code for displaying message phantoms for errors/warnings whenever you save a Rust fi...
import psutil class MemoryCollector(object): @staticmethod def get_usage(): return psutil.virtual_memory()._asdict()
"""Common settings and globals.""" from os.path import abspath, basename, dirname, join, normpath from sys import path DJANGO_ROOT = dirname(dirname(abspath(__file__))) SITE_ROOT = dirname(DJANGO_ROOT) SITE_NAME = basename(DJANGO_ROOT) path.append(DJANGO_ROOT) DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = ( ('Your ...
import config import handlers.base import models.base from models.task import TaskLock def main(): config.init_logging() app = handlers.base.app app.config['SQLALCHEMY_DATABASE_URI'] = config.SQLALCHEMY_DATABASE_URI models.base.init_db(app) with app.app_context(): for lock in models.base.db....
""" Django settings for personRegister project. Generated by 'django-admin startproject' using Django 1.8.6. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ import os...
import os import logging import uuid from xml.etree import ElementTree as ET from PyDatcomLab.Core.DictionaryLoader import defaultDatcomDefinition as DtDefine from PyDatcomLab.Core.datcomXMLLoader import datcomXMLLoader from PyDatcomLab.Core import datcomTools as dtTools from PyDatcomLab.Core import datcomDimension ...
import ul_gsm as gsm
""" PostgreSQL database backend for Django. Requires psycopg 2: http://initd.org/projects/psycopg2 """ import logging import sys from django.db import utils from django.db.backends import * from django.db.backends.signals import connection_created from django.db.backends.postgresql_psycopg2.operations import DatabaseOp...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('boards', '0014_auto_20160805_2004'), ] operations = [ migrations.AddField( model_name='board', name='estimated_number_of_hours', ...
from os.path import join from setuptools import setup, find_packages from setuphelp import current_version, PyTest, Updater, Clean DESCRIPTION = 'Define and read input files with an API inspired by argparse' try: with open('README.rst') as fl: LONG_DESCRIPTION = fl.read() except IOError: LONG_DESCRIPTIO...
import sys import pygame import pygame.locals as pgl import bds.constants as c import bds.input class Game(object): def __init__(self): pygame.init() self.screen = pygame.display.set_mode(tuple(c.SCREEN_DIMENSIONS)) self.running = False self.mode = None self.input = bds.input...
""" Simple math types to represent Vector, Matrix, Quaternion If the blender mathutils module is available, the blender API types are used, but otherwise a (minimally) compatible internal type is used instead. Also included are tools to create from simple lists, and convert between the EDM and blender axis interpretati...
from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) exce...
from rest_framework import serializers from rest_auth.registration.serializers import RegisterSerializer from allauth.account.adapter import get_adapter from allauth.account.utils import setup_user_email from . import models from nomadgram.images import serializers as images_serializers class UserProfileSerializer(seri...
import unittest from gamebuilder import GameBuilder from dataaccess import Room, Exit, ExitUnlockingItem, ItemUnlockingItem, Player class FakeDatabaseService(object): def __init__(self): self.row_id = 0 self.rooms = [] self.exits = [] self.exit_unlocking_items = [] self.item_unlocking_items = [] ...
import logging from six.moves.urllib.parse import urlparse from scrapy.utils.boto import is_botocore from scrapy.extensions.feedexport import BlockingFeedStorage logger = logging.getLogger(__name__) class S3FeedStorage(BlockingFeedStorage): def __init__(self, uri): from scrapy.conf import settings u...
from enum import Enum, EnumMeta from six import with_metaclass class _CaseInsensitiveEnumMeta(EnumMeta): def __getitem__(self, name): return super().__getitem__(name.upper()) def __getattr__(cls, name): """Return the enum member matching `name` We use __getattr__ instead of descriptors o...
''' Make life easier with util funcs ''' from requests import post, delete def task_sender(name=None, file_path=None, interval=None): ''' :name => name of task :file_path => '/path/to/your_script.py' :interval => time interval in seconds returns job id ''' if not all([name,fi...
from ircb.lib.constants.signals import (STORE_USER_CREATE, STORE_USER_CREATED, STORE_USER_GET, STORE_USER_GOT) from ircb.models import get_session, User from ircb.stores.base import BaseStore session ...
import random __author__ = 'Mushahid Khan' from django.core.management.base import BaseCommand, CommandError from feedback_survey.models import FeedbackTemplate, Section , SectionField class SectionFieldTypes: TEXT = 'text' SUB_SECTION = 'sub_section' RADIO = 'yes_no_radio' class Command(BaseCommand): h...
import torch import numpy import torch.nn as nn import torch.nn.utils.prune as prune from torch.nn.utils.prune import ( BasePruningMethod, _validate_pruning_amount_init, _compute_nparams_toprune, _validate_pruning_amount ) class MinMaxPrune(BasePruningMethod): PRUNING_TYPE = "unstructured" def __init__(...
from nose.tools import assert_equal, assert_raises import calc def test__group_tokens(): test_input = [ 1.0, '+', 2.0, '*', '(', 3.0, '-', 4.0, '/', '(', 5.0, '^', 6.0, ')', '+', 7.0, ')', '*', 8.0, '-', 9.0 ] test_output = [ 1.0, '+', 2.0, '*', [ 3.0, '-', 4.0, '...
from powerprompt.core import ColorBlock from powerprompt.segments import BaseSegment import sh class VcsSegment(BaseSegment): name = 'vcs' vcs_type = None def __init__(self, settings): super(VcsSegment, self).__init__(settings) self.fg_color_dirty = getattr(settings, 'fg_color_dirty', 239) ...
from django.apps import AppConfig class PhysicalConfig(AppConfig): name = 'physical'
"""Exceptions used by Home Assistant.""" class BluMateError(Exception): """General Home Assistant exception occurred.""" pass class InvalidEntityFormatError(BluMateError): """When an invalid formatted entity is encountered.""" pass class NoEntitySpecifiedError(BluMateError): """When no entity is spe...
"""Fluke drivers Driver following the technical note entitled: "Fluke 189/187/98-IV/87-IV Remote Interface Specification" """ import unittest import pyhard2.driver as drv Cmd, Access = drv.Command, drv.Access def _parse_measure(x): """Return measure.""" return float(x.split(",")[1].split()[0]) def _parse_unit(x...
"""SMACT benchmarking.""" from .utilities import timeit from ..structure_prediction.mutation import CationMutator class MutatorBenchmarker: """Benchmarking tests for CationMutator.""" @timeit def run_tests(self): """Initialize Mutator and perform tests.""" self.__cm_setup() self.__pa...
string = input() reversed_string = string[::-1] print(reversed_string)
from matplotlib import pyplot as plt for i in range(4): count = 0 plt.subplot(220+i+1) plt.axis((-20,20,-20,20)) with open("%d" % i,"r") as f: for line in f.readlines(): if line[0] != '\t': b = line.split("\t") before = [float(b[0]),float(b[1])] plt.plot([float(b[0]) - 1,float(b[0]) + 1],[float(b[1...
import os import pathlib import sys import yaml from .web.app import app __all__ = 'load_config', 'read_config', 'read_config_from_py',\ 'read_config_from_yaml' def load_config(config_file=None): if config_file is None: config_file = os.getenv('HIKIKOMORI_CONFIG', None) if config_file: ...
from redis import Redis from lua_call import function conn = Redis() function .call_external(""" return CALL.example.return_args({}, {4, 5, 6, ARGV}) """, conn)
from typing import List, Union from pyrep.objects.object import Object from pyrep.objects.proximity_sensor import ProximitySensor from pyrep.objects.force_sensor import ForceSensor from pyrep.robots.robot_component import RobotComponent import numpy as np POSITION_ERROR = 0.001 class Gripper(RobotComponent): """Rep...
def main(): # Test suite tests = [ [None, None], # Should throw a TypeError [4, 3], [7, 13] ] for item in tests: try: temp_result = fib_memoization(item[0]) if temp_result == item[1]: print('PASSED: fib_memoization({}) returned {}'....
import os import webbrowser import json import folium from requests import get def colorgrad(minimum, maximum, value): minimum, maximum = float(minimum), float(maximum) ratio = 2 * (value - minimum) / (maximum - minimum) b = int(max(0, 255 * (1 - ratio))) g = int(max(0, 255 * (ratio - 1))) r = 255 -...
import unittest def insertion_sort(seq): pass class OrdenacaoTestes(unittest.TestCase): def teste_lista_vazia(self): self.assertListEqual([], insertion_sort([])) def teste_lista_unitaria(self): self.assertListEqual([1], insertion_sort([1])) def teste_lista_binaria(self): self.ass...
__author__ = "Can Ozbek Arnav" import pandas as pd import numpy as np import pylab import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix import sys sys.path.append("/Users/ahmetcanozbek/Desktop/EE660/660Project/Code_Final_Used/functions") import ml_aux_functions as ml_aux import crop_rock df_full...
from __future__ import unicode_literals import os import re import shutil import tempfile import unittest import mock import sh import coveralls.git GIT_COMMIT_MSG = 'first commit' GIT_EMAIL = 'me@here.com' GIT_NAME = 'Daniël' GIT_REMOTE = 'origin' GIT_URL = 'https://github.com/username/Hello-World.git' class GitTest(u...
import requests import json from django.http.response import HttpResponse, Http404 from grade_parser.models import Program, Keyword from recommender import Recommender class KeywordsNotFoundException(Exception): pass def _get_slots_from_globo_api(url): str_content = requests.get(url).content content = json....
from typing import Any, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpRes...
'''Base Module for Sensor Collection Management''' import functools import collections import logging import multiprocessing import os import subprocess logger = logging.getLogger(__name__) __all__ = ['RA_DELIMITER', 'RA_FIELDS'] intconv = functools.partial(int, base=0) RA_DELIMITER = ',' RA_FIELDS = collections.Ordere...
import json import mischief.actors.process_actor as pa class MinionServer(pa.ProcessActor): def act(self): while True: self.receive( start=self.start ) def start(self, msg): with open('/msg', 'w') as f: f.write(json.dumps(msg)) class Another(pa...
__copyright__ = 'Copyright 2017-2018, http://radical.rutgers.edu' __author__ = 'Vivek Balasubramanian <vivek.balasubramaniana@rutgers.edu>' __license__ = 'MIT' import os import json import pika import time import threading as mt import radical.utils as ru from .. import exceptions as ree from .. ...
from xyppy.debug import DBG, warn, err from xyppy.zmath import to_signed_word import xyppy.ops as ops from xyppy.six.moves import range class VarForm: pass class ShortForm: pass class ExtForm: pass class LongForm: pass class ZeroOperand: pass class OneOperand: pass class TwoOperand: pass cla...
from datetime import datetime from flask import abort from blinker import signal from app import db post_save = signal('post_save') pre_delete = signal('pre_delete') class PrimaryKeyMixin(object): id = db.Column(db.Integer, primary_key=True) class CreateAndModifyMixin(object): created_at = db.Column(db.DateTime...
import numpy import six from chainer import cuda from chainer import function from chainer.utils import type_check def _extract_gates(x): r = x.reshape((x.shape[0], x.shape[1] // 4, 4) + x.shape[2:]) return (r[:, :, i] for i in six.moves.range(4)) def _sigmoid(x): return 1 / (1 + numpy.exp(-x)) def _grad_si...
class Solution(object): def numberToWords(self, num): """ :type num: int :rtype: str """ if num == 0: return 'Zero' table1 = [ '', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'T...
"""Prioritization scheme for identifying follow up variants in tumor-only samples. Generalizes the filtering scheme used in VarDict post-processing: https://github.com/AstraZeneca-NGS/VarDict/blob/9ffec9168e91534fac5fb74b3ec7bdd2badd3464/vcf2txt.pl#L190 The goal is to build up a standard set of prioritization filters b...
"""Pibooth main module. """ import os import shutil import logging import argparse import os.path as osp import pygame import pluggy import pibooth from pibooth import fonts from pibooth import language from pibooth.utils import (LOGGER, configure_logging, set_logging_level, print_columns_wor...
from __future__ import division from os import path from 21L import Image from subprocess import Popen SRC='img/reload_scaled.png' DST='../../src/qt/res/movies/update_spinner.mng' TMPDIR='/tmp' TMPNAME='tmp-%03i.png' NUMFRAMES=35 FRAMERATE=10.0 CONVERT='convert' CLOCKWISE=True DSIZE=(16,16) im_src = Image.open(SRC) if ...
import random import time import sys fname="/dev/snd/midiC2D0" keymin=int(60) keymax=int(72) fin=open(fname,"rb") fout=open(fname,"wb") print ("Exercise:") print ("Do three tones close. Reach out play any three tones one handed. We listen , we unlock the sounds with our ears so we here each note discretly and then we s...
import datetime from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.conf import settings def notify_callback_created(case): to = settings.CALL_CENTRE_NOTIFY_EMAIL_ADDRESS if not to: return from_address = "no-reply@digital.justice.gov.uk...
"""Unit tests for cron API.""" def test_cron_bad_originator(app): """Test cron API from bad origin address.""" token = app.cron_helper.get_cron_token() client = app.test_client() response = client.post( '/api/cron/1234/unit_test', environ_base={'REMOTE_ADDR': '192.168.1.1'} ) ass...
import motor.motor_asyncio from typing import Dict class KekDB(object): def __init__(self): """ Connect to MongoDB """ self.client = motor.motor_asyncio.AsyncIOMotorClient() self.db = self.client['svh'] self.quotes = self.db['quotes'] self.quote_log = self.db[...
import time import sqlite3 import pandas as pd def run(): con = sqlite3.connect("GE_Data.db") cur = con.cursor() tables = cur.execute("select name from sqlite_master where type = 'table'") print('Tables in db: ' + str(tables.fetchall())) print('Todays date: ' + str(time.strftime("%d_%m_%Y"))) print('Enter request...
import common LOG_DIR = common.script_dir() + '/logs/' LOG_PATH = LOG_DIR + 'spider.log' ERROR_PATH = LOG_DIR + 'spider_error.log' common.ensure_dir(LOG_DIR) def log(c): print c common.append_file(LOG_PATH,'\n[' + common.now_time() + ']' + str(c) + '\n') def error(e): print e common.append_file(ERROR_PA...
import pcapy def FindNw(): devs = pcapy.findalldevs() print(devs) FindNw()
import requests from bs4 import BeautifulSoup as BS busstoplist=[] f=open("busstop.txt" ,"r") for line in f: busstoplist.append(line.rstrip('\n')) for bustsop2 in busstoplist: r=requests.get("http://mtcbus.org/Places.asp?cboSourceStageName=ADYAR+B.S.&submit=Search.&cboDestStageName="+bustsop2) soup=BS(r.text,'html.p...
''' Run this script from the root of the repository to update all translations from transifex. It will do the following automatically: - fetch all translations using the tx tool - post-process them into valid and committable format - remove invalid control characters - remove location tags (makes diffs less noisy) ...
import argparse import os import codecs import re import regex from collections import deque def directory_of_file(filename): return os.path.dirname(os.path.realpath(filename)) def load_lines(filename): with codecs.open(filename, "r", "utf-8") as file: lines = [line for line in file] return line...
__author__ = 'deonheyns' import argparse from logfind import Logfind def main(): parser = argparse.ArgumentParser(description='Logfind...') parser.add_argument('-o', nargs='?', help='uses or logic to find text in log files. As in deon OR has OR blue OR eyes') args, text = parser.pars...
__author__ = 'cloud' import unittest class TestPromise(unittest.TestCase): def testPromise(self): pass def test2(self): print('test2') suite = unittest.TestSuite() suite.addTests(unittest.TestLoader().loadTestsFromModule(__name__)) if __name__ == '__main__': unittest.main(defaultTest=suite)
import sys import pprint pprint.pprint(sys.path)
import sys, os, re from flask import Flask, render_template, request from pymongo import MongoClient from bson import json_util import config import json from pyelasticsearch import ElasticSearch elastic = ElasticSearch(config.ELASTIC_URL) def process_search(results): records = [] if results['hits'] and results['hi...
__version__ = "2.3.3"
from __future__ import absolute_import from __future__ import unicode_literals import pytest from pre_commit_hooks.autopep8_wrapper import main @pytest.mark.parametrize( ('input_src', 'expected_ret', 'output_src'), ( ('print(1 + 2)\n', 1, 'print(1 + 2)\n'), ('print(1 + 2)\n', 0, 'print(1 + 2)...
__author__ = 'Vivian Liu' print("Hello from the master branch.")
import os import glob import shutil import os.path try: from setuptools import setup, Extension, Command except ImportError: from distutils.core import setup, Extension, Command exec(open('hoedownpy/_version.py').read()) dirname = os.path.dirname(os.path.abspath(__file__)) class BaseCommand(Command): user_o...
import writeformattedcsv import endpoints import datetime import time import logging import os __author__ = 'Rich Pearce' class DownloadByDateRange(): # setup logger logger = logging.getLogger('NBA API logger') csv_writer = None api_util = None def __init__(self, api_util): if not os.path.ex...
from Maps import PinExtractor class Chapter: def __init__(self, name, state, district, lat, lng, stat): self.name = name self.state = state self.district = int(district) self.lat = float(lat) self.lng = float(lng) self.stat = stat # TODO add population field that...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('frontend', '0037_auto_20181130_2130'), ] operations = [ migrations.AddField( model_name='presentation', name='quantity_means_pack...
from json import loads from flask_babel import gettext from findex_gui.web import app, db from findex_gui.orm.models import Options class OptionsController: @staticmethod def get(key: str): return Options.query.filter(Options.key == key).first() @staticmethod def set(key: str, val: dict): ...
import keras import numpy as np from keras.preprocessing import image from .IClassifier import IClassifier class ImageClassifier(IClassifier): """ классификатор изображений """ def __init__(self): self.__input_shape = None self.__aliases = None self.__model = None def init_classifier...
import zlib from django.core.signing import JSONSerializer, Signer, b64_decode, b64_encode from django.utils.encoding import force_bytes def fixed_dumps(obj, key=None, salt='core.signing', serializer=JSONSerializer, compress=False): """ The code is extracted from django.core.signing.loads Returns URL-safe, ...
from sys import version_info if version_info >= (2, 6, 0): def swig_import_helper(): from os.path import dirname import imp fp = None try: fp, pathname, description = imp.find_module('_example', [dirname(__file__)]) except ImportError: import _example ...
from __future__ import unicode_literals AUTHOR = 'Wyatt Gray' SITENAME = "Wyatt's Blog" SITEURL = '' PATH = 'content' TIMEZONE = 'Europe/Paris' DEFAULT_LANG = 'en' FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None AUTHOR_FEED_ATOM = None AUTHOR_FEED_RSS = None LINKS = (('Pelican', 'http://getp...
''' NPR Puzzle 2018-11-04 https://www.npr.org/2018/11/04/663572384/sunday-puzzle-can-you-convert-these-euros Think of an article of apparel in eight letters. Drop the last 2 letters. Move what are the now the last 2 letters to the front. You'll get an article of apparel in 6 letters. What is it? ''' import sys sys.path...
""" WSGI config for vir_manager project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTI...
import traceback import socket import random import time import pickle CORRUPT_P = 0.3 LOST_P = 0.1 TIMEOUT = 6 DEBUG = True class Packet: def __init__(self,mess,seqnum,ip,port): self.is_corrupt = False self.mess = mess self.seqnum = seqnum self.ip = ip self.port = port def m...
import OOMP newPart = OOMP.oompItem(9056) newPart.addTag("oompType", "ICIC") newPart.addTag("oompSize", "HQFN33") newPart.addTag("oompColor", "X") newPart.addTag("oompDesc", "KLPC33") newPart.addTag("oompIndex", "01") OOMP.parts.append(newPart)
import inputsCommon def get_tenant_data(tenantId): return { "policy:tenant": { "id": tenantId, "name": "GBP-FAAS-POC", "forwarding-context": { "l2-bridge-domain": [ { "id": "bridge-domain1", "parent": "l3-context-vrf-red" ...
import wx, os, sys from Config import * from Debugger import * from Colors import * from Updater import * class Header(wx.StaticText): def __init__(self,parent,id,text,font,color,pos=(200,12)): wx.StaticText.__init__(self,parent,id,text,pos=pos) self.SetFont(font) self.SetForegroundColour(co...
'''app.booker.book''' import os from flask import g, render_template, request from datetime import datetime, time from .. import get_keys from app.lib import mailgun from app.lib.dt import to_local, to_utc, ddmmyyyy_to_dt from app.main.etapestry import EtapError, call, get_udf from app.routing.build import create_order...
from ChannelSelection import ChannelSelection, BouquetSelector, SilentBouquetSelector from Components.ActionMap import ActionMap, HelpableActionMap from Components.ActionMap import NumberActionMap from Components.Harddisk import harddiskmanager from Components.Input import Input from Components.Label import Label from ...
from pybrain import BrainFuck_Int import time version = "0.1.0" tape = [0] * 30000 pointer = 0 print """PyBrain v{} (Wil Steadman)""".format(version) counter = 1 while True: prog = raw_input("pb ({}) #".format(counter)) time1 = time.time() interpreter = BrainFuck_Int(prog, tape, pointer) time2 = time.ti...
class Solution: @staticmethod def charval(char: str) -> int: return ord(char) - ord("a") @staticmethod def sign(x: int) -> int: if x < 0: return -1 return 1 def alphabetBoardPath(self, target: str) -> str: target = target.lower() result = "" ...
import pytest from plover import system from plover.config import DEFAULT_SYSTEM_NAME from plover.registry import registry @pytest.fixture(scope='session', autouse=True) def setup_plover(): registry.update() system.setup(DEFAULT_SYSTEM_NAME) pytest.register_assert_rewrite('plover_build_utils.testing')
""" xlwings - Make Excel fly with Python! Homepage and documentation: http://xlwings.org See also: http://zoomeranalytics.com Copyright (C) 2014, Zoomer Analytics LLC. All rights reserved. License: BSD 3-clause (see LICENSE.txt for details) """ import sys import numbers from . import xlplatform, string_types, time_type...
tocrack = "d0763edaa9d9bd2a9516280e9044d885" def fastfind(hashtocrack): with open('hashtabble.txt', 'r') as f: lines = f.readlines() for l in lines: parts = l.split(':') if len(parts) == 2: if parts[0] == hashtocrack: return parts[1] return "not found" print(fastfind(tocrack))
x=float(raw_input("Input a number: ")) if x%1==0: print("whole number") else: print("decimal") print("Done.")
"""Shape object for The Tragedy of the Falling Sky. Movement handling to the child blocks happens here. """ from __future__ import division import pygame import random from fallingsky.block import Block from fallingsky.util import Coord IMADEVELOPER = False class Shapes(object): """A lazymans enum to represent the ...
__author__ = 'simranjitsingh' import csv import mysql.connector import time import datetime from calculate_score import calBrevity, calcReadability, calcPersonalXPScores, escape_string cnx = mysql.connector.connect(user='merrillawsdb', password='WR3QZGVaoHqNXAF', host='awsdbinstance.cz5m3w...
from django.conf.urls import patterns, include, url from django.contrib import admin import sample from django.conf.urls.static import static import settings urlpatterns = patterns('', # Examples: # url(r'^$', 'sampleapp.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/',...
import logging, time from autotest_lib.client.common_lib import error from autotest_lib.client.virt import virt_utils def run_migration(test, params, env): """ KVM migration test: 1) Get a live VM and clone it. 2) Verify that the source VM supports migration. If it does, proceed with the te...