code stringlengths 1 199k |
|---|
*,Letter,*,upper,1.25,H,*,
*,Letter,*,smallCaps,1.1,h.sc,*,
*,Letter,*,lower,1,x,*,
*,Letter,*,minor,0.7,m.sups,.sups,
*,Number,Decimal Digit,*,1.2,one,*,
*,Number,Decimal Digit,*,1.2,zero.osf,.osf,
*,Number,Fraction,minor,1.3,*,*,
*,Number,*,*,0.8,*,.dnom,
*,Number,*,*,0.8,*,.numr,
*,Number,*,*,0.8,*,.inferior,
*,Numb... |
"""
model_b.py
by Ted Morin
contains a function to predict 2-year Incident Hypertension risks using Weibull beta coefficients from:
10.7326/0003-4819-148-2-200801150-00005
2008 A Risk Score for Predicting Near-Term Incidence of Hypertension
Framingham Heart Study
translated and adapted from from FHS online risk calcula... |
"""Test class for InterSatellite Sync feature
:Requirement: Satellitesync
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: UI
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
from robottelo.decorators import (
run_only_on,
stubbed,
tier1,
tier3,
upgrade
)
from robottelo... |
import unittest
from svgwrite.mixins import Clipping
from svgwrite.base import BaseElement
class SVGMock(BaseElement, Clipping):
elementname = 'svg'
class TestClipping(unittest.TestCase):
def test_clip_rect_numbers(self):
obj = SVGMock(debug=True)
obj.clip_rect(1, 2, 3, 4)
self.assertEqu... |
from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QApplication, QPushButton, QLineEdit, QLabel, QMenuBar, QStatusBar, QMessageBox, QProgressDialog, QFileDialog
import display
import cursor
import listing
import excel
import delete
import manual
try:
_fromUtf8 = QtCore.Q... |
import random
import sys
import pygame
import classes.board
import classes.extras as ex
import classes.game_driver as gd
import classes.level_controller as lc
class Board(gd.BoardGame):
def __init__(self, mainloop, speaker, config, screen_w, screen_h):
self.level = lc.Level(self, mainloop, 10, 8)
gd... |
from Hypotheses import *
from ModelSelection import LinearRegression
from Test import *
sigma = 5 # observation noise sigma
from Test import generate_noise_and_fit
hc = HypothesisCollection()
hc.append(PolynomialHypothesis(M=2, variance=3, noiseVariance=sigma**2))
hc.append(PolynomialHypothesis(M=6, variance=3, noiseV... |
__author__ = 'adalekin'
import re
import requests
import hashlib
from PIL import Image, ImageOps
from cStringIO import StringIO
from xparse.parser import *
from xparse.utils import get_in_dict, set_in_dict
class URLExtractor(object):
def __init__(self, regex, parser_class):
self.regex = re.compile(regex)
... |
from django.db import models
class Music(models.Model):
url = models.CharField('URL', max_length=255)
title = models.CharField('título', max_length=200, blank=True)
artist = models.CharField('artista', max_length=200, blank=True)
genre = models.CharField('gênero', max_length=100, blank=True)
file = ... |
"""
Kaggle上的Quora question pairs比赛,按照Abhishek Thakur的思路,把整个流程跑通了
讲解的文章https://www.linkedin.com/pulse/duplicate-quora-question-abhishek-thakur。
里面有两个实现,基于传统机器学习模型的实现和基于深度学习的实现,这段脚本是后者。
基本的思路比较简单,不清楚的地方也添加了注释。使用GloVe的词向量库,把每个句子转换成词向量
拼接起来的矩阵,之后就可以搭建神经网络了。自己在Convolution1D、LSTM和DropOut那一块儿还
有些迷糊。
"""
import pandas as pd
im... |
from kytos import models
from kytos.db import Session
from flask import Flask, redirect
from flask import url_for
from flask.ext.restful import abort, Resource, fields, reqparse, marshal_with, Api
from sqlalchemy.orm import subqueryload, scoped_session
from sqlalchemy.orm import exc
db_session = scoped_session(Session)... |
from __future__ import unicode_literals
from datetime import timedelta
from flask import session
from indico.core import signals
from indico.core.db import db
from indico.core.db.sqlalchemy.util.session import no_autoflush
from indico.modules.events.contributions import logger
from indico.modules.events.contributions.m... |
import sys
from Cream import *
def main():
#
# Substitute with your hostname
#
creamURL = "https://cream-12.pd.infn.it:8443/ce-cream/services/CREAM2"
#
# Substitute with your real CREAM Job ID returned by the JobRegister operation
#
localCreamJID1 = ""
#
# If you have to query another job put its Cream Job... |
'''
This script will remove the directories if that contains only xml files.
'''
import os
srcpath = raw_input("Enter the source path : ")
for root, sub, files in os.walk(os.path.abspath(srcpath)):
if files:
files = [f for f in files if not f.endswith('.xml')]
if not files:
fpath = os.pa... |
"""This file invokes predictionmetricsmanager.py tests
TODO: Move these tests to unit test format.
"""
from nupic.frameworks.opf.predictionmetricsmanager import (
test as predictionMetricsManagerTest)
if __name__ == "__main__":
predictionMetricsManagerTest() |
import sys
import os
import glob
from os.path import join, getsize
import re
import json
def is_pkg(path_parts, files):
return "__init__.py" in files
def count_class_refs(class_name, all_files):
"""
Patterns:
=\s+<class_name>\s*\(
<class_name>\.
"""
refs = 0
pats = [
'=\s+%s\s*\(... |
"""
Spyder Editor
This is a temporary script file.
"""
from json import loads
from pprint import pprint
from sys import argv
import urllib
class FREEBASE_KEY():
'''
please input the api_key here
'''
api_key = 'AIzaSyBWsQpGo34Lk0Qa3wD0kjW5H1Nfb2m5eaM'
def get_city_id(city_name):
query = city_name
... |
import shelve
db = shelve.open('class-shelve')
for key in db:
print(key, '=>\n)', db[key].name, db[key].pay)
bob = db['bob']
print(bob.lastName())
print(db['tom'].lastName) |
'''
Author: Robin David
License: GNU GPLv3
Repo: https://github.com/RobinDavid
Copyright (c) 2012 Robin David
PyStack 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 v... |
__author__ = 'Evtushenko Georgy'
from ..nodes.neuron import SignNeuron
from ..nodes.network import Network
from ..groups.group import Group
import networkx as nx
import numpy as np
class HopfieldNetwork(Network):
def __init__(self, size):
self.create_graph(size, SignNeuron)
self.weights = np.random.... |
from setuptools import setup, find_packages
from helga_spook import __version__ as version
setup(name='helga-spook',
version=version,
description=('prints nsa buzzwords'),
classifiers=['Development Status :: 4 - Beta',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3... |
import sys
import os
import re
import string
from xml.dom import minidom
from volk_regexp import *
from make_cpuid_c import make_cpuid_c
from make_cpuid_h import make_cpuid_h
from make_set_simd import make_set_simd
from make_config_fixed import make_config_fixed
from make_typedefs import make_typedefs
from make_environ... |
"""Clears the Cache"""
from django.core.cache import cache
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""
Clears the Cache
"""
help = "Clears the Cache"
def handle(self, **options):
"""Clears the Cache"""
cache.clear()
self.stdout.writ... |
rules = [
{
"name": "always false",
"rule": lambda container: False
}
] |
"""
Created on Wed Dec 14 14:10:41 2016
@author: sigurdja
"""
from setuptools import setup, find_packages
setup(
name="psse_models",
version="0.1",
packages=find_packages(),
) |
"""
This file is part of GObjectCreator.
GObjectCreator 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.
GObjectCreator is distributed in the ... |
"""
---------------------------------------------------------------------------
OpenVolunteer
Copyright 2009, Ludovic Rivallain
---------------------------------------------------------------------------
This file is part of OpenVolunteer.
OpenVoluntee... |
"""displays the root page"""
from django import shortcuts
def index(request):
"""Display the site root page.
`request` is the request invoking this view.
"""
return shortcuts.render_to_response('index.html') |
import subprocess
import os
import dialog
class RDP():
def __init__(self):
self.d = dialog.Dialog(dialog="dialog")
self.storage_path = os.path.expanduser("~/LidskjalvData")
def show_rdp_menu(self, site, host):
# """ """
# FIXME
# print("FIXME: rdp_menu")
# sys.exi... |
import magic
from pytag.structures import PytagDict
from pytag.constants import FIELD_NAMES
from pytag.formats import OggVorbisReader, OggVorbis, Mp3Reader, Mp3
MIMETYPE = {'application/ogg': (OggVorbisReader, OggVorbis),
'audio/mpeg': (Mp3Reader, Mp3)
}
class Tag:
"""Descriptor class.
"... |
class GetText():
_file_path = None
_body_list = None
_target = None
def __init__(self, file_path):
#self._file_path = open(file_path, "r+").read().replace("<br","\n<br")
self._file_path = file_path.replace("<br />", "<br />\n")
#self._file_path = (self._file_path.replace("\n",";;... |
import random
import textwrap
def print_bold(msg):
#Funcion para mostrar por pantalla un string en negrita
print("\033[1m"+msg+"\033[0m")
def print_linea_punteada(width=72):
print('-'*width)
def ocupar_chozas():
ocupantes = ['enemigo','amigo','no ocupada']
chozas = []
while len(chozas) < 5: #Def... |
'''
Open Source Initiative OSI - The MIT License:Licensing
Tue, 2006-10-31 04:56 nelson
The MIT License
Copyright (c) 2009 BK Precision
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restr... |
SMILEYS_INDEX=(
"""
[default]
happy.png :) :-)
excited.png :-D :-d :D :d
sad.png :-( :(
wink.png ;-) ;)
tongue.png :P :p :-P :-p
shocked.png =-O =-o
kiss.png :-*
glasses-cool.png 8-)
embarrassed.png :... |
import env
import numpy as np
import metaomr
import metaomr.kanungo as kan
from metaomr.page import Page
import glob
import pandas as pd
import itertools
import os.path
import sys
from datetime import datetime
from random import random, randint
IDEAL = [path for path in sorted(glob.glob('testset/modern/*.png'))
... |
import json
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.conf import settings
from guardian.shortcuts import get_anonymous_user
from geonode.groups.models import GroupProfile, GroupIn... |
import sys, os
sys.path.insert(0, os.path.abspath(os.path.join('..', '..')))
import cherrymusicserver as cherry
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'CherryMusic'
copyright = '2013, Tom Wallroth, with Tilman Boer... |
import matplotlib
matplotlib.use('GTKAgg')
import matplotlib.pyplot as plt
ax=plt.gca()
ax.invert_xaxis()
ax.invert_yaxis()
for tick in ax.xaxis.get_major_ticks():
tick.label1On = False
tick.label2On = True
for tick in ax.yaxis.get_major_ticks():
tick.label1On = False
tick.label2On = Tru... |
from __future__ import print_function
import httplib2
import os
import io
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
from apiclient.http import MediaIoBaseDownload
from apiclient.http import MediaFileUpload
import sys
import argparse
from pyfcm imp... |
from math import *
inp = raw_input()
spl = inp.split()
n = int(spl[0])
m = int(spl[1])
a = int(spl[2])
i = int(ceil(n * 1.0 / a))
j = int(ceil(m * 1.0 / a))
print max(1, i * j) |
import warnings
warnings.filterwarnings( "ignore", message = "The sre module is deprecated, please import re." )
from simplejson import JSONEncoder
from datetime import datetime, date
class Json( JSONEncoder ):
def __init__( self, *args, **kwargs ):
JSONEncoder.__init__( self )
if args and kwargs:
raise... |
"""Plotting module for Sympy.
A plot is represented by the ``Plot`` class that contains a reference to the
backend and a list of the data series to be plotted. The data series are
instances of classes meant to simplify getting points and meshes from sympy
expressions. ``plot_backends`` is a dictionary with all the back... |
"""Test class for :class:`robottelo.cli.hostgroup.HostGroup` CLI.
@Requirement: Hostgroup
@CaseAutomation: Automated
@CaseLevel: Acceptance
@CaseComponent: CLI
@TestType: Functional
@CaseImportance: High
@Upstream: No
"""
from fauxfactory import gen_string
from robottelo.cli.base import CLIReturnCodeError
from robottel... |
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Board, BoardPermissions, User, UserSettings
@receiver(post_save, sender=Board)
def init_board_permissions(sender, **kwargs):
"""Link existing benchmark countries to newly created countries."""
instance = kwar... |
import numpy as np
from ase import Hartree
from gpaw.aseinterface import GPAW
from gpaw.lcao.overlap import NewTwoCenterIntegrals
from gpaw.utilities import unpack
from gpaw.utilities.tools import tri2full, lowdin
from gpaw.lcao.tools import basis_subset2, get_bfi2
from gpaw.coulomb import get_vxc as get_ks_xc
from gpa... |
__params__ = {'la': 32, 'lb': 32, 'da': 10}
def protocol(client, server, params):
la = params['la']
lb = params['lb']
da = params["da"]
server.a = UnsignedVec(bitlen=la, dim=da).input(src=driver, desc="a")
server.b = Unsigned(bitlen=lb).input(src=driver, desc="b")
client.a <<= server.a
clien... |
import unittest
import sys
import os
root_folder = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + os.sep + ".." + os.sep + "aikif" )
sys.path.append(root_folder)
import core_data as mod_core
def get_method():
"""
returns a description in RST for the research paper
"""
txt = 'Method 1 - Ont... |
"""Fonctionnal testing for "Python In HTML" (PIH) and "HTML In Python" (HIP).
"""
__author__ = "Didier Wenzek (didier.wenzek@free.fr)"
import sys
sys.path.append('..')
import unittest
import thread, time
from util import *
class TemplateTest(unittest.TestCase):
"""Testing the Karrigell Scripting languages.
A test is ... |
quantidade = int (input())
cidade = input()
qt_quartos = int (input())
if cidade.lower() == "pipa":
if qt_quartos == 2:
valor_total = (quantidade * 75)+ 600
valor_unitario = valor_total / quantidade
else:
valor_total = (quantidade * 75)+ 900
valor_unitario = valor_total / quantid... |
import sys, argparse, os, numpy as np
from horton import log, __version__
from horton.scripts.common import parse_h5, store_args, check_output, \
write_script_output
from horton.scripts.espfit import load_charges, load_cost
np.seterr(divide='raise', over='raise', invalid='raise')
def parse_args():
parser = argp... |
from django.db import models
from django.conf import settings
from django.utils import timezone
from django.core.validators import MinValueValidator
from django.urls import reverse
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from .Committee import Committee
from... |
clouthes = ["T-Shirt","Sweater"]
print("Hello, welcome to my shop\n")
while (True):
comment = input("Welcome to our shop, what do you want (C, R, U, D)? ")
if comment.upper()=="C":
new_item = input("Enter new item: ")
clouthes.append(new_item.capitalize())
elif comment.upper()=="R":
print(end='')
elif comment... |
import unittest
from card_validation import (
numberToMatrix,
getOddDigits,
getEvenDigits,
sumOfDoubleOddPlace,
sumOfEvenPlace,
getDigit,
isValid
)
class CardValidationTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(CardValidationTest, self).__init__(*args, **... |
import ogre.renderer.OGRE as ogre
import ogre.io.OIS as OIS
from vector import Vector3
import os
import time
class InputMgr(OIS.KeyListener, OIS.MouseListener, OIS.JoyStickListener):
''' Manages keyboard and mouse, with buffered and unbuffered input. '''
def __init__(self, engine):
''' Creates Input Lis... |
from odoo import fields, models
class Channel(models.Model):
_inherit = 'slide.channel'
nbr_certification = fields.Integer("Number of Certifications", compute='_compute_slides_statistics', store=True)
class Category(models.Model):
_inherit = 'slide.category'
nbr_certification = fields.Integer("Number of... |
from __future__ import (absolute_import, division, print_function)
from Muon.GUI.Common.muon_load_data import MuonLoadData
import Muon.GUI.Common.utilities.load_utils as load_utils
class LoadRunWidgetModel(object):
"""Stores info on all currently loaded workspaces"""
def __init__(self, loaded_data_store=MuonLoa... |
"""Tests for functions and classes in data/processing.py."""
import glob
import os
from absl.testing import absltest
import heatnet.data.processing as hdp
import heatnet.file_util as file_util
import heatnet.test.test_util as test_util
import numpy as np
import xarray as xr
class CDSPreprocessorTest(absltest.TestCase):... |
from molpher.algorithms.functions import find_path
from molpher.core import ExplorationTree as ETree
class BasicPathfinder:
"""
:param settings: settings to use in the search
:type settings: `Settings`
A very basic pathfinder class that can be used to run exploration with
any combination of operatio... |
import convis
import numpy as np
import matplotlib.pylab as plt
plt.figure()
plt.imshow(convis.numerical_filters.gauss_filter_2d(4.0,4.0))
plt.figure()
plt.plot(convis.numerical_filters.exponential_filter_1d(tau=0.01)) |
import threading
import socket
import tornado
import tornado.wsgi
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.websocket
from traits.api import Instance, Int, CStr, Dict, Str
from automate.common import threaded
from automate.service import AbstractUserService
class TornadoService(A... |
from collections import namedtuple
from model.flyweight import Flyweight
from model.static.database import database
class ControlTowerResource(Flyweight):
def __init__(self,control_tower_type_id):
#prevents reinitializing
if "_inited" in self.__dict__:
return
self._inited = None
... |
import os
import threading
import requests
import lxml
from threading import Thread
from bs4 import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
pic_path = 'pic/' # 保存文件路径
URL = 'http://www.nanrenwo.net/z/tupian/hashiqitupian/'
URL1 = 'http://www.nanrenwo.net/'
class Worker(threading.Thread):
... |
"""To install: sudo python setup.py install
"""
import os
from setuptools import setup, find_packages
def read(fname):
"""Utility function to read the README file."""
return open(os.path.join(os.path.dirname(__file__), fname)).read()
VERSION = __import__('lintswitch').__version__
setup(
name='lintswitch',
... |
import graph
import dot
from core import *
import dataflow
def make_inst(g, addr, dest, op, *args):
def make_arg(a):
if a is None:
return None
if isinstance(a, int):
return VALUE(a)
if isinstance(a, str):
return REG(a)
return a
b = BBlock(addr)... |
from base.iterativeRecommender import IterativeRecommender
import numpy as np
from util import config
from collections import defaultdict
from math import log,exp
from scipy.sparse import *
from scipy import *
class CoFactor(IterativeRecommender):
def __init__(self, conf, trainingSet=None, testSet=None, fold='[1]')... |
import logging
from s13.Day5.conf import setting
logger = logging.getLogger('ATM-TRANSACTION-LOG')
logger.setLevel(logging.INFO) #configure a global logging level
console_handler = logging.StreamHandler() #print the log on the console
file_handler = logging.FileHandler("{}/log/access.log".format(setting.APP_DIR))
forma... |
import numpy as np
from PyQt5.QtGui import QPainterPath, QPen
from PyQt5.QtWidgets import QGraphicsPathItem
from urh import settings
from urh.cythonext import path_creator
from urh.ui.painting.GridScene import GridScene
from urh.ui.painting.SceneManager import SceneManager
class FFTSceneManager(SceneManager):
def _... |
import multiprocessing
import billiard
multiprocessing.Process = billiard.Process # noqa
import os
import glob
from ansible.cli.playbook import PlaybookCLI
from ansible.executor.playbook_executor import PlaybookExecutor
from ansible.inventory import Inventory
from ansible.parsing.dataloader import DataLoader
from ansi... |
from .views import BaseView
from forums.extension import db
from forums.api.forums.models import Board
from forums.api.tag.models import Tags
class BoardView(BaseView):
form_excluded_columns = ('topics')
class TagView(BaseView):
column_searchable_list = ['name']
form_excluded_columns = ('topics', 'followers... |
"""
A U1DB backend for encrypting data before sending to server and decrypting
after receiving.
"""
import os
from twisted.web.client import Agent
from twisted.internet import reactor
from leap.common.http import getPolicyForHTTPS
from leap.soledad.common.log import getLogger
from leap.soledad.client.http_target.send i... |
(S'7f2210613c44962221805a1b28aa76d6'
p1
(ihappydoclib.parseinfo.moduleinfo
ModuleInfo
p2
(dp3
S'_namespaces'
p4
((dp5
S'TkDrawer'
p6
(ihappydoclib.parseinfo.classinfo
ClassInfo
p7
(dp8
g4
((dp9
(dp10
tp11
sS'_filename'
p12
S'../python/frowns/Depict/TkMoleculeDrawer.py'
p13
sS'_docstring'
p14
S''
sS'_class_member_info'
... |
"""
EasyBuild support for installing Cray toolchains, implemented as an easyblock
@author: Kenneth Hoste (Ghent University)
@author: Guilherme Peretti Pezzi (CSCS)
@author: Petar Forai (IMP/IMBA)
"""
from easybuild.easyblocks.generic.bundle import Bundle
from easybuild.tools.build_log import EasyBuildError
KNOWN_PRGENV... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import textwrap
import os
import random
import subprocess
import sys
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.utils.color import stringc
class Display:
def __init__(self, verbosity=... |
'''
read the input data, parse to int list;
create mappings of (user,item) -> review int list
@author: roseck
@date Mar 15, 2017
'''
from __builtin__ import dict
import gzip
class DataPairMgr():
def _int_list(self,int_str):
'''utility fn for converting an int string to a list of int
'''
retu... |
import os
DEBUG = True
TEMPLATE_DEBUG = True
SETTINGS_DIR = os.path.dirname(os.path.realpath(__file__))
BUILDOUT_DIR = os.path.abspath(os.path.join(SETTINGS_DIR, '..'))
DATABASES = {
# If you want to use another database, consider putting the database
# settings in localsettings.py. Otherwise, if you change the... |
import sys
import os
extensions = [
'sphinx.ext.todo',
]
source_suffix = '.txt'
master_doc = 'index'
project = u'domogik-plugin-daikcode'
copyright = u'2014, Nico0084'
version = '0.1'
release = version
pygments_style = 'sphinx'
html_theme = 'default'
html_static_path = ['_static']
htmlhelp_basename = project |
import os
import re
import select
import socket
import struct
import time
from module.plugins.internal.Hoster import Hoster
from module.plugins.internal.misc import exists, fsjoin
class XDCC(Hoster):
__name__ = "XDCC"
__type__ = "hoster"
__version__ = "0.42"
__status__ = "testing"
__pattern__... |
my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # Inches
my_weight = 180 # lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
print "Let's talk about %s." % my_name
print "He's %d inches tall." % my_height
print "He's %d pounds heavy." % my_weight
print "Actually that's not too heavy"
print "He's ... |
"""
Implementation of the trigsimp algorithm by Fu et al.
The idea behind the ``fu`` algorithm is to use a sequence of rules, applied
in what is heuristically known to be a smart order, to select a simpler
expression that is equivalent to the input.
There are transform rules in which a single rule is applied to the
exp... |
import logging
from unittest.mock import MagicMock, call
from ert_logging._log_util_abort import _log_util_abort
def test_log_util_abort(caplog, monkeypatch):
shutdown_mock = MagicMock()
monkeypatch.setattr(logging, "shutdown", shutdown_mock)
with caplog.at_level(logging.ERROR):
_log_util_abort("fna... |
"""Colour class.
This module contains a class implementing an RGB colour.
"""
__author__ = 'Florian Krause <florian@expyriment.org>, \
Oliver Lindemann <oliver@expyriment.org>'
__version__ = ''
__revision__ = ''
__date__ = ''
import colorsys
from . import round
_colours = {
'aliceblue': (240, 248, 25... |
"""Test class for Smart/Puppet Variables
:Requirement: Smart_Variables
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: API
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
import json
from random import choice, uniform
import yaml
from fauxfactory import gen_integer, gen_string
from nailg... |
import os
from setuptools import setup
from distutils.cmd import Command
import django_auth_iam
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
setup(
name='django-auth-iam',
version=django_auth_iam.__version__,
description='Django authentication backend using Ama... |
""" Package for tesseract cube controllers. """
from .sim import SimulatedController
from .gpio import GPIOController
from .c_gpio import CffiGpioController
CUBES = [
SimulatedController,
GPIOController,
CffiGpioController,
] |
from cmd import Cmd
import regionfixer_core.constants as c
from regionfixer_core import world
from regionfixer_core.scan import console_scan_world, console_scan_regionset
class InteractiveLoop(Cmd):
def __init__(self, world_list, regionset, options, backup_worlds):
Cmd.__init__(self)
self.world_list... |
from dotenv import load_dotenv
load_dotenv('./.env') |
"""
Django settings for todo project.
Generated by 'django-admin startproject' using Django 1.9.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
BASE_DIR ... |
'''
Study Common Emitter Characteristics of NPN transistors.
Saturation currents, and their dependence on base current
can be easily visualized.
'''
from __future__ import print_function
import time,sys,os
from SEEL_Apps.utilitiesClass import utilitiesClass
from .templates import ui_NFET as NFET
from PyQt4 import QtCor... |
from __future__ import with_statement
import datetime
import threading
import traceback
import sickbeard
from sickbeard import logger
from sickbeard import db
from sickbeard import common
from sickbeard import helpers
from sickbeard import exceptions
from sickbeard import network_timezones
from sickbeard.exceptions imp... |
import sys
class DualModulusPrescaler:
def __init__(self,p):
self.m_p = p
return
def set_prescaler(self):
return
# may be internal
def set_a(self,a):
self.m_a = a
return
# may be internal
def set_n(self,n):
self.m_n = n
return
def set_r... |
import logging
import os
from lib import exception
from lib import repository
from lib.constants import REPOSITORIES_DIR
LOG = logging.getLogger(__name__)
def get_versions_repository(config):
"""
Get the packages metadata Git repository, cloning it if does not
yet exist.
Args:
config (dict): con... |
import uuid
from flask import g
def get_source_ip(my_request):
try:
# First check for an X-Forwarded-For header provided by a proxy / router e.g. on Heroku
source_ip = my_request.headers['X-Forwarded-For']
except KeyError:
try:
# First check for an X-Forwarded-For header prov... |
import os, re, shutil
for (base, _, files) in os.walk("essays",):
for f in files:
if f.endswith(".markdown"):
fp = os.path.join(base, f)
_, np = os.path.split(base)
np = re.sub(r"_def$", "", np)
np = os.path.join("essays", np+".markdown")
# print f... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
import codecs
from ansible.errors import AnsibleParserError
from ansible.parsing.quoting import unquote
_HEXCHAR = '[a-fA-F0-9]'
_ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\U{0} # 8-digit hex escapes
| \\u{... |
import os
import re
import glob
import shlex
from collections import OrderedDict
from configparser import ConfigParser
class AsyncConfigError(Exception):
def __init__(self, msg=None):
super(AsyncConfigError, self).__init__(msg)
def parse_string(key, val, dic):
if val:
dic[key] = val.strip()
... |
import datetime
import lxml.html
import re
from weboob.tools.browser import BasePage
from weboob.tools.misc import to_unicode
from weboob.tools.parsers.lxmlparser import select, SelectElementException
from ..video import YoujizzVideo
__all__ = ['VideoPage']
class VideoPage(BasePage):
def get_video(self, video=None)... |
"""Tests for Oscapcontent
:Requirement: Oscapcontent
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: UI
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
import unittest2
from fauxfactory import gen_string
from nailgun import entities
from robottelo.config import settings
from robottelo.co... |
from gnuradio import gr, gr_unittest
import flysky_swig
class qa_dumpsync (gr_unittest.TestCase):
def setUp (self):
self.tb = gr.top_block ()
def tearDown (self):
self.tb = None
def test_001_t (self):
# set up fg
self.tb.run ()
# check data
if __name__ == '__main__':
... |
from typing import Iterable, Mapping, Optional
from lib import data
from ..channel import pyramid
from ..channel import wall
def filterMessage() -> Iterable[data.ChatCommand]:
return []
def commands() -> Mapping[str, Optional[data.ChatCommand]]:
if not hasattr(commands, 'commands'):
setattr(commands, '... |
import sqlite3
import sys
"""<Mindpass is a intelligent password manager written in Python3
that checks your mailbox for logins and passwords that you do not remember.>
Copyright (C) <2016> <Cantaluppi Thibaut, Garchery Martial, Domain Alexandre, Boulmane Yassine>
This program is free software: you can red... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.