prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
#
# ovirt-engine-setup -- ovirt engine setup
# Copyright (C) 2013 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... | 'engine=%s:%s'
) % (
self.environment[
osetupcons.RenameEnv.FQDN
| ],
self.environment[
oengcommcons.ConfigEnv.PUBLIC_HTTPS_PORT
],
)
content.append(line)
return content
def __init__(self, context):
super(Plugin, self).__init__(context=... |
#!/usr/bin/env python
#
# email.py
# TurboHvZ
#
# Copyright (C) 2008 Ross Light
#
# 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
# (at your opt... | ntly sends an email.
This will immediately return if mail has been turned off. The sender is
set to the value of the configuration value ``hvz.webmaster_email``.
:Returns: The newly created message
:ReturnType: turbomail.message.Message
"""
if not turbogears.config.get('mail.on', Fals... | copy()
variables.setdefault('message_format', 'email')
from_address = turbogears.config.get('hvz.webmaster_email')
new_message = GenshiMessage(from_address, recipient, subject,
template, variables, **kw)
turbomail.enqueue(new_message)
return new_message
def send_gene... |
import unittest
from unittest import mock
from betfairlightweight import APIClient
from betfairlightweight import resources
from betfairlightweight.endpoints.scores import Scores
from betfairlightweight.exceptions import APIError
from tests.tools import create_mock_json
class ScoresInit(unittest.TestCase):
def t... | onse)
@mock.patch("betfairlightweight.endpoints.scores.Score | s.request")
def test_list_scores(self, mock_response):
mock = create_mock_json("tests/resources/score.json")
mock_response.return_value = (mock.Mock(), mock.json(), 1.3)
mock_update_keys = mock.Mock()
response = self.scores.list_scores(mock_update_keys)
assert mock.json.call... |
c_uint32,
POINTER(c_uint32),
c_uint32)
vmb_feature_info_query = _vimba_lib.VmbFeatureInfoQuery
vmb_feature_info_query.restype = c_int32
vmb_feature_info_query.argtypes = (c_void_p,
c_char_p,
... | tureQueueFlush
vmb_capture_queue_flush.restype = c_int32
vmb_capture_queue_flush.argtypes = (c_void_p,)
vmb_interfaces_list = _vimba_lib.VmbInterfacesList
vmb_interfaces_list.restype = c_int32
vmb_interfaces_list.argtypes = (POINTER(VmbInterfaceInfo),
c_uint32,
... | POINTER(c_uint32),
c_uint32)
vmb_interface_open = _vimba_lib.VmbInterfaceOpen
vmb_interface_open.restype = c_int32
vmb_interface_open.argtypes = (c_char_p,
c_void_p)
vmb_interface_close = _vimba_lib.VmbInterfaceClose
vmb_interface_close.restype = c_... |
.contrib.auth.models import User
# app imports
from oweb.tests import OWebViewTests
from oweb.models.account import Account
from oweb.models.research import Research
from oweb.models.ship import Ship
from oweb.models.planet import Planet, Moon
from oweb.models.building import Building
from oweb.models.defense import De... | 'item_type': 'defense',
'item_id': d_pre.id,
'item_level': d_pre.count - 1 },
HTTP_REFERER=reverse('oweb:planet_defense',
args=[p.id]))
self.assertRedirects(r,
... | id]),
status_code=302,
target_status_code=200)
d_post = Defense.objects.get(pk=d_pre.pk)
self.assertEqual(d_pre.count - 1, d_post.count)
def test_moon_defense_update( |
"""Emoji config functions"""
import json
import os
import re
from logging import getLogger
from card_py_bot import BASEDIR
__log__ = getLogger(__name__)
# Path where the emoji_config.json will be stored
EMOJI_CONFIG_PATH = os.path.join(BASEDIR, "emoji_config.json")
# Dictionary that is keyed by the Discord short em... | ", ":6m:": "6",
":2rm:": "Two or Red",
":gwm:": "Green or White",
":wm:": "White",
":um:": "Blue",
":16m:": "16",
":urm:": "Blue or Red",
":ubm:": "Blue or Black",
":11m:": "11"
}
def get_emoji_config_string() -> str:
"""Return a string of all the mana ids (in order) for config set... | g
EMOJI_CONFIG_STRING = get_emoji_config_string()
def create_config_json() -> dict:
"""Create and save a blank default config json also return the dict that
created the json"""
emoji_config = dict()
for short_emoji_id in MANA_ID_DICT:
emoji_config[short_emoji_id] = {
"web_id": M... |
exceeded is: " + limit_reason]}
raise XeroRateLimitExceeded(response, payload)
elif response.status_code == 500:
raise XeroInternalError(response)
elif response.status_code == 501:
raise XeroNotImplemented(response)
elif response.st... | def save_or_put(self, data, method="post", headers=None, summarize_errors=True):
uri = "/".join([self | .base_url, self.name])
body = self._prepare_data_for_save(data)
params = self.extra_params.copy()
if not summarize_errors:
params["summarizeErrors"] = "false"
return uri, params, method, body, headers, False
def _save(self, data):
return self.save_or_put(data, me... |
def pbj_while(slices):
output = ''
while | (slices > 0):
slices = slices - 2
if | slices >= 2:
output += 'I am making a sandwich! I have bread for {0} more sandwiches.\n'.format(slices / 2)
elif slices < 2:
output += 'I am making a sandwich! But, this is my last sandwich.'
return output
print pbj_while(int(raw_input('How many slices of bread do you have? ')))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2007 Troy Melhase
# Distributed under the terms of the GNU General Public License v2
# Author: Troy Melhase <troy@gci.net>
import sys
from PyQt4.QtCore import QVariant
from PyQt4.QtGui import (QApplication, QFrame, QIcon,
QStandardIte... | ata(QVariant(tickerId), tickerIdRole)
class SessionTreeModel(QStandardItemModel):
def __init__(self, session, parent=None):
""" Construct | or.
@param session Session instance
@param parent ancestor object
"""
QStandardItemModel.__init__(self)
self.session = session
root = self.invisibleRootItem()
for key, values in session.items():
item = SessionTreeItem(key)
root.appendRow(i... |
"""
Tests of neo.io.igorproio
"""
import unittest
try:
import igor
HAVE_IGOR = True
except ImportError:
| HAVE_IGOR = False
from neo.io.igorproio import IgorIO
from neo.test.iotest.common_io_test import BaseTestIO
@unittest.skipUnless(HAVE_IGOR, "requires igor")
class TestIgorIO(BaseTestI | O, unittest.TestCase):
ioclass = IgorIO
entities_to_download = [
'igor'
]
entities_to_test = [
'igor/mac-version2.ibw',
'igor/win-version2.ibw'
]
if __name__ == "__main__":
unittest.main()
|
# "Copyright (c) 2000-2003 The Regents of the University of California.
# All rights reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose, without fee, and without written agreement
# is hereby granted, provided that the above copyright notice, the follow... | strg += "%s/%s" % (msgs.count(1),len(msgs))
sys.stdout.write(strg)
sys.stdout.flush()
| numPrintedChars = len(strg)-numPrintedChars
except Queue.Empty:
print ""
break
#now, pack the data so that it can be easily unpacked
for i in range(len(data)):
data[i] = pack('B',data[i])
return ''.join(data[... |
from webhelpers import *
from datetime import datetime
def time_ago( x ):
return date.d | istance_of_time_in_words( x, | datetime.utcnow() )
def iff( a, b, c ):
if a:
return b
else:
return c |
iano'),
(70, 'BA', 'BIH', 387, 'Bosnia y Herzegovina', 'Europa', '', 'BAM', 'Marco convertible de Bosnia-Herzegovina'),
(72, 'BW', 'BWA', 267, 'Botsuana', 'África', '', 'BWP', 'Pula de Botsuana'),
(74, 'BV', 'BVT', 0, 'Isla Bouvet', '', '', '', ''),
(76, 'BR', 'BRA', 55, 'Brasil', 'América', 'América del Sur', 'BRL', '... | 593, 'Ecuador', 'América', 'América del Sur', '', | ''),
(222, 'SV', 'SLV', 503, 'El Salvador', 'América', 'América Central', 'SVC', 'Colón salvadoreño'),
(226, 'GQ', 'GNQ', 240, 'Guinea Ecuatorial', 'África', '', '', ''),
(231, 'ET', 'ETH', 251, 'Etiopía', 'África', '', 'ETB', 'Birr etíope'),
(232, 'ER', 'ERI', 291, 'Eritrea', 'África', '', 'ERN', 'Nakfa eritreo'),
(2... |
"""Resolwe collection model."""
from django.contrib.postgres.fields import ArrayField
from django.contrib.postgres.indexes import GinIndex
from django.contrib.postgres.search import SearchVectorField
from django.db import models, transaction
from resolwe.permissions.models import PermissionObject, PermissionQuerySet
... | late for Postgres model for storing a collection. | """
class Meta(BaseModel.Meta):
"""BaseCollection Meta options."""
abstract = True
#: detailed description
description = models.TextField(blank=True)
settings = models.JSONField(default=dict)
#: collection descriptor schema
descriptor_schema = models.ForeignKey(
"flo... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2016 Alex Forencich
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 restriction, including without limitation the... | ument_id', 'WaveRunner 204MXi-A')
super(lecroy104MXiA, self).__init__(*args, **kwargs)
self._analog_channel_count = 4
self._digital_channel_count = 0
self._channel_count = self._analog_channel_count + self._digital | _channel_count
self._bandwidth = 1e9
self._init_channels()
|
rt *
from mmls import *
from mount import *
from mount_ewf import *
from get_ntuser_paths import *
from get_usrclass_paths import *
from get_system_paths import *
from done import *
from unix2dos import *
from check_for_folder import *
from mount_encase_v6_l01 import *
from calculate_md5 import *
import os
import code... | ip out single quotes from the quoted path
#no_quotes_path = Image_Path.replace("'","")
#print("THe no quotes path is: " + no_quotes_path)
#call mount_ewf function
Image_Path = mount_ewf(Image_Path, outfile,mount_point)
#call mmls function
partition_info_dict, temp_time = mmls(outfile, Image_Path)
p... | t")
#if filesize of mmls output is 0 then run parted
if(file_size == 0):
print("mmls output was empty, running parted")
outfile.write("mmls output was empty, running parted")
#call parted function
partition_info_dict, temp_time = parted(outfile, Image_Path)
else:
#read through the mmls output... |
1df367ecd4f68aab894e57b31", "repos@localhost:gentoo-kde-shard.git", pull=True),
"gnome" : GitTree("gentoo-gnome-shard", "ffabb752f8f4e23a865ffe9caf72f950695e2f26", "repos@localhost:ports/gentoo-gnome-shard.git", pull=True),
"x11" : GitTree("gentoo-x11-shard", "12c1bdf9a9bfd28f48d66bccb107c17b5f5af577", "repos@localho... | feaacde82cd21ddd5e207ad1f4 (Updated 25 Dec 2016)
funtoo_overlays = {
"funtoo_ | media" : GitTree("funtoo-media", "master", "repos@localhost:funtoo-media.git", pull=True),
"plex_overlay" : GitTree("funtoo-plex", "master", "https://github.com/Ghent/funtoo-plex.git", pull=True),
#"gnome_fixups" : GitTree("gnome-3.16-fixups", "master", "repos@localhost:ports/gnome-3.16-fixups.git", pull=True),
... |
#expone | nt
#find 2^n
n = input("Enter n: ")
print 2**n
| |
# -*- coding: utf-8 -*-
# The MIT License (MIT)
# Copyright (c) 2015 Percy Li
# See LICENSE for details.
import struct
import threading
import copy
class FrameBuffer(object):
def __init__(self,decoder = None):
self.data_buffer = bytes([])
self.decoder = decoder
def s... | = threading.RLock()
def set_decoder (self,decoder = None):
with self.internal_lock:
return FrameBuffer.set_decoder(self,decoder)
def pop_frame (self):
with self.internal_lock:
return FrameBuffer.pop_frame(self)
def push_frame (self,fra | me):
with self.internal_lock:
return FrameBuffer.push_frame(self,frame)
def append_buffer (self,buf):
with self.internal_lock:
return FrameBuffer.append_buffer(self,buf)
def pop_buffer (self):
with self.internal_lock:
... |
imp | ort re
def pythonize_camelcase_name(name):
"""
GetProperty -> get_property
"""
def repl(match):
return '_' + match.group(0).lower()
s = re.sub(r'([A-Z])', repl, name)
if s.startswith('_'):
| return s[1:]
else:
return s
|
'''
Given: A protein string PP of length at most 1000 aa.
Return: The | total weight of PP. Consult the monoisotopic mass table.
'''
def weight(protein):
# Build mass table from mass_table.txt
mass = {}
with open("mass_table.txt", "r") as m:
for line in m:
lst = line.split(" ")
mass[lst[0]] = float(lst[1].rstrip())
# Calculate the mass of protein
total = 0
f... | protein:
total += mass[aa]
return total
|
# coding: utf-8
# license: GPLv3
from enemies import *
from hero import *
def annoying_input_int(message =''):
answer = None
while answer == None:
try:
answer = int(input(message))
except ValueError:
print('Вы ввели недопустимые символы')
return answer
def game_tou... | ён удар... **')
if dragon.is_alive():
break
print('Дракон', dragon._color, 'повержен!\n')
if hero.is_alive():
print('Поздравляем! Вы победили!')
print('Ваш накопленный опыт:', hero._experience)
else:
print('К сожалению, Вы проиграли...')
def start_game():
... | ragon_number = 3
dragon_list = generate_dragon_list(dragon_number)
assert(len(dragon_list) == 3)
print('У Вас на пути', dragon_number, 'драконов!')
game_tournament(hero, dragon_list)
except EOFError:
print('Поток ввода закончился. Извините, принимать ответы более невозможно.... |
from django.core.urlresolvers import reverse
import django.http
import django.utils.simplejson as json
import functools
def make_url(request, reversible):
return request.build_absolute_uri(reverse(reversible))
def json_output(func):
@functools.wraps(func)
def wrapper(*args, | **kwargs):
output = func(*args, **kwargs)
| return django.http.HttpResponse(json.dumps(output),
content_type="application/json")
return wrapper
|
import time
from netCDF4 import Dataset
from oceansar.ocs_io import NETCDFHandler
class ProcFile(NETCDFHandler):
""" Processed raw data file generated by the OASIS Simulator
:param file_name: File name
:param mode: Access mode (w = write, r = read, r+ = read + append)
:param proc_dim: Pr... | 'rg_dim'))
slc_r.units = '[]'
slc_i.units = '[]'
inc_angle = self.__file__.createVariable('inc_angle', 'f8')
inc_angle.units | = '[deg]'
f0 = self.__file__.createVariable('f0', 'f8')
f0.units = '[Hz]'
ant_L = self.__file__.createVariable('ant_L', 'f8')
ant_L.units = '[m]'
prf = self.__file__.createVariable('prf', 'f8')
prf.units = '[Hz]'
v_ground = self.__file... |
"""Regularizations.
Each regularization method is implemented as a subclass of
:class:`Regularizer`,
where the constructor takes the hyperparameters, an | d the `__call__` method
constructs the symbolic loss expression given a parameter.
These are made for use with :meth:`Model.regularize`, but can also be used
directly in the :meth:`loss` method of :class:`.Model` subclasses.
"""
import theano
import theano.tensor as T
from theano.ifelse import ifelse
class Regulariz... | T.sqrt(T.sqr(p).sum()) * T.as_tensor_variable(self.penalty)
class StateNorm(Regularizer):
"""Squared norm difference between recurrent states.
Note that this method seems to be unstable if the initial hidden state is
initialized to zero.
David Krueger & Roland Memisevic (2016).
`Regularizing RNN... |
# Print the version splitted in three components
import | sys
verfile = sys.argv[1]
f = open(verfile)
version = f.read()
l = [a[0] for a in version.split('.') if a[0] in '0123456789']
# If no revision, '0' is added
if len(l) == 2:
l.appe | nd('0')
for i in l:
print i,
f.close()
|
ed with this software.
#-----------------------------------------------------------------------------
'''
'''
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
from __future__ import absolute_impo... | other projects to instruct Bokeh how to display
content in other notebooks.
This function is primarily of use to developers wishing to integrate Bokeh
| with new notebook types.
Args:
notebook_type (str) :
A name for the notebook type, e.e. ``'Jupyter'`` or ``'Zeppelin'``
If the name has previously been installed, a ``RuntimeError`` will
be raised, unless ``overwrite=True``
load (callable) :
A fu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
''' Lyndor runs from here - contains the main functions '''
import sys, time, os
import module.message as message
import module.save as save
import module.cookies as cookies
import module.read as read
import install
import module.move as move
import module.draw as draw
im... | '''
# Check for a valid url
if url.find('.html') == -1:
sys.exit(message.animate_characters(Fore.LIGHTRED_EX, draw.ANONYMOUS, 0.02))
url = url[:url.find(".html")+5 | ] #strip any extra text after .html in the url
# Folder/File paths
lynda_folder_path = read.location + '/'
course_folder_path = save.course_path(url, lynda_folder_path)
desktop_folder_path = install.get_path("Desktop")
download_folder_path = install.get_path("Downloads")
# Read preferences... |
{
'name': "Sale only available products on Website",
'summary': """Sale only available products on Website""",
'version': '1.0.0',
'author': 'IT-Projects LLC, Ivan Yelizariev',
'license': 'GPL-3',
'category': 'Custom',
'website': 'https://yelizariev.github.io',
'images': ['images/availab... | .00,
'currency': 'EUR',
'depends': ['website_sale'],
' | data': [
'website_sale_available_views.xml',
],
'installable': True,
}
|
""" JobRunningWaitingRatioPolicy
Policy that calculates the efficiency following the formula:
( running ) / ( running + waiting + staging )
if the denominator is smaller than 10, it does not take any decision.
"""
from DIRAC import S_OK
from DIRAC.ResourceStat... | :
result[ 'Status' ] = 'Error'
result[ 'Reason' ] = commandResult[ 'Message' ]
return S_OK( result )
commandResult = commandResult[ 'Value' ]
if not commandResult:
result[ 'Status' ] | = 'Unknown'
result[ 'Reason' ] = 'No values to take a decision'
return S_OK( result )
commandResult = commandResult[ 0 ]
if not commandResult:
result[ 'Status' ] = 'Unknown'
result[ 'Reason' ] = 'No values to take a decision'
return S_OK( result )
running = float( commandRes... |
complexe = importeur.salle.creer_etendue("complexe")
complexe.origine = (20, 20)
obstacle = importeur.salle.obstacles["falaise" | ]
coords = [
(20, 20),
(21, 20),
(22, 20),
(23, 20) | ,
(24, 20),
(25, 20),
(20, 21),
(20, 22),
(20, 23),
(20, 24),
(20, 25),
(19, 25),
(19, 26),
(18, 26),
(17, 26),
(19, 27),
(17, 27),
(17, 28),
(18, 28),
(19, 28),
(20, 28),
(21, 28),
(22, 28),
(23, 28),
(24, 28),
(24, 27),
(24, 2... |
# Copyright (c) 2012 - 2015 Lars | Hupfeldt Nielsen, Hupfeldt IT
| # All rights reserved. This work is under a BSD license, see LICENSE.TXT.
from framework import api_select
def create_jobs(api_type):
api = api_select.api(__file__, api_type)
api.flow_job()
api.job('passwd_args', exec_time=0.5, max_fails=0, expect_invocations=1, expect_order=1,
params=(('s1',... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### P | LEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Installation()
result.template = "object/installation/faction_perk/turret/shared_block_sm.iff"
result.attribute_template_id = -1
result.stfName("turret_n","block_small")
## | ## BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
# -*- coding: utf-8 -*-
try:
f1 = open("input.txt","r",encoding="utf-8")
except IOError:
print("Не удалось найти входной файл input.txt")
try:
f2 = open("out | put.txt","w",encoding="utf-8")
except IOError:
print("Не удалось открыть выходной файл output.txt")
import re # импортируем модуль работы с регулярными выражениями
# --- регулярное выражение для заголовков вида: == ййй ==
zagolovok_level2 = re.compile("==.*==") # жадный квантификатор .*
# --- регулярные в... | ый кватнификатор .*?
ssylka_inner_id = re.compile("\[\[id.*?\|.*?\]\]") # id
ssylka_inner_club = re.compile("\[\[club.*?\|.*?\]\]") # club
ssylka_inner_public = re.compile("\[\[public.*?\|.*?\]\]") # public
# --- регулярное выражение для внешних ссылок вида [http**|**]
ssylka_outer = re.compile("\[h... |
yld = 0
num = 1
ship = Ship.objects.get(id=1)
harvester = Harvester.objects.get(id=1)
cycle_bonus = skill * Decimal(0.05)
yld = harvester.yld
c = harvester.cycle * (1 - cycle_bonus)
y = yld * (1 + ship.yld_bonus) * num
#parse Dscan
sites = []
proc_sites = []... |
g = Gas.objects.get(item_id=type_id)
g.last_price = avg_price
g.save()
gas | es = Gas.objects.all()
a, c = APICheck.objects.get_or_create(id=1)
a.save()
context = {'status': status, 'gases': gases}
return render(request, "home/pull_prices.html", context)
@staff_member_required
def wipe_db(request):
s = Site.objects.all()
s.delete()
g = Gas.objects.all()
g.delete... |
from quanthistling.tests import *
class TestBookController(TestController):
def test_index(self):
response = self.app.get(url(contro | ller='book', action='index'))
| # Test response...
|
lass implements the mixed case
where the bra does not equal the ket.
@author: R. Bourquin
@copyright: Copyright (C) 2014, 2016 R. Bourquin
@license: Modified BSD License
"""
from functools import partial
from numpy import squeeze, sum
from WaveBlocksND.Observables import Observables
__all__ = ["ObservablesMixedHAWP... | """
return self._innerproduct.quadrature(pacbra, packet, diag_component=component, diagonal=True, summed=summed)
def norm(self, wavepacket, *, component=None, summed=False):
r"""Calculate the :math:`L^2` norm :math:`\langle \Psi | \Psi | \rangle` of the wavepacket :math:`\Psi`.
:param wavepacket: The wavepacket :math:`\Psi` of which we compute the norm.
:type wavepacket: A :py:class:`HagedornWavepacketBase` subclass instance.
:param component: The index :math:`i` of the component :math:`\Phi_i` whose norm is computed.
... |
he terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABI... | property in self.properties:
source += property.generate_typemap()
source += ' { "", "", 0 },\n' # null terminated
| source += '};\n\n'
source += self._define_WmiInfo_struct()
source += "\n\n"
return source
def generate_classes_typedef(self):
"""Returns C string for typedefs"""
typedef = "typedef struct _%s %s;\n" % (self.name, self.name)
typedef += "typedef struct _%s_Data %s_... |
#!/usr/bin/python
from PyQt4 import QtCore, QtGui
class Bubble(QtGui.QLabel):
def __init__(self,text):
super(Bubble, | self).__init__(text)
self.setContentsMargins(5,5,5,5)
def paintEvent(self, e):
p = QtGui.QPainter(self)
| p.setRenderHint(QtGui.QPainter.Antialiasing,True)
p.drawRoundedRect(0,0,self.width()-1,self.height()-1,5,5)
super(Bubble,self).paintEvent(e)
class MyWidget(QtGui.QWidget):
def __init__(self,text,left=True):
super(MyWidget,self).__init__()
hbox = QtGui.QHBoxLayout()
... |
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | RANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ter | ms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
############################... |
import logging
import sys
import traceback
from django.conf import settings
from django.core.cache import cache
try:
from django.utils.module_loading import import_string
except ImportError:
# compatibility with django < 1.7
from django.utils.module_loading import import_by_path
import_string = import... | _name__)
def clean(self):
# There's nothing to clean, since the name is `self.__class__.__name__`.
pass
def save(self, *args, **kwargs):
raise NotImplementedError()
def natural_key(self):
return str(self.__class__.__name__)
def is_anonymous(self):
return False... | return True
def set_password(self, password):
raise NotImplementedError()
def check_password(self, password):
raise NotImplementedError()
def set_unusable_password(self):
pass
def has_usable_password(self):
return False
def get_session_auth_hash(self):
... |
# -*- coding: UTF-8 -*-
# translation.py
#
# Copyright (C) 2013 Cleany
#
# Author(s): Cédric Gaspoz <cga@cleany.ch>
#
# This file is part of cleany.
#
# Cleany 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, e... | 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. See the
# GNU General Public License | for more details.
#
# You should have received a copy of the GNU General Public License
# along with Cleany. If not, see <http://www.gnu.org/licenses/>.
# Stdlib imports
# Core Django imports
# Third-party app imports
from modeltranslation.translator import translator, TranslationOptions
# Cleany imports
#from .... |
"""
Misago-native rehash of Django's createsuperuser command that
works with double authentication fields on user model
"""
import sys
from getpass import getpass
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand
from d... | :
self.stderr.write(e.messages[0])
email = None
if password is not None:
try:
password = password.strip()
validate_password(password)
except ValidationError as e:
self.stderr.write(e.messages[0])
... | ager's create_superuser using our wrapper
self.create_superuser(username, email, password, verbosity)
else:
try:
if hasattr(self.stdin, 'isatty') and not self.stdin.isatty():
raise NotRunningInTTYException("Not running in a TTY")
#... |
, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is furnished
#to do so, subject to the following conditions:
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
#INCLUDING BUT NOT LIMITED TO THE W... | on: x=None
if x== None or x == 0:
floats=[]
for i in betaValues:
if i=='': pass
elif float(i)==0: pass
else: floats.append(float(i))
try: return min(floats)
except Exception: print betaValues;sys.exit | ()
else:
return x
def betaHighCount(x,betaHigh):
if x>betaHigh:
return 1
else: return 0
def betaLowCount(x,betaLow):
if x<betaLow:
return 1
else: return 0
def getIDsFromFile(filename):
filterIDs = {}
fn = filepath(filename)
for line in open... |
#!/usr/bin/env python2.7
# encoding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Vers... | csv
import unittest
import tika.parser
class CreateTest(unittest.TestCase):
"test for file types"
def __init__(self, methodName='runTest', param1=None, param2=None):
super(CreateTest, self).__init__(methodName)
self.param1 = param1
@staticmethod
def parameterize(test_case, param1=Non... | uite = unittest.TestSuite()
for name in testnames:
suite.addTest(test_case(name, param1=param1, param2=param2))
return suite
class RemoteTest(CreateTest):
def setUp(self):
self.param1 = tika.parser.from_file(self.param1)
def test_true(self):
self.assertTrue(self.para... |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | paddle.static.Program()):
x_np = np.full([10, 10], -1.)
x = paddle.static.data(name="X", shape=[10, 10], dtype='float64')
x.exponential_(1.0)
exe = paddle.static.E | xecutor()
out = exe.run(paddle.static.default_main_program(),
feed={"X": x_np},
fetch_list=[x])
self.assertTrue(np.min(out) >= 0)
def test_dygraph(self):
paddle.disable_static()
x = paddle.full([10, 10], -1., dtype='float32... |
from OpenGL import GL
import numpy as np
import math
def drawLine(start, end, color, width=1):
GL.glLineWidth(width)
GL.glColor3f(*color)
GL.glBegin(GL.GL_LINES)
GL.glVertex3f(*start)
GL.glVertex3f(*end)
GL.glEnd()
def drawCircle(center, radius, color, rotation=np.array([0,0,0]), axis=np.arra... | Rotatef(rotation[0]*90,axis[0],0,0)
GL.glRotatef(rotation[1]*90,0,axis[1],0)
GL.glRotatef(rotation[2]*90,0,0,axis[2])
else:
GL.glRotatef(rotation*90,axis[0],axis[1],axis[2])
GL.glBegin(GL.GL_POLYGON)
steps = [i * ((math.pi*2)/sections) | for i in range(sections)]
for i in steps:
GL.glVertex3f(math.cos(i)*radius, math.sin(i)*radius, 0,0)
GL.glEnd()
GL.glPopMatrix()
def makeDrawFunction(drawFunction, *args):
def closure():
drawFunction(*args)
return closure |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import numpy as np
import argparse
from google.protobuf import text_format
#https://github.com/BVLC/caffe/issues/861#issuecomment-70124809
import matplotlib
matplotlib.use('Agg')
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.p... | del = os.path.join(g_image_embedding_testing_folder, 'snapshots%s_iter_%d.caffemodel'%(g_shapenet_synset_set_handle, args.iter_num))
image_embedding_prototxt = g_image_embedding_testing_prototxt
if args.caffemodel:
image_embedding_caffemodel = args.caffemodel
if args.prototxt:
image_embedding_prototxt = args.p... | prototxt=image_embedding_prototxt,
caffemodel=image_embedding_caffemodel,
feat_name='image_embedding',
caffe_path=g_caffe_install_path,
mean_file=g_mean_file)[0]
print image_embedding_array.tolist()
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2018-10-26 01:35
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('pttrack', '0006_referral_additional_fiel... | se_name=b'Appointment scheduled?')),
| ('pt_showed', models.CharField(blank=True, choices=[(b'Y', b'Yes'), (b'N', b'No')], help_text=b'Did the patient show up to the appointment?', max_length=1, null=True, verbose_name=b'Appointment attended?')),
('appointment_location', models.ManyToManyField(blank=True, help_text=b'Where did the patient ... |
import os
from .base import * # NOQA
import dj_database_url
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
)
DATABASES = {'default': dj_database_url.config()}
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.R... | ct.com/en/1.3/ref/settings/#email-port
EMAIL_PORT = os.environ.get('MAILGUN_SMTP_PORT', None )
# See: https://docs.djangoproject.com/en/1.3/ref/settings/#email-subject-prefix
EMAIL_SUBJECT_PREFIX = '[Scorinator] '
# See: https://docs.djangoproject.com/en/1.3/ref/settings/#email-us | e-tls
EMAIL_USE_TLS = True
# See: https://docs.djangoproject.com/en/1.3/ref/settings/#server-email
SERVER_EMAIL = EMAIL_HOST_USER
########## END EMAIL CONFIGURATION |
89dbbc)
ss[7], ss[3] = RND(ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],4,0x3956c25bf348b538)
ss[6], ss[2] = RND(ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],5,0x59f111f1b605d019)
ss[5], ss[1] = RND(ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],6,0x923f82a4af194f9b)
ss[4], ss[0] = RND(ss[1],ss[2... | 4],ss[5],ss[6],ss[7],48,0x19a4c116b8d2d0c8)
ss[2], ss[6] = RND(ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],49,0x1e376c085141ab53)
ss[1], ss[5] = RND(ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],50,0x2748774cdf8eeb99)
ss[0], ss[4] = RND(ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],ss[3],ss[4],51,0x34b0bcb5e19b... | ,ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],ss[2],53,0x4ed8aa4ae3418acb)
ss[5], ss[1] = RND(ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],ss[1],54,0x5b9cca4f7763e373)
ss[4], ss[0] = RND(ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],ss[7],ss[0],55,0x682e6ff3d6b2b8a3)
ss[3], ss[7] = RND(ss[0],ss[1],ss[2],ss[3],ss[4],ss[5],ss[6],s... |
d in delimiters)
if allow_no_value:
self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d),
re.VERBOSE)
else:
self._optcre = re.compile(self._OPT_TMPL.format(delim=d),
re.VERB... | return fallback
def getfloat(self, section, option, *, raw=False, vars=None,
fallback=_U | NSET):
try:
return self._get(section, float, option, raw=raw, vars=vars)
except (NoSectionError, NoOptionError):
if fallback is _UNSET:
raise
else:
return fallback
def getboolean(self, section, option, *, raw=False, vars=None,
... |
"""
pystrix.ami.dahdi
=================
Provides classes meant to be fed to a `Manager` instance's `send_action()` function.
Specifically, this module provides implementations for features specific to the DAHDI technology.
Legal
-----
This file is part of pystrix.
pystrix is free software; you can redistribute it ... | Dials a number on an off-hook DAHDI channel.
"""
def __init__(self, dahdi_channel, number):
"""
`dahdi_channel` is the channel to use and `number` is the number to dial.
"""
_Request.__init__(self, 'DAHDIDialOffhook')
self['DAHDIChannel'] = dahdi_channel
self[... | l.
"""
def __init__(self, dahdi_channel):
"""
`dahdi_channel` is the channel to hang up.
"""
_Request.__init__(self, 'DAHDIHangup')
self['DAHDIChannel'] = dahdi_channel
class DAHDIRestart(_Request):
"""
Fully restarts all DAHDI channels.
"""
def __init__(... |
import RPi.GPIO as GPIO
import time
from array import *
#configuracoin de pines del stepper bipolar
out1 = 11
out2 = 13
out3 = 15
out4 = 16
#delay value
timeValue = 0.005
#matriz de pines del stepper
outs = [out1,out2,out3,out4]
#secuencia para mover el stepper
matriz = [
[1,0,0,1],
[1,1,0,0],
[0,1,1,0... | ef wakeupMotor():
for o in outs:
GPIO.output(o,GPIO.HIGH)
def sleepMotor():
for o in outs:
GPIO.output(o,GPIO.LOW)
def setMatrizPins(pin,valor):
if (valor == 0):
GPIO.output(outs[pin],GPIO.LOW)
if (valor == 1):
GPIO.output(outs[pin],GPIO.HIGH)
def runForward():
| i = 0
while (i < 4):
#print(matriz[i][0],matriz[i][1],matriz[i][2],matriz[i][3])
setMatrizPins(0,matriz[i][0])
setMatrizPins(1,matriz[i][1])
setMatrizPins(2,matriz[i][2])
setMatrizPins(3,matriz[i][3])
i = i + 1
time.sleep(timeValue)
def ru... |
self.O
filename = os.path.join('/tmp', e.name)
e.F1.dump(filename)
e.update_xml_attribute('Lectura')
e.reload(update=True)
return e
register(SmallDiffError)
class UnionFenosa0measError(ImpError):
description = 'Union Fenosa NULL measurement'
priority = 2
exit = Tr... | ('name', 'in', [DesdeFechaHora, HastaFechaHora]),
('lectura', '=', e.error.valor_db + consumption )]
lect_pool_ids = O.GiscedataLecturesLecturaPool.search(fields_to_search)
if not len(lect_pool_ids) > 0:
... | lect_pool.update_observacions('R. 0 Estimada a partir de consum F1 (ABr)')
return
raise Exception('{exception_tag}: Scenario not found'.format(**locals()))
register(UnionFenosa0measError)
class StartOfContractError(ImpError):
description = 'WARNING: ** Contract- First Measure... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Andreas Büsching <crunchy@bitkipper.net>
#
# a generic dispatcher implementation
#
# Copyright (C) 2006, 2007, 2009, 2010
# Andreas Büsching <crunchy@bitkipper.net>
#
# This library is free software; you can redistribute it and/or modify
# it under the terms of... | dispatchers[ | True]:
return MIN_TIMER
else:
return None
def dispatcher_remove(method):
"""Removes an external dispatcher function from the list"""
global __dispatchers, MIN_TIMER
for val in (True, False):
if method in __dispatchers[val]:
__dispatchers[val].remove(method)
break
if __dispatchers[True]:
return MIN_... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-01-20 19:10
from __future__ import unicode_literals
from django.db import migrations, mod | els
class Migration(migrations.Migration):
dependencies = [
| ('subjects', '0012_auto_20170112_1408'),
]
operations = [
migrations.AlterField(
model_name='subject',
name='tags',
field=models.ManyToManyField(blank=True, null=True, to='subjects.Tag', verbose_name='tags'),
),
]
|
# -*- encoding: utf-8 -*-
"""Test class for Template CLI
:Requirement: Template
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: CLI
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
from fauxfactory import gen_string
from robottelo.cli.base import CLIReturnCodeError
from robottelo.... | k if operating system can be removed from a template
:id: b5362565-6dce-4770-81e1-4fe3ec6f6cee
:expectedresults: Ope | rating system is removed from template
:CaseLevel: Integration
"""
template = make_template()
new_os = make_os()
Template.add_operatingsystem({
'id': template['id'],
'operatingsystem-id': new_os['id'],
})
template = Template.info({'id': te... |
# -*- coding: utf-8 -*-
#+---------------------------------------------------------------------------+
#| 01001110 01100101 01110100 01111010 01101111 01100010 |
#| |
#| Netzob : Inferring communication protocol... | Check if a variable is in the temporary memory.
@param variable: the given variable we search in memory.
@return: True if the variable has been found in the memory.
"""
return variable.getID() in self.temporaryMemory.keys()
def res | tore(self, variable):
"""restore:
Copy back the value of a variable from the real memory in the temporary memory.
@param variable: the given variable, the value of which we want to restore.
"""
if variable.getID() in self.memory.keys():
self.temporary... |
eckFolder():
"""Used to create the data folder at first startup"""
if not os.path.exists(SAVE_FOLDER):
print("Creating " + SAVE_FOLDER + " folder...")
os.makedirs(SAVE_FOLDER)
def checkFiles():
"""Used to initialize an empty database at first startup"""
theFile = SAVE_FOLDER +... | tings[serverId][self.keyLeaveLogEnabled]:
channel = self.bot.get_channel(self.settings[serverId][self.keyLeaveLogChannel])
await self.bot. | send_message(channel,
":x: ``Server Leave :`` User {0.name}#"
"{0.discriminator} ({0.id}) has left the "
"server.".format(leaveUser))
LOGGER.info("User %s#%s (%s) has left the server.... |
ous
view_only_link.anonymous = True
view_only_link.save()
res = app.get(view_only_link_url)
assert 'contributors' not in res.json['data'][0]['relationships']
assert 'implicit_contributors' not in res.json['data'][0]['relationships']
assert 'bibliographic_contributors' not... | ]
assert res.json['data']['attributes']['category'] == child['data']['attributes']['category']
project.reload()
assert res.json['data']['id'] == project.nodes[0]._id
assert project.nodes[0].logs.latest().action == NodeLog.PROJECT_CREATED
def test_creates_child_creates_child_and_san... | <strong>Project</strong>'
description = 'An <script>alert("even reasonabler")</script> child'
res = app.post_json_api(url, {
'data': {
'type': 'nodes',
'attributes': {
'title': title,
'description': description,
... |
WrtParentInterval.wrtParentIntervalNum)
WrtParentInterval.wrtParentIntervalNum += 1
# Create function interval
FunctionInterval.__init__(self, wrtReparentFunc, name = name)
### Function Interval subclasses for instantaneous pose changes ###
class PosInterval(FunctionInterv... | ath, hpr=hpr, scale=scale,
| other = other):
if other:
np.setHprScale(other, hpr, scale)
else:
np.setHprScale(hpr, scale)
# Determine name
if (name == None):
name = ('HprScale-%d' %
HprScaleInterval.hprScaleIntervalNum)
Hpr... |
from kivy.config import | Config
from kivy.config import ConfigParser
import pentai.base.logger as log
|
import os
def config_instance():
return _config
def create_config_instance(ini_file, user_path):
global _config
ini_path = os.path.join(user_path, ini_file)
if not ini_file in os.listdir(user_path):
log.info("Writing initial ini file %s" % ini_path)
import shutil
shutil.copy(... |
#!/usr/bin/env python3
#
# Copyright (C) 2013 - Tony Chyi <tonychee1989@gmail.com>
#
# 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, or (at your option)
# any later version.
#
... | loor, Boston, MA 02110-1301 USA.
from PyQt5 import QtWidgets, QtCore, QtGui
import json
import urllib.request
import sys
class Timer(QtCore.QThread):
"""Run QTimer in another thread."""
trigger = QtCore.pyqtSignal(int, dict)
def __init__(self, parent=None):
QtCore.QThread.__init__(self, pare | nt)
self.interval = 0
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.tc)
def setup(self, thread_no=1, interval=0):
self.thread_no = thread_no
self.interval = interval
def run(self):
self.timer.start(self.interval)
@QtCore.pyqtSlot()
def... |
from json import dumps # pragma: no cover
from sqlalchemy.orm import class_mapper # pragma: no cover
from app.models import User, Group # pragma: no cover
def serialize(obj, columns):
# then we return their values in a dict
return dict((c, getattr(obj, c)) for c in columns)
def queryAllToJson(model,conditions):
# ... |
columns = [c.key for c in class_mapper(model).columns]
serialized_objs = [
serialize(obj,columns)
for obj in model.query.filter_by(**conditions)
]
return dumps(serialized_objs)
def objectToJson(obj):
columns = [c.key for c in class_mapper(obj.__class__).columns]
serialized_obj = serialize(obj, columns)
ret... | name):
user = User.query.filter_by(username=username).first()
if user is None:
raise Exception('username %s not found in database' % username)
else:
return user.id
def getGroupId(groupname):
group = Group.query.filter_by(groupname=groupname).first()
if group is None:
raise Exception('groupname %s not found ... |
class ocho:
def __init__(self):
| self.cadena=''
def getString(self):
self.cadena = raw_input("Your desires are orders to | me: ")
def printString(self):
print "Here's your sentence: {cadena}".format(cadena=self.cadena)
oct = ocho()
oct.getString()
oct.printString()
|
from django.urls import reverse
from oppia.test import OppiaTestCase
cla | ss CompletionRatesViewTest(OppiaTestCase):
fixtures = ['tests/test_user.json',
'tests/test_oppia.json',
'tests/test_quiz.json',
'tests/test_permissions.json',
'tests/test_cohort.json',
'tests/test_course_permissions.json',
... | ts/test_usercoursesummary.json']
def setUp(self):
super(CompletionRatesViewTest, self).setUp()
self.allowed_users = [self.admin_user, self.staff_user]
self.disallowed_users = [self.teacher_user, self.normal_user]
def test_view_completion_rates(self):
template = 'reports/complet... |
import logging
log = logging.ge | tLogger(__name__)
try:
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.normalization import BatchNormalization
from keras.layers.advanced_activations import PReLU, LeakyReLU
from keras.optimizers import Adagrad, Adadelta, RMSprop, Adam
... | keras.utils import to_categorical
import_keras = True
except:
import_keras = False
log.info('could not import keras. Neural networks will not be used')
def keras_create_model(params, problem_type):
# creates a neural net model with params definition
log.info('creating NN structure')
model = ... |
# Copyright 2014 Netflix, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | ts:
if rrse | t.name == fqdn + '.':
app.logger.debug('found fqdn to delete: {}'.format(rrset))
for rr in rrset.resource_records:
changes = boto.route53.record.ResourceRecordSets(self.conn, zone_id)
changes.add_change("DELETE", fqdn, type, ttl).a... |
from __future__ import absolute_import, unicode_literals
import json
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailadmin.widgets import AdminChooser
class AdminSnippetChooser(AdminChooser):
target_content_type = None
def __i... | turn "createSnippetChooser({id}, {content_type | });".format(
id=json.dumps(id_),
content_type=json.dumps('{app}/{model}'.format(
app=content_type.app_label,
model=content_type.model)))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#--------------------------------------------------------------------------------------------------
# Program Name: holy_orders
# Program Description: Update program for the Abbot Cantus API server.
#
# Filename: holy_orders/current.py
# Purpose:... | our option) any later version.
#
# 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. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of... | ---------------------------------------------------
'''
Functions to determine which resources to update.
'''
import datetime
import logging
import tornado.log
import iso8601
# settings
LOG_LEVEL = logging.DEBUG
# script-level "globals"
_log = tornado.log.app_log
def _now_wrapper():
'''
A wrapper functio... |
extended by any subscription manager test case to make
sure nothing on the actual system is read/touched, and appropriate
mocks/stubs are in place.
"""
def setUp(self):
# No matter what, stop all patching (even if we have a failure in setUp itself)
self.addCleanup(patch.stopall)
... | mined.
"""
invalid_identity = NonCallableMock(name='In | validIdentityMock')
invalid_identity.is_valid |
# Copyright 2020 Tensorforce Team. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | Uniform distribution:
<ul>
<li><b> | minval</b> (<i>int / float</i>) – Lower bound
(<span style="color:#00C000"><b>default</b></span>: 0 / 0.0).</li>
<li><b>maxval</b> (<i>float > minval</i>) – Upper bound
(<span style="color:#00C000"><b>default</b></span>: 1.0 for float,
<span style="color:#C000... |
from di | stutils.core import setup
setup(
name = 'ml_easy_peer_grade',
packages = ['ml_easy_peer_grade'],
version = '0.18',
scripts=['bin/ml_easy_peer_grade'],
description = 'Ez peer grade your project members, exclusive to privileged Bilkent students',
author = 'Cuklahan Dorum',
author_email = 'badass@alumni.bil... | [],
)
|
evisions")
class Revisions(Collection):
"""
A collection of revisions indexes by title, page_id and user_text.
Note that revisions of deleted pages are queriable via
:class:`mw.api.DeletedRevs`.
"""
PROPERTIES = {'ids', 'flags', 'timestamp', 'user', 'userid', 'size',
'sh... | r | ev_docs, rvcontinue = self._query(*args, **kwargs)
for doc in rev_docs:
yield doc
revisions_yielded += 1
if limit != None and revisions_yielded >= limit:
done = True
break
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
=========================================================================
Program: Visualization Toolkit
Module: TestNamedColorsIntegration.py
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.... | or.update({idx: vtk.vtk | ImageMaskBits()})
operator[idx].SetInputConnection(shrink.GetOutputPort())
eval('operator[' + str(idx) + '].SetOperationTo' + op + '()')
operator[idx].SetMasks(255, 255, 0)
mapper.update({idx: vtk.vtkImageMapper()})
if op != "ByPass":
... |
,'period':2},
{'name':'fitness','period':3},
{'name':'reading','period':4},
{'name':'rc-cars','period':14}]},
{'forename':'Andy','surname':'Andy','age':51, 'tags':('family',),
'job':{'name':'Killer','category':'... | name='Mike',surname='Meyer',age=14, tags=('work'),
job=Job(name='Banker',category='Business'),
hobbies=[Hobby(name='swimming',period=14)]
),
Person(forename='Marc',surname='Andrew',age=78, tags=('hobby','work'),
| job=Job(name='Police',category='Government'),
hobbies=[Hobby(name='swimming',period=7),
Hobby(name='music',period=1),
Hobby(name='reading',period=2),]
),
Person(forename='Marc',surname='Muscels',age=35, tags=('family'... |
# Copyright (C) 2009, Hyves (Startphone Ltd.)
#
# This module is part of the Concurrence Framework and is released under
# the New BSD License: http://www.opensource.org/licenses/bsd-license.php
from concurrence.timer import Timeout
from concurrence.database.mysql import ProxyProtocol, PacketReader, PACKET_READ_RESULT... | lf.protocol = None
self.reader = None
self.buffer = None
def reset(self, state):
self.protocol.reset(state)
def readFromStream(self):
#read some data from | stream into buffer
if self.remaining:
#some leftover partially read packet from previous read, put it in front of buffer
self.buffer.limit = self.buffer.position + self.remaining
self.buffer.compact()
else:
#normal clear, position = 0, limit = capacity
... |
"""
Setup/build script for MasterChess
For usage info, see readme.md
"""
import os, sys, subprocess
from distutils.dir_util import copy_tree
from setuptools import setup
from MasterChessGUI import __description__, __copyright__, __version__
def get_folder(path):
if isinstance(path, list):
return [get_fo... | + __version__)] # TODO: Test this!!
}
]
})
if PY2EXE_BUNDLE:
options.update({
"options": {
"py2exe": {
"bundle_files": 1
}
},
"zipfile": None
})
else:
options.update({
"scrip... | "data_files": DATA_FILES,
"install_requires": ["wx"]
})
setup(**options)
if sys.platform == "darwin" and "py2app" in sys.argv:
# If we have a compiled MC-QuickLook or MC-Spotlight, include that
if os.path.isdir(os.path.join("dist", "MasterChess.app", "Contents")):
# QuickLook
... |
# -*- coding: utf-8 -*-
# © 2011 Raphaël Valyi, Renato Lima, Guewen Baconnier, Sodexis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, models, fields
class ExceptionRule(models.Model):
_inherit = 'exception.rule'
rule_group = fields.Selection(
selection_add... | ss SaleOrder(models.Model):
_inherit = ['sale.order', 'base.exception']
_name = 'sale.order'
_order = 'main_exception_id asc, date_order desc, name desc'
rule_group = fields.Selection(
selection_add=[('sale', 'Sale')],
default='sale',
)
@api.model
def test_all_draft_orders(... | et.test_exceptions()
return True
@api.constrains('ignore_exception', 'order_line', 'state')
def sale_check_exception(self):
orders = self.filtered(lambda s: s.state == 'sale')
if orders:
orders._check_exception()
@api.onchange('order_line')
def onchange_ignore_excep... |
# -*- coding: utf-8 -*-
# Copyright 2013 Christoph Reiter
#
# 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 2 of the License, or
# (at your option) any later version.
"""Everythi... | M_PROP_LABEL,
_("Play/Pause"))
play_pause.property_set_bool(Db | usmenu.MENUITEM_PROP_VISIBLE, True)
main.child_append(play_pause)
def play_pause_cb(item, timestamp):
player.playpause()
play_pause.connect("item-activated", play_pause_cb)
next_ = Dbusmenu.Menuitem()
next_.property_set(Dbusmenu.MENUITEM_PROP_LABEL, _("Next"))
next_.property_set_bool(... |
#Problem J4: Wait Time
inputarray = []
for i in range(input()):
inputarray.append(raw_input().split(" "))
#Number, total, lastwait, response
frie | ndarray = []
ctime = 0
for i in range(len(inputarray)):
if inputarray[i][0].lower() == "c":
ctime += inputarray[i][1]
if inputarray[i][0].lower() == "r":
friendlist = [friendarray[j][0] for j in range(len(friendarray))]
if (inputarray[i][1] not in frien | dlist):
friendarray.append([inputarray[i][0].lower(), 0, ])
else:
location = friendlist.index(inputarray[i][1])
friendarray[location] = [inputarray[i][1], friendarray[location] + ]
|
# pytgasu - Automating creation of Telegram sticker packs
# Copyright (C) 2017 Lemon Lam <almk@rmntn.net>
#
# 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
# ... | ip() for l in f] # strip line breaks
except ValueError:
print(ERROR_DEFFILE_ENCODING % def_file)
else:
set_title = lines[0]
| set_short_name = lines[1]
stickers = list() # there may be a 120 stickers per set hard limit, idk
for sticker_line in lines[2:]:
if not _sticker_line_pattern.fullmatch(sticker_line):
print(ERROR_INCORRECT_STICKER_LINE % sticker_line)
continue
... |
import pandas as pd
from pandas import DataFrame
df = pd.read_csv('sp500_ohlc.csv', index_col = 'Date', parse_dates=True)
#n | otice what i did, since it is an object
df['H-L'] = df.High - df.Low
print df.head()
df['100MA'] = pd.rolling_mean(df['Close'], 100)
# must do a slice, since there will be no value for 100ma until 100 points
print df[200:210]
df['Difference'] = df['Close'] | .diff()
print df.head()
|
w.mouse.LEFT: "left",
pyglet.window.mouse.MIDDLE: "middle",
pyglet.window.mouse.RIGHT: "right",
}
@self.window.event
def on_mouse_motion(x, y, dx, dy):
y = self.h - y
h = self.getHandlerMethod("onMouseMove")
if h: h(x, ... | n getter
def _colorComponentSetter(i):
def setter(self, x):
components = list(self.sprite.color)
components[i] = int(x * 255)
self.sprite.color = components
return setter
r = property(_colorComponentGetter(0), _colorCompo | nentSetter(0))
g = property(_colorComponentGetter(1), _colorComponentSetter(1))
b = property(_colorComponentGetter(2), _colorComponentSetter(2))
def _setOpacity(self, x): self.sprite.opacity = int(x*255.0)
def _getOpacity(self): return self.sprite.opacity/255.0
opacity = property(_getOpacity, _... |
(self, backend, rigor_config):
self.rigor_config = rigor_config
self.backend = backend
try:
self.thumbnail_size_max = int(rigor_config.get("webapp","thumbnail_size_max"))
except rigor.config.NoValueError:
self.thumbnail_size_max = 128
try:
self.results_per_page = int(rigor_config.get("webapp","percep... | search_results %}
<div class="searchResult">
<a href="/db/{{db_name}}/percept/{{'{}'.format(percept.id)}}">
| {% if percept.x_size and percept.y_size: %}
<img class="searchResultImg" src="{{percept.img_url+'?max_size='}}{{thumbnail_size_max}}" width="{{thumbsize(percept.x_size, percept.y_size)[0]}}" height="{{thumbsize(percept.x_size, percept.y_size)[1]}}" />
{% else %}
<div class="missingImage" style=... |
#!/usr/bin/env python
from os import path
from collections import defaultdict
import math
root = path.dirname(path.dirname(path.dirname(__file__)))
result_dir = path.join(root, 'results')
def get_file_name(test):
test = '%s_res | ult' % test
return path.join(result_dir, test)
def mean(l):
return float(sum(l))/len(l) if len(l) > 0 else float('nan')
def std_dev(l):
m = mean(l)
return math.sqrt(sum((x - m) ** 2 for x in l) / len(l))
def run_timing_overhead_ana():
test_name = 'timing_overhead'
file_name = get_file_name(te... | le_name) as f:
for l in f:
datas.append(int(l))
datas = [i for i in datas[:10000]]
print "%s mean: %f" % (test_name, mean(datas))
print "%s std dev: %f" % (test_name, std_dev(datas))
def run_loop_overhead_ana():
test_name = 'loop_overhead'
file_name = get_file_name(test_name)
... |
"""Support for the Airly air_quality service."""
from homeassistant.components.air_quality import (
ATTR_AQI,
ATTR_PM_2_5,
ATTR_PM_10,
AirQualityEntity,
)
from homeassistant.const import CONF_NAME
from .const import (
ATTR_API_ADVICE,
ATTR_API_CAQI,
ATTR_API_CAQI_DESCRIPTION,
ATTR_API_C... | IT],
LABEL_PM_2_5_PERCENT: round(self.coordinator.data[ATTR_API_PM25_PERCENT]),
LABEL_PM_10_LIMIT: self.coordinator.data[ATTR_API_PM10_LIMIT],
LABEL_PM_10_PERCENT: round(self.coordinator.data[ATTR_API_PM10_PERCENT]),
}
async def async_a | dded_to_hass(self):
"""Connect to dispatcher listening for entity data notifications."""
self.async_on_remove(
self.coordinator.async_add_listener(self.async_write_ha_state)
)
async def async_update(self):
"""Update Airly entity."""
await self.coordinator.async_r... |
# -*- coding: utf-8 -*-
from openerp impor | t models, fields, api
class CalendarEvent(models.Model):
_inherit = 'calendar.event'
meeting_reason_id = fields.Many2one(
'calendar.event.meeting.reason',
string="Meeting reason",
ondelete="restrict")
class CalendarEventMeetingReason(models.Model):
_name = 'calendar.event.meeting.... | )
|
"""SCons.Tool.mwcc
Tool-specific initialization for the Metrowerks CodeWarrior compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001 - 2014 The SCons Foundation
#
# Permission is he... | ense = os.path.join(path, 'license.dat')
self.includes = [msl, support]
self.libs = [msl, support]
def __str__(self):
return self.version
CSuffixes = ['.c', '.C']
CXXSuffixes = ['.cc', '.cpp', '.cxx', | '.c++', '.C++']
def generate(env):
"""Add Builders and construction variables for the mwcc to an Environment."""
import SCons.Defaults
import SCons.Tool
set_vars(env)
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in CSuffixes:
static_obj.add_action(suffix, S... |
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTW... | ABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, A | RISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
import libtcodpy as libtcod
import tokenizer
import match
import textfield
import textview
import command
SCREEN_WIDTH = 80
SCREEN_HEIGHT = 35
FONT_FLAGS = libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD
FONT_FILE = 'fonts/dejavu12x... |
from django.contrib import admin
from treebeard.admin import TreeAdmin
from treebeard.forms import movenodeform_factory
from oscar.core.loading import get_model
AttributeOption = get_model('catalogue', 'AttributeOption')
AttributeOptionGroup = get_model('catalogue', 'AttributeOptionGroup')
Category = get_model('catal... | dmin.site.register(ProductClass, ProductClassAdmin)
admin.site.register(Product, ProductAdmin)
admin.site.register(ProductAttribute, ProductAttributeAdmin)
admin.site.register(ProductAttributeValue, ProductAttributeValueAdmin)
admin.site.register(AttributeOptionGroup, AttributeOptionGroupAdmin)
admin.site | .register(Option, OptionAdmin)
admin.site.register(ProductImage)
admin.site.register(Category, CategoryAdmin)
admin.site.register(ProductCategory)
|
# regression tree
# input is a dataframe of features
# the corresponding y value(called labels here) is the scores for each document
import pandas as pd
import numpy as np
from multiprocessing import Pool
from itertools import repeat
import scipy
import scipy.optimize
node_id = 0
def get_splitting_points(args):
#... | _depth > max_depth:
return create_leaf(label)
#######
min_error = None
split_var = None
min_split = None
var_spaces = [data.iloc[:,col].tolist() for col in xrange(data.shape[1])]
cols = [col for col in xrange(data.shape[1])]
pool = Pool()
for split, error, ierr, numf in pool.map(find_splits_parall | el, zip(var_spaces, repeat(label), cols)):
if not min_error or error < min_error:
min_error = error
split_var = col
min_split = split
pool.close()
splitting_feature = (split_var, min_split)
children = split_children(data, label, split_var, min_split)
left_data, left_label, right_data, right_label = chi... |
ory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import monary
# If extensions (or modules to document with autodoc... | themes.
html_theme = 'defau | lt'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of... |
form = self.search_form.refresh()
get_filter_args(self._filters)
widgets = self._get_chart_widget(
filters=self._filters,
definition=self.definitions[group_by],
order_column=self.definitions[group_by]["group"],
order_direction="asc",
)
wi... | f,
filters=None,
order_column="",
order_direction= | "",
widgets=None,
group_by=None,
height=None,
**args
):
height = height or self.height
widgets = widgets or dict()
group_by = group_by or self.group_by_columns[0]
joined_filters = filters.get_joined_filters(self._base_filters)
value_columns = ... |
#!/usr/bin/env python
'''
Pymodbus Asynchronous Client Examples
--------------------------------------------------------------------------
The following is an example of how to use the asynchronous modbus
client implementation from pymodbus.
'''
#------------------------------------------------------------------------... | ': 1,
'read_count': 8,
'write_address': 1,
'write_registers': [20]*8,
}
rq = client.readwrite_registers(**arguments)
rr = client.read_input_reg | isters(1,8)
dassert(rq, lambda r: r.registers == [20]*8) # test the expected value
dassert(rr, lambda r: r.registers == [17]*8) # test the expected value
#-----------------------------------------------------------------------#
# close the client at some time later
#---------------------... |
import pytest
from fastapi.testclient import TestClient
from ...utils import needs_py310
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"get": {
"responses": {
"200": {
... | "in": "query",
}
],
}
}
},
"components": {
"schemas": {
"ValidationError": {
"title": "ValidationError",
"required": ["loc", "msg", "type"],
"type": "object",
... | "items": {"type": "string"},
},
"msg": {"title": "Message", "type": "string"},
"type": {"title": "Error Type", "type": "string"},
},
},
"HTTPValidationError": {
"title": "HTTPValidationError",
... |
tProp('Power', experiment, 'Power (dBm)', '0')
self.pulsewidth = FloatProp('PulseWidth', experiment, 'Pulse Width (us)', '0')
self.pulserep = FloatProp('PulseRep', experiment, 'Pulse Rep Time (us)', '0')
self.startfreq = FloatProp('StartFreq', experiment, 'Start Frequency (MHz)', '0')
... | errcode = self.va.fnLMS_InitDevice(self.ID)
if (errcode != 0):
logger.error("Failed to initialize Vaunix device {}. Error code {}.".format(self.ID,errcode))
raise PauseError
self.maxPower = int(self.va.fnLMS_GetMaxPwr(self.ID)/4)
self.minPower = in... | self.maxFreq = int(self.va.fnLMS_GetMaxFreq(self.ID))
return
def freq_unit(self,val):
return int(val*100000)
def power_unit(self,value):
return int((self.maxPower - value)*4)
def power_sanity_check(self,value):
if (value < self.minPo... |
# -*- coding: utf-8 -*-
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__ ... | t'][0:len(nick)] == nick and m | sg['action'] == "PRIVMSG":
if msg['text'] == "\x01VERSION\x01":
self.log_debug(_("Sending CTCP VERSION"))
sock.send("NOTICE %s :%s\r\n" % (msg['origin'], ctcp_version))
elif msg['text'] == "\x01TIME\x01":
se... |
import os
import argparse
import tensorflow as tf
import numpy as np
import sys
sys.path.append('../')
from reader import flickr8k_raw_data
def make_example(image_feature, caption_feature, id):
# The object we return
ex = tf.train.SequenceExample()
# A non-sequential feature of our example
sequence_le... | vocab = flickr8k_raw_data(
args.caption_tokens_dir)
rand_idx = np.arange(0, len(train_caps['names']))
rng = np.random.RandomState(seed=1234)
rng.shuffle(rand_idx)
# dump the captions generated for debugging purpose
with open(os.path.join(args.caption_tokens_dir, 'dump.txt'), 'w') as fp:
... | pprint import pformat
fp.write("\n###### vocab######\n")
fp.write(pformat(vocab))
fp.write("\n###### train ######\n")
rand_train_caps = {
'names': [train_caps['names'][i] for i in rand_idx],
'word_to_ids': [train_caps['word_to_ids'][i] for i in rand_idx],
}
fp.write(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.