code
stringlengths
1
199k
''' Created on Oct 10, 2017 In order to run this service, 2 ini files are required: - local_svc.ini - contains cofig properties for this service. This currently includes: - HOST - host of the service - PORT - port on which it will listen ...
from mumax2 import * setgridsize(128, 128, 1) setcellsize(1e-6, 1e-6, 1e-6) load('current') load('solver/euler') savegraph('graph.png') setv('dt', 1e-15) setv('E_ext', [1, 0, 0]) setv('r', 1.7e-3) # Cu resist = makearray(1, 4, 4, 1) for i in range(0,4): for j in range(0,4): resist[0][i][j][0] = 1 resist[0][1][2][0] ...
import random def gaussian(T, N, particle_mass=None, zero_momentum=True, seed=7654321, kb=1.0): """Generates velocities with temperature T according to a Maxwell-Boltzmann distribution. Args: T: The desired temperature expre. N: The number of particles. particle_mass: The list of particl...
"""`pyjector` package. Provides the main depedency-injection class utilities """ from __future__ import absolute_import __author__ = 'Papavassiliou Vassilis' __date__ = '2015-3-28' __version__ = '0.0.1' __all__ = ['InjectionError', 'Injector'] from pyjector.pyjector import *
import os from lxml import html from django.urls import reverse from django.test import TransactionTestCase, override_settings, tag from dashboard.models import DataDocument, Product, ProductToPUC from dashboard.tests.loader import fixtures_standard from django.core.exceptions import ObjectDoesNotExist @override_settin...
""" Important note: bad regexes that cause catastrophic backtracking can hang your Python processes (especially because Python's re does not release the GIL! If you are putting this module behind a web server be wary of ReDoS attacks. Unfortunately there is no clean way around that, so make sure to set processing killi...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: azure_rm_mysqlconfiguration_info version_added: "2.8" short_des...
from PySide.QtNetwork import * from PySide.QtCore import * from PySide.QtGui import * from subprocess import Popen, PIPE class EPISODE(QListWidgetItem): def __init__(self, parent=None, title='<Title>', value='<Value>'): super(EPISODE, self).__init__(parent) self.title = title self.value = va...
"""minimal package setup""" import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="magpysv", version="1.1", author="Grace Cox", author_email="gracecox@cp.dias.ie", license="MIT", url="https://gith...
import sys, os, time import threading try: import queue except ImportError: import Queue as queue try: import cymysql as mdb except ImportError: sys.exit("\nPlease install cymysql for python 3, \ninformation can be found in INSTALL.txt\n") import subprocess import string import lib.info as info import signal import...
import urllib import urllib2 import re import sys import os import time import socket from StringIO import StringIO import gzip application_log_enabled = True module_log_enabled = True http_debug_log_enabled = True LIST = "list" THUMBNAIL = "thumbnail" MOVIES = "movies" TV_SHOWS = "tvshows" SEASONS = "seasons" EPISODES...
import sys import os sys.path.append(os.path.expanduser('~/wikisource')) from ws_namespaces import page as page_prefixes, index as index_prefixes import re import tempfile import os from common import ws_utils from common import utils import pywikibot from pywikibot import pagegenerators as pagegen def is_imported_page...
import xml.etree.ElementTree as ET import os,sys import datetime templatexml = 'config/config.xml' outxml = 'config/DVA1_VLA.xml' os.system('cp '+templatexml+' '+outxml) tree = ET.parse(outxml) root = tree.getroot() root.set('name','DVA1/JVLA-A') root[0].text = " 'Example configuration file made with pyxml' " """ A...
""" Packager: pip """ import re import subprocess from pybombs.packagers.extern import ExternCmdPackagerBase, ExternPackager from pybombs.utils import sysutils from pybombs.utils import subproc PIP_INSTALLED_CACHE = None class ExternalPip(ExternPackager): """ Wrapper for pip """ def __init__(self, logge...
from django.db import models, migrations TIPOS = ['SPAM','Estafa','Extorsión'] def add_tipos(apps, schema_editor): Tipo = apps.get_model("backend", "Tipo") for titulo in TIPOS: Tipo.objects.create(titulo=titulo) def del_tipos(apps, schema_editor): Tipo = apps.get_model("backend", "Tipo") for tit...
''' Author: Vedant Wakalkar Python Program to subtract two Matrices of size m*n. ''' def input_matrix(m,n): # m,n -> size of Matrix (m*n) mat = [] for i in range(m): # Enter space seperated input for elements of matrix # Enter 'n' no. of elemnts row wise and press enter for next row elements temp = ma...
type = "passive" def handler(fit, container, context): fit.modules.filteredItemBoost( lambda mod: mod.item.requiresSkill("Shield Operation") or mod.item.requiresSkill("Capital Shield Operation"), "shieldBonus", container.getModifiedItemAttr("shieldBoostMultiplier"))
from django.conf.urls import patterns from django.http import HttpResponse import json from snf_django.lib import api from logging import getLogger log = getLogger(__name__) urlpatterns = patterns( 'synnefo.api.extensions', (r'^(?:/|.json|.xml)?$', 'demux'), (r'^/([\w-]+)(?:/|.json|.xml)?$', 'demux_extensio...
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('ABC', '0041_auto_20180207_0036'), ] operations = [ migrations.AlterField( model_name='event', name='customer', field=models....
import os import sys try: from setuptools import setup setup except ImportError: from distutils.core import setup setup( name='radosgw-admin', version='1.7.1', author='Valery Tschopp', author_email='valery.tschopp@gmail.com', include_package_data=True, requires=['boto'], install_...
import settings import os mydir = os.path.dirname(os.path.abspath(__file__)) simulationSettings = settings.SimulationSettings() modelSettings = settings.ModelSettings() analogSignalRecordingSettings = settings.DataSettings() spikeRecordingSettings = settings.DataSettings() changeSettings = settings.ChangeSettings() sim...
from __future__ import unicode_literals import frappe from frappe.utils import flt, cstr, nowdate, nowtime from erpnext.stock.utils import update_bin from erpnext.stock.stock_ledger import update_entries_after def repost(only_actual=False, allow_negative_stock=False, allow_zero_rate=False, only_bin=False): """ Repost...
from __future__ import absolute_import, division, print_function import time from datetime import datetime, timedelta import uuid from copy import deepcopy from invenio_db import db from invenio_workflows import workflow_object_class, Workflow def build_workflow(workflow_data, data_type='hep', extra_data=None, status=N...
import sys class GofedTest(): pass if __name__ == "__main__": sys.exit(1)
"""Permissions $Id: permission.py 67630 2006-04-27 00:54:03Z jim $ """ from zope.interface import implements from zope.component import queryUtility, getUtilitiesFor from zope.security.checker import CheckerPublic from zope.security.interfaces import IPermission class Permission(object): implements(IPermission) ...
from __future__ import print_function import time, sys, json, os, re from oqt import elements def intm(f): if f<0: return int(f*10000000-0.5) return int(f*10000000+0.5) def addto(res, filterempty=False): def _(bls): res.extend((b for b in bls if (b is not None) and (not filterempty or len(b)...
from plainbox.provider_manager import setup, N_ setup( name='plainbox-provider-simple', namespace='com.example', version="1.0", description=N_("A really simple Plainbox provider"), gettext_domain="com_example_simple", )
import copy import errno import os import time import random import lit.Test # pylint: disable=import-error import lit.TestRunner # pylint: disable=import-error from lit.TestRunner import ParserKind, IntegratedTestKeywordParser \ # pylint: disable=import-error from libcxx.test.executor import LocalExecutor...
import threading def checksrvs(s,listsrvs): msg = [] for ctrl in listsrvs: tt = serverthreads(ctrl) if not tt: msg.append(s + '_' + ctrl) if len(msg) == 0: msg = None return msg def infothreads(): msg = [] ths = threading.enumerate() for th in ths: try: ...
def cal(): respuesta= max(sum(int(c) for c in str(a**b)) for a in range(100) for b in range(100)) return str(respuesta) if __name__ == "__main__": print(cal())
from ghstats import issueDir from operator import itemgetter import os import re import json import argparse from datetime import datetime def createContributionDict(repoPath, fileList): contribDict = {} lines = [] for x in fileList: with open(os.path.join(repoPath, x)) as f: lines = lin...
import sys import os import re import errno import json if not len(sys.argv) > 2: sys.exit(16) infile = sys.argv[1] regex = sys.argv[2] try: statefile = sys.argv[3] except: statefile = "log_state.json" def open_file(filename, mode='r', ifnotexists=None): ''' filename - path to file mode - mode t...
from util import hook, scheduler, user, database, formatting import re @hook.command(autohelp=False,adminonly=True) def mask(inp,bot=None,input=None,db=None): if inp: mask = user.get_hostmask(inp,db) else: mask = input.mask return formatting.output(db, input.chan, 'hostmask', [mask]) def compare_hostmasks(h...
from xml.dom import minidom HEADER_TEMPL = """\ /*this file is auto_generated by volk_register.py*/ struct VOLK_CPU volk_cpu; //implement get cpuid for gcc compilers using a copy of cpuid.h //implement get cpuid for MSVC compilers using __cpuid intrinsic static inline unsigned int cpuid_eax(unsigned int op) { unsig...
import ctools import time try: import matplotlib.pyplot as plt has_matplotlib = True except: has_matplotlib = False def unbinned_pipeline(model_name, duration): """ Unbinned analysis pipeline. """ # Set script parameters caldb = "prod2" irf = "South_50h" ra ...
""" Generate artificial datasets """ import os import random from optparse import OptionParser from nupic.data.file_record_stream import FileRecordStream def _generateCategory(filename="simple.csv", numSequences=2, elementsPerSeq=1, numRepeats=10): """ Generate a simple dataset. This contains a bu...
""" Converts a native Python dictionary into an XML string. Supports int, float, str, unicode, list, dict and arbitrary nesting. """ from __future__ import unicode_literals __version__ = '1.5.6' version = __version__ from random import randint import collections import logging import sys from xml.dom.minidom import par...
from __future__ import division, absolute_import, print_function import numpy as np import math import random def Read_Reactions(): mollist = [] etot = [] # read molecules and energies with open('mols.txt','r') as f: for line in f: dat = line.split() mollist.append(dat[0]...
"""Occpation number objects.""" import warnings import numpy as np from ase.units import Hartree from gpaw.utilities import erf from math import pi class OccupationNumbers: """Base class for all occupation number objects.""" def __init__(self, fixmagmom): self.fixmagmom = fixmagmom self.magmom =...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fortios_report_style short_description: Report style configur...
from helper.libexporter.exportHTML import * LibExporterRepository = { "html": exportHTML }
""" wid_tty_monitor a serial port packet monitor that plots live data using PyQwt This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. revision 0.1 2017/abr mlabru initial release (Linux/Pyth...
""" Copyright 2011-13 Attila Zseder Email: zseder@gmail.com This file is part of hunmisc project url: https://github.com/zseder/hunmisc hunmisc is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version...
import tornado.web import tornado.ioloop import threading import utility import controller import api import model.periodical app = tornado.web.Application([ # The API... Hereeee we go. ('/api/grid/exists', api.grid.Exists), ('/api/grid/info', api.grid.Info), ('/api/socket', controller.SocketHandler), ...
""" Bybit exchange subclass """ import logging from typing import Dict from freqtrade.exchange import Exchange logger = logging.getLogger(__name__) class Bybit(Exchange): """ Bybit exchange class. Contains adjustments needed for Freqtrade to work with this exchange. Please note that this exchange is not...
import argparse import logging from PyQt5 import QtGui import mops.app import mops.gui_systems import mops.preferences import mops.logger def main(): mops.logger.init() mops.logger.log.info('log folder:%s' % mops.logger.get_log_folder()) parser = argparse.ArgumentParser() parser.add_argument('-t', '--te...
import sys import os sys.path.insert(0, os.path.abspath('../build/swig/python')) extensions = [ 'sphinx.ext.mathjax', 'sphinx.ext.autodoc', ] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = 'despeckCL' copyright = '2015-2019, Gerald Baier' version = '0.1' release = '0.1' ex...
#** Interface to the edit control. #**/ #* The License.txt file describes the conditions under which this software may be distributed. */ #* file which contains any comments about the definitions. HFacer.py does the generation. */ #* hold a pointer and sptr_t, a signed integer large enough to hold a pointer. #* M...
import cookielib import urlparse,urllib2,urllib,re import os import sys from core import logger from core import config from core import scrapertools from core.item import Item from servers import servertools __channel__ = "xhamster" __category__ = "X" __type__ = "generic" __title__ = "xHamster" __language__ = "ES" __a...
"""The qutebrowser test suite conftest file.""" import os import sys import warnings import pathlib import pytest import hypothesis from PyQt5.QtCore import PYQT_VERSION pytest.register_assert_rewrite('helpers') from helpers import logfail from helpers.logfail import fail_on_logging from helpers.messagemock import mess...
import vcsn from test import * def check(num_sccs, a): for algo in ['dijkstra', 'kosaraju', 'tarjan_iterative', 'tarjan_recursive']: scc = a.scc(algo) CHECK(scc.is_isomorphic(a)) CHECK_EQ(num_sccs, scc.num_components()) CHECK_EQ(num_sccs, scc.condense().info()['number of states']) a ...
'''Definition of all excpetions in HORTON''' class SymmetryError(Exception): '''Exception raised when some symmetry algorithm fails''' pass class ElectronCountError(ValueError): '''Exception raised when a negative number of electron is encountered, or when more electrons than basis functions are requ...
import glob import numpy as np v = np.array( dirin = '01_pfamSaccharomyces/' V = [] for l in Ls: ftxt = open(l,'r').readlines() V.append( (l,len(ftxt[1].strip()),len(set(ftxt[1].strip().lower()))) )
''' TEcalc, Tao-Eldrup calculator (text mode interface). Translates oPs lifetime into pore size using the Tao-Eldrup model and also the "Rectangular Tao-Eldrup model" See: TL Dull et al., J. Phys Chem B 105, 4657 (2001) ''' ''' This file is part of PAScual. PAScual: Positron Annihilation Spectroscopy data analysis...
from couchpotato.core.event import fireEvent from couchpotato.core.helpers.encoding import tryUrlencode from couchpotato.core.helpers.rss import RSS from couchpotato.core.logger import CPLog from couchpotato.core.providers.nzb.base import NZBProvider from couchpotato.environment import Env from dateutil.parser import p...
import pytest from mock import MagicMock, ANY, AsyncMock from randovania.cli.commands import randomize_command from randovania.games.game import RandovaniaGame from randovania.layout.base.cosmetic_patches import BaseCosmeticPatches from randovania.interface_common.options import Options from randovania.interface_common...
from django.db import models from edc_base.model_fields.custom_fields import OtherCharField from edc_base.model_managers import HistoricalRecords from ..managers import CurrentSiteManager from edc_base.model_validators import date_not_future from edc_constants.choices import YES_NO_NA from edc_visit_tracking.managers i...
import math def jNumberInteger(n, e): tmp = math.pow(n, 1.0 / e) tmp = str(tmp).split('.') if tmp[1] != '0': return False else: return True def sumN1toN2Cube(n1, n2, e): sum = 0 while (n1 <= n2): sum += math.pow(n1, e) n1 += 1 return sum def cubeEq(n,e): s...
from .user import *
""" WSGI config for ankblog 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.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_M...
from matplotlib import pyplot as plt import numpy as np import csv data = [] with open("data.dat") as f: reader = csv.reader(f) for row in reader: data.append(np.asarray(row, dtype=np.float)) data = list(zip(*data)) plt.plot(data[0],data[1], label="training set") plt.plot(data[0],data[2], label="validat...
""" gp.py contains utility functions related to computation in Gaussian processes. """ import numpy as np import scipy.linalg as spla import scipy.optimize as spo import scipy.io as sio import scipy.weave SQRT_3 = np.sqrt(3.0) SQRT_5 = np.sqrt(5.0) def dist2(ls, x1, x2=None): # Assumes NxD and MxD matrices. # C...
import asyncio, hashlib, urllib import urllib.request as urllib2 from http.cookiejar import CookieJar from random import randrange, randint, random import re import hangups import plugins __cleverbots = dict() """ Cleverbot API adapted from https://github.com/folz/cleverbot.py """ class Cleverbot: """ Wrapper o...
from __future__ import unicode_literals from django.db import migrations forward_sql = """ CREATE OR REPLACE FUNCTION get_financial_year_start() RETURNS date IMMUTABLE AS $$ BEGIN IF (EXTRACT(month from CURRENT_DATE) < 4) THEN RETURN ('04-01-'||EXTRACT(year from CURRENT_DATE) - 1)::date; ELSE ...
from django.contrib import admin from django.contrib.admin.filters import SimpleListFilter from django.contrib.admin.views.decorators import staff_member_required from django.db.models.aggregates import Count from django.conf.urls import url from django.http import HttpResponse from jane.waveforms import models import ...
__author__ = 'traviswarren' import datetime from django.test import TestCase from django.core.urlresolvers import reverse from django.contrib.auth.models import User from train_track.tests.model_factory import EventFactory class EventArchiveViewTestCases(TestCase): def setUp(self): self.user = User.objects....
''' Driver method to run the SasCalc module ''' import sys import sascalc as sascalc import sassie.interface.input_filter as input_filter import sassie.interface.sascalc_filter as sascalc_filter import multiprocessing svariables = {} runname = 'run_0' pdbfile = 'new_lysozyme.pdb' dcdfile = 'new_lysozyme.pdb' xon = 'neu...
""" (C) Copyright 2009 Igor V. Custodio This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be u...
import gnomekeyring class Keyring(object): """Interface between Config and Gnome Keyring.""" def __init__(self, app_name, app_desc): self.keyring = gnomekeyring.get_default_keyring_sync() self.app_name = app_name self.app_desc = app_desc def get_password(self, auth_token): pa...
""" Traces: Activity Tracker Copyright (C) 2015 Adam Rule with Aurélien Tabard, Jonas Keper, Azeem Ghumman, and Maxime Guyaux Inspired by Selfspy and Burrito https://github.com/gurgeh/selfspy https://github.com/pgbovine/burrito/ You should have received a copy of the GNU General Public License along with Traces. If not...
import ExtractNodes ExtractNodes.DoIt("Compact", debug=False)
from typing import Callable import zmq from jsonschema import validate, ValidationError class ZmqServer: def __init__( self, transformer: Callable[[dict], dict], port=5555, validation_schema=None ): self._transformer = transformer context = zmq.Context() socket = context.socket(z...
class PluginMount(type): """ A plugin mount point derived from: http://martyalchin.com/2008/jan/10/simple-plugin-framework/ Acts as a metaclass which creates anything inheriting from Plugin """ def __init__(cls, name, bases, attrs): """Called when a Plugin derived class is imported""...
import random, logging, itertools class PeopleMatcher(object): def __init__(self): self.data=[] self.honoredProhibited = 0 def __repr__(self): return str(self.data) def setHonoredProhibited(self, val): self.honoredProhibited = int(val) def addPerson(self, person, prohibited=[]): for o in pro...
""" Emerge operation to build and install a package together with all required dependencies. We're cool like gentoo. :3 """ import sys import gettext __trans = gettext.translation('pisi', fallback=True) _ = __trans.ugettext import pisi import pisi.context as ctx import pisi.util as util import pisi.data.dependency as d...
from rootpy import log as rlog from . import log; log = log[__name__] import ROOT from ..units import GeV from .. import datasets import os from math import sqrt import ROOT ignore_fit_warning = rlog['/ROOT.Fit'].ignore('Fit data is empty') class MMC(object): INITED = False def __init__(self, year): if ...
''' A simple experimental browser which also stores sites and categories in the DB First version: 12 Aug 2009 Upgrade to GTK3: 27 Mar 2016 Fixes for Python v3: 27 Oct 2019 ''' import os import sys import gi gi.require_version('Gtk', '3.0') gi.require_version('WebKit2', '4.0') from BrowserUtility import * from gi.reposi...
import uuid def GetMacAddr(): mac = uuid.UUID(int = uuid.getnode()).hex[-12:] return ':'.join([mac[x:x+2] for x in range(0, 11, 2)])
import copy import datetime import json import os import time import unittest import httpretty import pkg_resources import requests pkg_resources.declare_namespace('perceval.backends') from grimoirelab_toolkit.datetime import datetime_utcnow from perceval.backend import BackendCommandArgumentParser from perceval.errors...
import pika connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='hello') while True: data = raw_input('>>>') if data == 'q': break channel.basic_publish(exchange='', routing_key='hello', body=data) ...
from sys import stdin from os import urandom from time import localtime from types import NoneType from syslog import syslog, LOG_CRIT from base64 import b64encode from hmac import HMAC from argparse import ArgumentParser from subprocess import Popen, PIPE import re salt_data = None salt_day = None salt_size = 16 entit...
from __future__ import print_function import math import os import time from pymavlink import quaternion from pymavlink import mavutil from common import AutoTest from common import AutoTestTimeoutException from common import NotAchievedException from common import PreconditionFailedException import operator testdir = ...
import ParticleStats_Maths as PS_Maths import math import numpy as na import os,sys from PIL import Image, ImageDraw, ImageColor import glob import re def Colourer (Word, Colour, Mode, Weight,Size): W_S = "" W_E = "" if(Weight == "bold"): W_S = "<B>" W_E = "</B>" elif(Weight == "italics"): W_S = "<I>" ...
""" This file contains the Qudi hardware file to control SRS SG devices. Qudi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Qudi is distrib...
from .. import fredutil import binary_search def _reverse_watch_main_thread(dbg, s_expr, s_expr_val): """Perform 'reverse-watch' command on expression, *only* in the main thread of the program. Return True if reverse-watch succeeded, or False if it failed.""" fredutil.fred_debug("Starting reverse-watch ...
from __future__ import unicode_literals import frappe import unittest class TestQualityProcedure(unittest.TestCase): def test_quality_procedure(self): test_create_procedure = create_procedure() test_create_nested_procedure = create_nested_procedure() test_get_procedure, test_get_nested_procedure = get_procedure(...
from __future__ import print_function from __future__ import unicode_literals from django.http import HttpResponse from lizard_map import coordinates from lizard_map.views import AppView from lizard_sticky.models import Sticky from lizard_sticky.models import Tag class StickyBrowserView(AppView): """Show sticky bro...
import abc from common.utils.attack_utils import UsageEnum from monkey_island.cc.database import mongo from monkey_island.cc.services.attack.technique_reports import AttackTechnique, logger class UsageTechnique(AttackTechnique, metaclass=abc.ABCMeta): @staticmethod def parse_usages(usage): """ P...
Altura =float(input("Qual a sua Altura?")) Peso = float(input("Qual o seu Peso?")) IMC = Peso / (Altura * Altura) print(IMC)
from astropy.io import fits from astropy.wcs import WCS from astropy import coordinates from astropy import units as u from astropy.time import TimeDelta from astropy.time import Time from astropy.table import Table from .catalog import Query from .astronomy import FitsOps from .astronomy import AstCalc from .astronomy...
from django.conf import settings from django.core.exceptions import PermissionDenied from django.template.response import TemplateResponse from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404, redirect from django.core.urlresolvers import reverse from django.views.dec...
file = 'text.txt' commands = ('add', 'subtract', 'divide', 'multiply') with open(file) as objectItem: lines = objectItem.readlines() lines = [x.strip('\n').lower() for x in lines] for num, content in enumerate(lines): if content in commands: try: if 'result:' in lines[num + 3 ]: ...
from __future__ import print_function import sys from django.core.management.base import BaseCommand from django.core.exceptions import ValidationError from bhp066.apps.bcpp_subject.models import SubjectConsent from edc_consent.models.consent_type import ConsentType class Command(BaseCommand): help = ('Updates the ...
from __future__ import absolute_import from __future__ import print_function import os from setuptools import setup, find_packages def read(fname): orig_content = open(os.path.join(os.path.dirname(__file__), fname)).readlines() content = "" in_raw_directive = 0 for line in orig_content: if in_ra...
''' This is an example of using Stillinger-Weber nonbonded 3-body potential (Si melt). The initial configuration is a diamond structure. A result is radial distribution function 'rdf.dat' (units - [nm]) ''' import sys import time import math import espresso import mpi4py.MPI as MPI from espresso import Real3D f...
from django.db import migrations, transaction from django.core.exceptions import ObjectDoesNotExist def load_initial_data(apps, schema_editor): Badge = apps.get_model('badges', 'Badge') BadgeType = apps.get_model('badges', 'BadgeType') print("AUTOCOMMIT!!!!:", transaction.get_autocommit()) db_alias = sc...
""" """ __version__ = "$Id$" import smtplib server = smtplib.SMTP('mail') server.set_debuglevel(True) # show communication with the server try: dhellmann_result = server.verify('dhellmann') notthere_result = server.verify('notthere') finally: server.quit() print 'dhellmann:', dhellmann_result print 'notther...
""" Settings for reputation changes that apply to user in response to various actions by the same users or others """ from askbot.conf.settings_wrapper import settings from askbot.deps.livesettings import ConfigurationGroup, IntegerValue from django.utils.translation import ugettext_lazy as _ from askbot.conf.super_gro...
from uber.common import * class HTTPRedirect(cherrypy.HTTPRedirect): def __init__(self, page, *args, **kwargs): args = [self.quote(s) for s in args] kwargs = {k:self.quote(v) for k,v in kwargs.items()} cherrypy.HTTPRedirect.__init__(self, page.format(*args, **kwargs)) if URL_BASE.sta...
from builtins import next from builtins import str from builtins import object from unittest import mock from bugwarrior.services import bts from .base import ServiceTest, AbstractServiceTest class FakeBTSBug(object): bug_num = 810629 package = "wnpp" subject = ("ITP: bugwarrior -- Pull tickets from github,...