prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
import collections
class Command:
def __init__(self, template):
self._values = template
def __getite | m__(self, key):
value = self._values[key]
if isinstance(value, dict) or isinstance(value, list):
return Command(value)
return self._values[key]
def __setitem__(self, key, value):
try:
self._values[key] = type(self._values[key])(value)
except ValueErro... | eption):
pass
|
from django.conf import settings
from gnip_search.gnip_search_api import GnipSearchAPI
from gnip_search.gnip_search_api import QueryError as GNIPQueryError
class Frequency:
"""
Class collection for Frequency
"""
DATE_FORMAT = "%Y-%m-%d %H:%M"
def __init__(self, query, sample, start, end):
... | return result
def get(self, data):
| response_data = []
for f in data:
response_data.append(f)
response_data = sorted(response_data, key=lambda f: -f[3])
return response_data
|
from dive_operator import DiveOperator
from dive_python_operator import DivePy | thonOperator
__all__ = ['DiveOperator | ', 'DivePythonOperator']
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from bottle import route, get, post, view, run, app, default_app, static_file
from palpite import palpite
@get('/')
@view('index.html')
def i | ndex_get():
return dict()
@post('/')
@view('index.html')
def index_post():
gera_palpite = palpite()
return dict(jogo=gera_palpite)
@get('/favicon.ico')
@get('/favicon.png')
def favicon():
return static_file('/static/favicon.png', root='.')
@get('/normalize.css')
def no | rmalizecss():
return static_file('normalize.css', root='static')
@get('/skeleton.css')
def skeletoncss():
arq = 'skeleton.css'
return static_file(arq, root='./static')
app = default_app()
app.run(server='gae',debug=True)
|
"""
ONE-TIME UPDATE OF converting SubredditPage.created_at, FrontPage.created_at to u | tc
Daylight Savings Time = Nov 6 2am
if we see the ET time Nov 6 12am, then it is EDT: EDT-->UTC = +4 = Nov 6 4am
if we see the ET time Nov 6 1-2am, then it is unclear whether it is EDT or EST; assume it is EST
> assumption is becaues I don't think we really care about this, as long as we are consistent
if we see ... | me Nov 6 2:30am, then it is EST: EST-->UTC = +5 = Nov 6 7:30am
if we see the ET time Nov 6 3am, then it is EST: EST-->UTC = +5 = Nov 6 8am
"""
import re, random, string, sys, math, os, datetime
BASE_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../", "../")
sys.path.append(BASE_DIR)
import simpl... |
"""Contains a baseclass for plugins."""
###############################################################################
#
# TODO: [ ]
#
###############################################################################
# standard library imports
from collections import Iterable
from functools import wraps
import loggin... | self.power_on_keywords = ["turn.on." + self.name.lower()]
self.power_off_keywords = ["turn.off." + self.name.lower()]
if group:
if not isinstance(group, str) and isinstance(group, Iterable):
top_level = []
sub_level = []
words = []
... | top_level.append(key)
words.append(key)
for sub in sub_level:
for top in top_level:
words.append(sub + top)
for word in words:
self.power_on_keywords.append("turn.on." + word.lower(... |
class A:
def test(self):
print "I##|nitializing A", "test"##|
attribute = "hello"
| def my_method(self):
print self.attribute
a = A()
a.test()
##r Should expand to Full String "Initializing | A"
# Invalid selection:
# nitializing A", "test" |
.json and task_run.json from MoorFrog
Output is a set of bounding boxes, well pad points,
and pond clicks.
""".format(__docname__, '-' * len(__docname__)))
return 1
#/* ======================================================================= */#
#/* Define print_help_info() function
#/* ======================... | :type tasks: list
:param layer: OGR layer object
:type layer: <ogr.Layer class>
:return: True on success and False on failure
:rtype: bool
"""
| # Update user
print("Creating bounding boxes")
# Define fields
print(" Defining bbox fields...")
fields_definitions = (('id', 10, ogr.OFTInteger),
('site_id', 254, ogr.OFTString),
('location', 254, ogr.OFTString),
('wms_... |
"""Module defining ``Eigensolver`` classes."""
import numpy as np
from gpaw.utilities.blas import axpy
from gpaw.eigensolvers.eigensolver import Eigensolver
from gpaw import extra_parameters
class RMM_DIIS(Eigensolver):
"""RMM-DIIS eigensolver
It is expected that the trial wave functions are orthonormal
... | weight = kpt.weight
else:
weight = kpt.f_n[n]
if self.nbands_converge != 'occupied':
if wfs.bd.global_index(n) < self.nbands_converge:
weight = kpt.weight
else:
| weight = 0.0
error += weight * integrate(R_xG[n - n1], R_xG[n - n1])
# Precondition the residual:
self.timer.start('precondition')
ekin_x = self.preconditioner.calculate_kinetic_energy(
psit_xG, kpt)
dpsit_xG = self.preconditio... |
"""empty message
Revision ID: 2728b7328b78
Revises: d7c7f3be40a
Create Date: 2015-10-20 13:44:12.129389
"""
# revision ide | ntifiers, used by Alembic.
revision = '2728b7328b78'
down_revision = 'd7c7f3be40a'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generat | ed by Alembic - please adjust! ###
op.drop_table('conference_schedule')
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('conference_schedule',
sa.Column('id', sa.INTEGER(), nullable=False),
sa.Column('entry', sa.VARCHAR(... |
project: str = None,
service_account_file: str = "",
):
channel.initialize()
self.name = name
self.display_name = display_name
self.allow_password_signup = allow_password_signup
self.enable_email_link_signin = enable_email_link_signin
self.disable_auth =... | email_link_signin
)
self.disable_auth = Primitive.from_proto(response.disable_auth)
self.enable_anonymous_user = Primitive.from_proto(
response.enable_anonymous_user
)
self.mfa_config = TenantMfaConfig.from_proto(response.mfa_config)
self.test_phone_numbers = ... | ct = Primitive.from_proto(response.project)
def delete(self):
stub = tenant_pb2_grpc.IdentitytoolkitAlphaTenantServiceStub(channel.Channel())
request = tenant_pb2.DeleteIdentitytoolkitAlphaTenantRequest()
request.service_account_file = self.service_account_file
if Primitive.to_proto... |
# -*- coding: utf-8 -*-
"""The application's model objects"""
from zope.sqlalchemy import ZopeTransactionExtension
from sqlalchemy.orm import scoped_session, sessionmaker
# from sqlalchemy import MetaData
from sqlalchemy.ext.declarative import declarative_base
# Global session manager: DBSession() returns the Thread-l... | de tg2, you need to make sure this is called before
# you use the model.
#
# See the following example:
# global t_reflected
# t_reflected = Table("Reflected", metadata,
# autoload=True, autoload_with=engine)
# mapper(Reflected, t_reflected)
# Import your model modules here.
from tri... | e import *
# from tribal.model.pei import *
from tribal.model.sysutil import *
from tribal.model.dba import *
from tribal.model.bby import *
from tribal.model.tag import *
# from tribal.model.cabelas import *
from tribal.model.lemmi import *
from tribal.model.tmw import *
from tribal.model.mglobalpack import *
from tri... |
import os
import flask
import memdam.blobstore.localfolder
import memdam.eventstore.sqlite
from memdam.server.web import app
def get_archive(username):
| """
:param username: the name of the user for which we should get the event archive
:type username: string
:returns: a new (or cached) archive
:rtype: memdam.eventstore.api.Eventstore
"""
db_file = app.config['DATABASE_FOLDER']
if db_file == ':memory:':
| return flask.g._archives[username]
assert db_file != ''
db_file = os.path.join(db_file, username)
if not os.path.exists(db_file):
os.makedirs(db_file)
archive = memdam.eventstore.sqlite.Eventstore(db_file)
return archive
def get_blobstore(username):
"""
:param username: the ... |
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from nipype.testing import assert_equal
from nipype.interfaces.semtools.utilities.brains import BRAINSInitializedControlPoints
def test_BRAINSInitializedControlPoints_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
use... | for key, metadata in output_map.items():
for metakey, value in met | adata.items():
yield assert_equal, getattr(outputs.traits()[key], metakey), value
|
#! /usr/bin/python
# Copyright (c) 2015, Matthew P. Grosvenor
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# ... | )
if l | en(nums) < 100:
print "Fatal Error! Not enough points (%i)" % len(nums)
sys.exit(-1)
nums.sort()
#min = numpy.min(nums)
#max = numpy.max(nums)
#print min,max
(ys,xs) = numpy.histogram(nums,bins=bins_count, range=[min(nums),max(nums)])
percent = [0,1,10,25,50,75,90,99,100]
print "Total samples %i" % len(nums)... |
import psyco
psyco.full()
import linker.coff
from linker import store
m,n='python26.dll','Py_DecRef'
localname = None,'__imp__<%s!%s>'%(m,n)
if True:
# this should import from python26.lib,Py_DecRef
# this should export ia32.obj,stuff
a = linker.coff.object.open('~/work/syringe/src | /ia32.obj')
# imports None,Py_DecRef
# this should import from python26.dll,Py_DecRef
# this should export Py_DecRef
b = linker.coff.library.open('~/python26/libs/python26.lib')
# imports python26.dll,Py_DecRef
# exports None,Py_DecRef
# this should import from whatever
# and export wh... | d = linker.coff.executable.open('~/../../windows/syswow64/msvcr100.dll')
# raise NotImplementedError("symbol consolidation isn't working")
if True:
z = b
z[store.BaseAddress] = 0x10000000
for x in z.undefined:
z[x] = 0xbbbbbbbb
out = file('blah','wb')
for x in z.segments:
y = ... |
tReaderTC
from hwtLib.structManipulators.structWriter_test import StructWriter_TC
from hwtLib.tests.constraints.xdc_clock_related_test import ConstraintsXdcClockRelatedTC
from hwtLib.tests.frameTmpl_test import FrameTmplTC
from hwtLib.tests.pyUtils.arrayQuery_test import ArrayQueryTC
from hwtLib.tests.pyUtils.fileUtils... | drcodedFsmExampleTC,
OneHotToBinTC,
BinToBcdTC,
BcdToBinTC,
AxiS_strFormat_TC,
BinToOneHotTC,
GrayCntrTC,
TwoCntrsTC,
SelfRefCntrTC,
CountLeadingTC,
MultiplierBoothTC,
IndexingTC,
CdcTC,
RamResourcesTC,
SimpleAsyncRamTC,
SimpleSyncRamTC,
SimpleUnitAxiStrea... | d_randomized_TC,
HsJoinFair_2inputs_TC,
HsJoinFair_3inputs_TC,
HandshakedCdc_slow_to_fast_TC,
HandshakedCdc_fast_to_slow_TC,
*HandshakedToAxiStreamTCs,
*RamAsHs_TCs,
LfsrTC,
BitonicSorterTC,
InterfaceWithArrayTypesTC,
FlipRegTC,
FlipCntrTC,
FlipRamTC,
HsSplitCopyTC,
... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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.
#
# This program is ... | l = "Active Ele | ment"
@classmethod
def poll(cls, context):
return (context.meta_ball and context.meta_ball.elements.active)
def draw(self, context):
layout = self.layout
metaelem = context.meta_ball.elements.active
layout.prop(metaelem, "type")
split = layout.split(... |
import os
def create_fds():
(fd1, fd2) = os.p | ipe()
return (os.fdopen(fd2, "w"), os.fdopen(fd1, "r"))
def filename(pipef):
return 'pipe:[%d]' % os.fstat(pipef.f | ileno()).st_ino
def dump_opts(sockf):
return [ ]
|
"""MiniAEFrame - A minimal AppleEvent Application framework.
There are two classes:
AEServer -- a mixin class offering nice AE handling.
MiniApplication -- a very minimal alternative to FrameWork.py,
only suitable for the simplest of AppleEvent servers.
"""
from warnings import warnpy3k
warnpy3k("In 3... | r(self, event):
what, message, when, where, modifiers = event
h, v = where
if what == kHighLevelEvent:
msg = "High Level Event: %r %r" % (code(message), code(h | (v<<16)))
try:
AE.AEProcessAppleEvent(event)
except AE.Error, err:
... | rr
print 'in', msg
traceback.print_exc()
return
elif what == keyDown:
c = chr(message & charCodeMask)
if modifiers & cmdKey:
if c == '.':
raise KeyboardInterrupt, "Command-period"
if c == 'q':... |
"""
Test basic std::weak_ptr functionality.
"""
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestSharedPtr(TestBase):
mydir = TestBase.compute_mydir(__file__)
@add_test_categories(["libc++"])
@skipIf(compiler=no_match("clang"))
... | il.run_to_source_breakpoint(self,
"// Set break point at this line.", lldb.SBFileSpec("main.cpp"))
self.runCmd("settings set target.import-std-module true")
self.expect("expr (int)*w.lock()", substrs=['(int) $0 = 3'])
self.expect("expr (int)(*w.lock() = 5)", substrs=['(int) $1 = 5'... |
self.expect("expr w.use_count()", substrs=['(long) $4 = 0'])
|
"""Support for Alexa skill auth."""
import asyncio
from datetime import timedelta
import json
import logging
import aiohttp
import async_timeout
from homeassistant.core import callback
from homeassistant.helpers import aiohttp_client
from homeassistant.util import dt
_LOGGER = logging.getLogger(__name__)
LWA_TOKEN_... | return None
lwa_params = {
"grant_type": "refresh_token",
"refresh_token": self._prefs[STORAGE_REFRESH_TOKEN],
"client_id": self.client_i | d,
"client_secret": self.client_secret,
}
_LOGGER.debug("Calling LWA to refresh the access token.")
return await self._async_request_new_token(lwa_params)
@callback
def is_token_valid(self):
"""Check if a token is already loaded and if it is still va... |
import requests
import time
import json
# ------------ Do data need to roll
def roll_data_if_needed(secondsAllowed):
# calculate last time
last_roll_time = get_status()
now = int(time.time())
time_since_roll = now - last_roll_time
# do I need to roll?
if time_since_roll > secondsAllowed:
| roll_data()
else:
print 'do not roll'
# ------------ Get current status
def get_status():
response = firebaseGet('status.json')
json = response.json()
return json.get('lastRollTime')
# ------------ Roll the data
def roll_data():
# delete backu | p
firebaseDelete('temperatures-backup.json')
# update status time
data = '{{"lastRollTime": {:d}}}'.format(int(time.time()))
firebasePut('status.json', data)
# get current values
response = firebaseGet('temperatures.json')
current_values = response.text
# add to backup
firebasePut... |
"""
Tests for the plugin API
"""
from __future__ import ab | solute_import
from django.test import TestCase
from openedx.core.lib.plugins import PluginError
from openedx.core.lib.course_tabs import CourseTabPluginManager
class TestCourseTabApi(TestCase):
"""
Unit tests for the course tab plugin API
"""
def test_get_plugin(self):
"""
Verify tha... | rseTabPluginManager.get_plugin("instructor")
self.assertEqual(tab_type.title, "Instructor")
with self.assertRaises(PluginError):
CourseTabPluginManager.get_plugin("no_such_type")
|
nk_stat * scalar are TRUE, i.e. non-contam
sequences. To return contaminants (sequences that FAIL the inequality),
set negate to True."""
i_s = stats_header.index(sample_stat)
i_b = stats_header.index(blank_stat)
passed_otus = set()
for otu in stats_dict:
if((float(stats_dict[otu][i_s... | s = opts.valid_states
blank_id_fp = opts.blank_id_fp
contaminant_db_fp = opts.contaminant_db_fp
contaminant_similarity = opts.contaminant_similarity
max_correlation = opts.max_correlation
correlate_header | = opts.correlat |
fter experimenting w/ disabling the USB reset.
from devil.utils import reset_usb # pylint: disable=unused-import
logger = logging.getLogger(__name__)
from py_utils import modules_util
# Script depends on features from psutil version 2.0 or higher.
modules_util.RequireVersion(psutil, '2.0')
def KillAllAdb():
def... | f denylist:
denylist.Extend([device.adb.GetDeviceSeri | al()], reason='reboot_failure')
except device_errors.CommandTimeoutError:
logger.exception('Timed out while rebooting %s.', str(device))
if denylist:
denylist.Extend([device.adb.GetDeviceSerial()], reason='reboot_timeout')
try:
device.WaitUntilFullyBooted(
retries=0, timeout... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018-2019 Matthias Klumpp <matthias@tenstral.net>
#
# Licensed under the GNU Lesser General Public License Version 3
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free... | he event to the world
self._pub_queue.put([bytes(event['tag'], 'utf-8'),
bytes(data, 'utf-8')])
def run(self): |
if self._socket:
log.warning('Tried to run an already running event receiver again.')
return
self._socket = self._ctx.socket(zmq.ROUTER)
self._socket.bind(self._endpoint)
server_stream = zmqstream.ZMQStream(self._socket)
server_stream.on_recv_stream(sel... |
from __future__ import absolute_import
from collections import namedtuple
# Other useful structs
TopicPartition = namedtuple("TopicPartition",
["topic", "partition"])
| BrokerMetadata = namedtuple("BrokerMetadata",
["nodeId", "host", "port", "rack"])
PartitionMetadata = namedtuple("PartitionMetadata",
["topic", "partition", "leader", "replicas", "isr", "error"])
OffsetAndMetadata = namedtuple("OffsetAndMetadata",
# TODO | add leaderEpoch: OffsetAndMetadata(offset, leaderEpoch, metadata)
["offset", "metadata"])
OffsetAndTimestamp = namedtuple("OffsetAndTimestamp",
["offset", "timestamp"])
# Define retry policy for async producer
# Limit value: int >= 0, 0 means no retries
RetryOptions = namedtuple("RetryOptions",
["limit"... |
import argparse
i | mport changeling_client.api
import changeling_client.commands
parser = argparse.ArgumentParser()
parser.add_argument('--endpoint', required=True)
subparsers = parser.add_subparsers()
changeling_client.commands.register(subparsers)
def main():
args = parser.parse_args()
service = changeling_client.api.Servi... | t)
args.func(service, args)
|
ance of class.
@param version: Version must either be a string or a tuple of integers
or strings representing integers.
Version strings must begin with integer numbers separated by dots and
may end with any string.
"""
self._versio... | """Returns string representation of version.
"""
return self._versionstr
class TableFilter:
"""Class for filtering rows of tables based on filters on values of columns.
The tables are represented as nested lists (list of lists of columns.)
"""
def __init__(self... | ignore_case=False):
"""Register filter on a column of table.
@param column: The column name.
@param patterns: A single pattern or a list of patterns used for
matching column values.
@param is_regex: The patterns will be treated... |
"""EAS two-devices turn
Revision ID: 17dc9c049f8b
Revises: ad7b856bcc0
Create Date: 2014-10-21 20:38:14.311747
"""
# revision identifiers, used by Alembic.
revision = '17dc9c049f8b'
down_revision = 'ad7b856bcc0'
from datetime import datetime
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import... | _at=datetime.utcnow(),
filtered=False,
eas_device_id=a._eas_device_id,
eas_device_type=a._eas_device_type,
eas_policy_key=a.eas_policy_key,
eas_sync_k... | nc_key)
a.primary_device = primary
a.secondary_device = secondary
db_session.add(a)
db_session.commit()
conn = op.get_bind()
acct_device_map = dict(
(id_, device_id) for id_, device_id in conn.execute(text(
"""SELECT id, secondary_device_id fr... |
import asyncio
import pip
import pickle
import os.path
try:
import discord
except:
pip.main(['install', 'git+https://github.com/Rapptz/discord.py@async#egg=discord.py'])
try:
import win_unicode_console
except:
0
try:
from lxml import html
except ImportError:
pip.main(['install', 'lxml'])
t... | d_message(channel, message, tts=True)
# Save the new list into the file
with open(cachedFilePath, 'w') as file:
for key, value in newList.items():
file.write('%s: %s\n' % (key.replace(':', colonId), value))
print('Done checking bookmarks for \'%s\'!'... | in server.channels:
if channel.id == channelId:
return channel
return 0
def kiss_list_from_bookmarks(self, content):
dataList = {}
table = content[content.find('<table class="listing">'):content.find('</table>')]
table = table[table.find(... |
'''trec_dd.* namespace package can have several subpackages, see
http://github.com/trec-dd for more info
.. This software is released under an MIT/X11 open source license.
Copyright 2015 Diffeo, Inc.
'''
im | port pkg_resources
pkg_resou | rces.declare_namespace(__name__)
|
with a too long section of type waiting
"""
# early | returns
# if there is no transfer it won't have any waiting sections
if journey.nb_transfers == 0:
return True
if journey.duration < self.max_waiting_duration:
return True
for s in journey.sections:
if s.type != response_pb2.WAITING:
... | continue
return False
return True
class FilterMaxSuccessivePhysicalMode(SingleJourneyFilter):
message = 'too_much_successive_section_same_physical_mode'
def __init__(self, successive_physical_mode_to_limit_id='physical_mode:Bus', max_successive_physical_mode=3):
self.... |
from django import forms
from depotwork.questions.models import Question, Answer
class QuestionForm(forms.ModelForm):
title = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}),
max_length=255)
description = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control'}),
... | odel = Question
fields = ['title', 'description', 'tags']
class AnswerForm(forms.ModelForm):
question = forms.ModelChoiceField(widget=forms.HiddenInput(), queryset=Question.objects.all())
description = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control', 'rows':'4'}),
max_lengt... |
fields = ['question', 'description'] |
"""
==========================================
Author: Tyler Brockett
Username: /u/tylerbrockett
Description: Alert Bot (Formerly sales__bot)
Date Created: 11/13/2015
Date Last Edited: 12/20/2016
Version: v2.0
==========================================
"""
import praw
im... | return []
except Exception as e:
Logger.log(traceback.format_exc(), Color.RED)
raise RedditHelperException(RedditHelperException.GET_SUBMISSIONS_EXCEPTION)
return submissions
def | get_original_message_id(self, received_message, database):
message = received_message
while message.parent_id and len(database.get_subscriptions_by_message_id(str(message.author), message.id)) == 0:
message = self.reddit.inbox.message(message.parent_id[3:])
return message.id
def... |
#!/usr/bin/python2
import collections
import os
from loranode import RN2483Controller
# from ../_examplify.py import Examplify
import os
os.sys.path.append(os.path.dirname(os.path.abspath('.')))
from _examplify import Examplify
import lora, pmt, osmosdr
from gnuradio import gr, blocks
class ReceiveWhitening:
de... | Exception("[ReceiveWhitening] Outputfile '" + self.outputFile + "' does not exist!")
else:
ra | ise Exception("[ReceiveWhitening] Tempfile '" + self.tempFile + "' does not exist!")
else:
raise Exception("[ReceiveWhitening] Inputfile '" + self.inputFile + "' does not exist!")
if __name__ == '__main__':
ofile = '/tmp/tmp_whitening.cfile'
testset = [ (7, "4/6"), (7, "4/7"), (8, "4/5"), ... |
#
# Allows GTK 3 python applications to exit when CTRL-C is raised
# From https://bugzilla.gnome.org/show_bug.cgi?id=622084
#
# Author: Simon Feltman
# License: Presume same as pygobject
#
import sys
import signal
| from typing import ClassVar, List
from gi.repository import GLib
class InterruptibleLoopContext:
"""
Context Manager for | GLib/Gtk based loops.
Usage of this context manager will install a single GLib unix signal handler
and allow for multiple context managers to be nested using this single handler.
"""
#: Global stack context loops. This is added to per InterruptibleLoopContext
#: instance and allows for context nes... |
##############################################################################
# Copyright (c) 2013-2017, 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... | ion 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IM | PLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms 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.... |
import os
import qprompt
path = qprompt.ask_str("Enter path to file", | vld=lambda x: os.path.isfile(x))
size = | qprompt.ask_int("Enter number less than 10", vld=lambda x: x < 10)
|
self.assertEqual(response.status_code, 302)
def test_hide_from_not_user(self):
self._create_user_and_login("jo")
response = self.client.get(self.url)
self.assertEqual(response.status_code, 302)
def test_show_to_anon_if_public(self):
self.xform.shared = True
self.xfo... | d = True
self.xform.save()
response = self.anon.get(reverse(download_xlsform, kwargs={
'username': self.user.username,
'id_string': self.xform.id_string
}))
self.assertEqual(response.status_code, 200)
def test_dl_xls_for_basic_auth(self):
extra = {
... | lsform, kwargs={
'username': self.user.username,
'id_string': self.xform.id_string
}), **extra)
self.assertEqual(response.status_code, 200)
def test_dl_json_to_anon_if_public(self):
self.xform.shared = True
self.xform.save()
response = self.anon.get(r... |
# Copyright (c) 2017 SUSE LLC
import logging
import re
import subprocess
# Run a command, and return the result in string format, stripped. Return None if command fails.
def _run_cmd(cmd_array):
try:
return subprocess.check_output(cmd_array).decode("utf-8").strip()
except subprocess.CalledProcessErro... | there is an error."""
commithash = _run_cmd(['git', 'rev-parse', '--verify', 'HEAD'])
return 'Unknown commit hash' if commithash is None else commithash
def file_is_dirty(file_path):
"""If a file is new, modified, or delet | ed in git's tracking return True. False otherwise."""
file_status_msg = _run_cmd(['git', 'status', '--untracked-files=all', str(file_path)])
# git outputs filename on a line prefixed by whitespace if the file is new/modified/deleted
if re.match(r'^\s*' + file_path + '$', file_status_msg):
return Tru... |
v.log_file+"_dist"+".dat")
logger.info("End test.")
logger.info( "Wall time for all %s", time.time()-tt_glob)
return 42
else:
logger.error("Something wrong in test selection.")
else:
logger.info("This is not a test!")
# Dictionary for statistics.
... | +str(os.getpid())+'/status'
status_dest = '../logs/status'+str(os.getpid())+'@mid'
shcopy(status_src, status_dest)
stats['Time elapsed before traversing'] = time.time()-tt_glob
logger.info("Time elapsed before traversing %s", stats['Time elapsed before traversing'])
################################
#... | r.info("Starting data-data counts...")
particles_counts, trav_stats['data'], stats_array[0,:]= mod.count(d_tree_1, d_tree_2, shell, self_corr, v.strategy)
logger.info("Particles counts:")
logger.info("DD %s", particles_counts)
result_file.write("Particles_counts ")
np.savetxt(result_file, particle... |
#!/bin/py | thon
import suds
from suds.client import Client
u = 'http://owsx:owsx_user@localhost:8080/orawsv/OWSX/OWSX_UTL/PAY_RAISE'
h = {'User-Agent':'Mozilla/4.0'}
client | = Client(u)
print(client)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-08-06 14:35
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.del | etion
class Migration(migrations.Migration):
dependencies = [
('players', '0006_statistics'),
]
operations = [
migrations.AlterField(
model_name='statistics',
name='player',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, relate... | to='players.Player'),
),
]
|
import curses
from pygments import token
class ColorProfile:
def __init__( | self):
self._map = {
token.Text : 4,
token.Keyword : 3,
token.Comment : 2,
token.Number : 5,
token.Name : 6,
token.Error : 7,
token.Punctuation : 8,
token.Whitespace : 0
}
def color_for(self, attr):
| #this should return a curses color_pair depending
#on 'attr', which is a Pygments token type
if not attr in self._map:
return 1
else:
return self._map[attr] |
"""
Definition of models.
"""
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
# python manage.py makemigrations app
progress = models.IntegerField(default=0)
progress_v1 = models.Integer | Field(default=0)
progress_v2 = models.IntegerField(default=0)
progress_v3 = models.IntegerField(default=0)
progress_g1 = models.IntegerField(default=0)
progress_g2 = models.IntegerField(default=0)
progress_g3 = models.IntegerField(default=0)
progress_v1.contribute_to_class(User, ' | progress_v1')
progress_v2.contribute_to_class(User, 'progress_v2')
progress_v3.contribute_to_class(User, 'progress_v3')
progress_g1.contribute_to_class(User, 'progress_g1')
progress_g2.contribute_to_class(User, 'progress_g2')
progress_g3.contribute_to_class(User, 'progress_g3')
progress.contribute_to_class(User, 'pro... |
import pandas as pd
import numpy as np
import warnings
from clint.textui import colored
warnings.simplefilter("ignore")
class Sweetcat:
"""Load SWEET-Cat database"""
def __init__(self):
# self.fname_sc = 'WEBSITE_online_EU-NASA_full_database.rdb'
self.fname_sc = 'WEBSITE_online_EU-NASA_full_d... | 'dec'], keep=False)][['name',
'hd',
'ra',
'dec']])
print(colored.green('\nSame HD number'))
print(sc.SC[sc.SC.duplicated(['hd... | 'ra',
'dec']])
print(colored.green('\nApproximate RA/DEC ...'))
# Remove the characters after the . in the coordinates
ra_sc = sc.SC['ra'].values.tolist()
ra_approx = list(map(lambda i: i[... |
from .logic import LogicAdapter
class NoKnowledgeAdapter(LogicAdapter):
"""
This is a system adapter that is automatically added
to the list of logic adapters durring initialization.
This adapter is placed at the beginning of the list
to be given the highest | priority.
"""
def process(self, statement):
"""
If there are no known responses in the database,
then a confidence of 1 should be returned with
the input statement.
Other | wise, a confidence of 0 should be returned.
"""
if self.context.storage.count():
return 0, statement
return 1, statement
|
# Copyright 2008-2010 by Peter Cock. All rights reserved.
#
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Bio.AlignIO support for the "nexus" file format.
You are expected to use this module... | ndle = StringIO("""#NEXUS
[TITLE: NoName]
begin data;
dimensions ntax=4 nchar=50;
format interleave | datatype=protein gap=- symbols="FSTNKEYVQMCLAWPHDRIG";
matrix
CYS1_DICDI -----MKVIL LFVLAVFTVF VSS------- --------RG IPPEEQ----
ALEU_HORVU MAHARVLLLA LAVLATAAVA VASSSSFADS NPIRPVTDRA ASTLESAVLG
CATH_HUMAN ------MWAT LPLLCAGAWL LGV------- -PVCGAAELS VNSLEK----
CYS1_DIC... |
from django.apps import apps
from django.conf import settings
from django.core import checks
from django.db import connections as django_connections, DEFAULT_DB_ALIAS, router
from corehq.sql_db.exceptions import PartitionValidationError
@checks.register('settings')
def custom_db_checks(app_configs, **kwargs):
er... | e.__class__.__module__, e.__class__.__name__,
e
)))
for model in apps.get_models():
app_label = model._meta.app_label
enabled_envs = env_specific_apps.get(app_label)
if enabled_envs and settings.SERVER_ENVIRONMENT not in enabled_envs:
continue
... | ntinue
if issubclass(model, PartitionedModel):
for db in get_db_aliases_for_partitioned_query():
_check_model(model, using=db)
else:
_check_model(model)
return errors
|
# snapy - a python snmp library
#
# Copyright (C) 2009 ITA Software, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 2 as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be ... | now = time.localtime()
now = "%d-%d-%d,%d" % (now[0], now[1], now[2], now[3])
result = self.session.sget([OID(".1.3.6.1.2.1.25.1.2.0")])
self.assert_(result)
value = result[0][1].split(':', 1)[0]
| self.assertEquals(value, now)
return self.finishGet()
class TestSessionV2cBulk(TestSessionV2c):
bulk = True
class TestTimeoutsV1(unittest.TestCase):
version = "1"
def setUp(self):
self.session = Session(
version=self.version,
community="public",
... |
f | rom __future__ import unicode_literals
import sys
sys.path = sys.path[1:]
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, render_to_response
from django.core.mail import send_mail
from django.conf import settings
import os
def blog(request):
context = {}
c | ontext['thanks'] = True
return render(request, "blog/blog.html", context)
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Raspberry.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that th... | except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_li... | sys.argv)
|
from . import account_journal
from . impor | t barcode_rule
from . import pos_config
from . import pos_order
from . import product_category
from . import pr | oduct_template
|
import numpy as np
from moha.system.basis import SlaterDeterminant
| class state(object):
def __init__(self):
pa | ss
class WaveFunction(state):
def __init__(self):
pass
class HFWaveFunction(WaveFunction):
"""
"""
def __init__(self,dim,occ,coefficient,density,fock,eorbitals,Eelec,Etot):
self.dim = dim
self.occ = occ
self.coefficient = coefficient
self.density = density
... |
from setuptools import setup
'''
The packages subprocess and tkinter is also required from the standard library
''' |
setup(
name='PLOD',
version='1.0',
description='Matplotlib plot designer',
author='David Kleiven',
licence='MIT',
author_ema | il='davidkleiven446@gmail.com',
install_requires=['numpy', 'matplotlib'],
url='https://github.com/davidkleiven/PLOD',
classifiers=[
'Programming Language :: Python :: 3',
],
#py_modules=['plotHandler', 'controlGUI'],
packages=['PLOD']
)
|
import deck
class Hand:
def __init__(self):
self.cards = []
de | f add(self, card):
self.cards.app | end(card)
def size(self):
return len(self.cards)
def score(self):
# sperate cards into aces and others
regular_cards = [c for c in self.cards if c.value != "A"]
aces = [c for c in self.cards if c.value == "A"]
#tally up regular card values
points = 0
fo... |
ogle.oauth2 import service_account # type: ignore
from google.cloud.dialogflowcx_v3.types import flow
from google.cloud.dialogflowcx_v3.types import flow as gcdc_flow
from google.longrunning import operations_pb2 # type: ignore
from google.protobuf import empty_pb2 # type: ignore
try:
DEFAULT_CLIENT_INFO = gap... | s = scopes
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials and credentials_file:
raise core_exceptions.DuplicateCredentialArgs(
"'credentials_file' and 'credentials' are mutually exclusive"
)
if credent... | , **scopes_kwargs, quota_project_id=quota_project_id
)
elif credentials is None:
credentials, _ = google.auth.default(
**scopes_kwargs, quota_project_id=quota_project_id
)
# If the credentials are service account credentials, then always try to use se... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import zmq
from zmq.eventloop import ioloop as ioloop_mod
import zmqdecorators
import time
SERVICE_NAME = "urpobot.motor"
SERVICE_PORT = 7575
SIGNALS_PORT = 7576
# How long to wait for new commands before stopping automatically
COMMAND_GRACE_TIME = 0.250
class motorserv... | eck for CRLF
self.input_buffer += data
# Trim prefix NULLs and linebreaks
self.input_buffer = self.input_buffer.lstrip(chr(0x0) + "\r\n")
#print "input_buffer=%s" % repr(self.input_buffer)
if ( len(self.input_buffer) > 1
and self.input_buffer[-2:] == "\r\n"):
... | fer
self.message_received(self.input_buffer[:-2])
self.input_buffer = ""
def message_received(self, message):
#print("DEBUG: msg=%s" % message)
try:
# Currently we have no incoming messages from this board
pass
except Exception as e:
... |
# Include the Dropbox SDK
import dropbox
class DropBoxSDK():
# Get your app key and secret from the Dropbox developer website
app_key = ''
app_secret = ''
def authorize(self):
flow = dropbox.client.DropboxOAuth2FlowNoRedirect(self.app_key, self.app_secret)
authorize_url = flow.start()
# Have the ... | t.DropboxClient(self.access_token)
#print 'linked | account: ', client.account_info()
return client
|
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
import os.path
import subprocess
import sys
libpg_query = os.path.join('.', 'libpg_query')
class PSqlParseBuildExt(build_ext):
def run(self):
return_code = subprocess.call(['make', '-C', libpg_query, 'build'])
... | query],
library_dirs=[libpg_query])
]
if USE_CYTHON:
from Cython.Build import cythonize
extensions = cythonize(extensions)
setup(name='psqlparse',
version='1.0-rc7',
url='https://github.com/alculquicondor/psqlparse',
author='Aldo Culquicondor',
author_email='aldo@amigoclo... | SQL queries using the PostgreSQL query parser',
install_requires=['six'],
license='BSD',
cmdclass={'build_ext': PSqlParseBuildExt},
packages=['psqlparse', 'psqlparse.nodes'],
ext_modules=extensions)
|
import sys
import gc
import pygame
from pygame.locals import *
from input import *
import snd
TICKS_PER_SECOND = 25
GAMETICKS = 1000 / TICKS_PER_SECOND
def set_game_speed( slowdown ):
global TICKS_PER_SECOND
global GAMETICKS
TICKS_PER_SECOND = int( 25 * slowdown )
GAMETICKS = 100... | ygame.display.set_caption( self.name )
# Init the input
pygame.mouse.set_ | visible( False )
pygame.event.set_grab( False )
snd.init()
def deinit_pygame( self ):
snd.deinit()
pygame.quit()
def before_gameloop( self ):
pass
def after_gameloop( self ):
pass
def run( self ):
try:
self.init_py... |
#!/usr/bin/env python
import errno
import os
import re
import sys
from configparser import ConfigParser
import jinja2
from errbot.version import VERSION
def new_plugin_wizard(directory=None):
"""
Start the wizard to create a new plugin in the current working directory.
"""
if directory is None:
... | [a-zA-Z][a-zA-Z0-9 _-]*$",
).strip()
module_name = name.lower().replace(" ", "_")
directory_name = name.lower().replace(" ", "-")
class_name = "".join([s.capitalize() for s in name.lo | wer().split(" ")])
description = ask(
"What may I use as a short (one-line) description of your plugin?"
)
python_version = "3"
errbot_min_version = ask(
f"Which minimum version of errbot will your plugin work with? "
f"Leave blank to support any version or input CURRENT to sele... |
#! /usr/bin/env python
import logging, logtool
from .page import Page
from .xlate_frame import XlateFrame
LOG = logging.getLogger (__name__)
class Contents:
@logtool.log_call
def __init__ (self, canvas, objects):
self.canvas = canvas
self.objects = objects
@logtool.log_call
def render (self):
w... | rds = pg.next (obj.asset)
with XlateFrame (self.canvas, obj.tile_t | ype, *coords,
inset_by = "margin"):
# print ("Obj: ", obj.asset)
obj.render ()
|
from PyQt5 import QtWidgets, uic, QtCore
import sys
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
# Load the UI Page. uic is the thing that lets us use a .ui file
# This only works if the .ui file is in the same directory
super(MainWindow, self).__in... | s something.
self.state_connected = False
self.state_igniter = False
self.state_MEV = False
self.state_N2OV = False
self.state_N2O = False
self.state_N2 = False
self.state_NCV = False
self.state_RV = False
self.state_VV = False |
self.state_abort = False
self.state_run = False
def setup_buttons_etc(self):
# Alright so basically since there is not a "loop" to put methods in that
# you want to update based on things that have changed in the GUI,
# PyQt has these things called signals and slot... |
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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) an... | )
# Note: only want to represent the encrypted data
def represent_vault_encrypted_unicode(self, data):
return self.represent_scalar(u'!vault', data._ciphertext.decode(), style='|')
if PY3:
represent_unicode = yaml.representer.SafeRepresenter. | represent_str
else:
represent_unicode = yaml.representer.SafeRepresenter.represent_unicode
AnsibleDumper.add_representer(
AnsibleUnicode,
represent_unicode,
)
AnsibleDumper.add_representer(
AnsibleUnsafeText,
represent_unicode,
)
AnsibleDumper.add_representer(
HostVars,
represent_hostvars... |
#
# This file is part of Invenio.
# Copyright (C) 2016, 2017 CERN.
#
# Invenio 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.
#
# Inve... | e 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization | or submit itself to any jurisdiction.
"""Create access branch."""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '67ba0de65fbb'
down_revision = None
branch_labels = (u'invenio_access', )
depends_on = 'dbdbc1b19cf2'
def upgrade():
"""Upgrade database."""
def... |
imp | ort angr
######################################
# socket
######################################
class socket(angr.SimProcedure):
#pylint:disable=arguments-differ
def run(self, domain, typ, protocol):
conc_domain = self.state.solver.eval(domain)
conc_typ = self.state.solver.eval(typ)
c... | ')
nonce = self.state.globals.get('socket_counter', 0) + 1
self.state.globals['socket_counter'] = nonce
fd = self.state.posix.open_socket(('socket', conc_domain, conc_typ, conc_protocol, nonce))
return fd
|
sfh_tests
import ResolvedStellarPops as rsp
from TPAGBparams import snap_src
import galaxy_tests
def ms_color_cut():
comp90 = sfh_tests.read_completeness_table(absmag=True)
tri_dir = os.environ['TRILEGAL_ROOT']
# make these simulations by editing a constant sf trilegal file
# using tab_sfr/ as a sourc... | s out:
for i, target in enumerate(comp90['target']):
dline = {'target': target}
for band in ['opt', 'ir']:
if band == 'opt':
filter1 = sfh_tests.get_filter1(target.lower())
filter2 = 'F814W'
else:
... | filter2 = 'F160W'
m2m = {'target': target, 'filter2': filter2, 'filter1': filter1}
compf1 = comp90[i]['%s_filter1' % band]
dline['%s_filter1' % band] = rsp.astronomy_utils.mag2Mag(compf1, filter1, photsys, **m2m)
... |
(2, 3): 23.240228721514185,
(2, 1): -23.9264368052234,
(2, 4): 0.63465512968445115,
(4, 2): -4.5501817884252063,
(1, 0): 20.307078207040306,
(0, 3): np.nan,
(4, 0): -14.421880216023439,
... | _speeds().tolist()
real_speeds = [np.nan,
np.nan,
np.nan,
np.nan,
np.nan,
| 857.99153458573994,
1596.9530747771976,
873.15267834726137,
1282.3088174598233,
408.98588960526808,
378.40023709328955,
1809.9895146014187,
917.93227668556324,
... |
um=chunk.nansum, numel=nannumel),
partial(moment_agg, sum=np.nansum, ddof=ddof), axis=axis,
keepdims=keepdims, dtype=dt, split_every=split_every,
combine=partial(moment_combine, sum=np.nansum))
with ignoring(AttributeError):
nanvar = wraps(chunk.nanvar... | ult = np.empty(shape=vals.shape, dtype=[('vals', vals.dtype),
('arg', arg.dtype)])
result['vals'] = vals
result['arg'] = arg
return result
def arg_agg(func, argfunc, data, axis=None, **kwargs):
return _arg_combine(data, axi | s, argfunc, keepdims=False)[0]
def nanarg_agg(func, argfunc, data, axis=None, **kwargs):
arg, vals = _arg_combine(data, axis, argfunc, keepdims=False)
if np.any(np.isnan(vals)):
raise ValueError("All NaN slice encountered")
return arg
def arg_reduction(x, chunk, combine, agg, axis=None, split_ev... |
# Generated from STIXPattern.g4 by ANTLR 4.9.2
from antlr4 import *
if __name__ is not None and "." in __name__:
from .STIXPatternParser import STIXPatternParser
else:
from STIXPatternParser import STIXPatternParser
# This class defines a complete generic visitor for a parse tree produced by STIXPatternParser.... | se tree produced by STIXPatternParser#objectPath.
def visitObjectPath(self, ctx:STIXPatternParser.ObjectPathContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by STIXPatternParser#objectType.
def visitObjectType(self, ctx:STIXPatternParser.ObjectTypeContext):
return sel... | return self.visitChildren(ctx)
# Visit a parse tree produced by STIXPatternParser#indexPathStep.
def visitIndexPathStep(self, ctx:STIXPatternParser.IndexPathStepContext):
return self.visitChildren(ctx)
# Visit a parse tree produced by STIXPatternParser#pathStep.
def visitPathStep(self, ctx... |
def Woody():
| # complete
print "Reach for the sky but don't burn your wings!"# this will make it much easier in future problems to see that something is actually happe | ning |
time
import sys
from decimal import Decimal
from HTMLParser import HTMLParseError
from time import strptime
import mylar
def GCDScraper(ComicName, ComicYear, Total, ComicID, quickmatch=None):
NOWyr = datetime.date.today().year
if datetime.date.today().month == 12:
NOWyr = NOWyr + 1
logger.fdebu... | oup (response)
cnt1 = len(soup.findAll("tr", {"class": "listing_even"}))
cnt2 = len(soup.findAll("tr", {"class": "listing_odd"}))
| cnt = int(cnt1 + cnt2)
#print (str(cnt) + " results")
resultName = []
resultID = []
resultYear = []
resultIssues = []
resultURL = None
n_odd = -1
n_even = -1
n = 0
while (n < cnt):
if n%2==0:
n_even+=1
resultp = soup.findAll("tr", {"class": "list... |
ssion
from flexget.logger import console
log = logging.getLogger('web_server')
_home = None
_app_register = {}
_default_app = Flask(__name__)
random = random.SystemRandom()
web_config_schema = {
'oneOf': [
{'type': 'boolean'},
{
'type': 'object',
'properties': {
... | on.add(web_secret)
session.commit()
return web_secret.value
class User(Base, UserMixin):
""" User class available for flask apps to handle authentication using flask_login """
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
| name = Column(Unicode(50), unique=True)
token = Column(Unicode, default=generate_key)
password = Column(Unicode)
def __repr__(self):
return '<User %r>' % self.name
def get_id(self):
return self.name
class WebSecret(Base):
""" Store flask secret in the database """
__tablename... |
s) to contain current inquiries to
self._restriction = None
self._also_restriction = None
self._subset = None
if isinstance(host_list, basestring):
if "," in host_list:
host_list = host_list.split(",")
host_list = [ h for h in host_list if h a... | parts of it correspond to start/stop offsets. limits is
a tuple of (start, stop) or None
"""
if not "[" in pattern or pattern.startswith('~'):
return (pattern, None) |
(first, rest) = pattern.split("[")
rest = rest.replace("]","")
try:
# support selectors like webservers[0]
x = int(rest)
return (first, (x,x))
except:
pass
if "-" in rest:
(left, right) = rest.split("-",1)
... |
import re, requests, csv, time, traceback
from bs4 import BeautifulSoup
teams = []
for group in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']:
try:
url = "http://www.oddschecker.com/football/champions-league/champions-league-group-%s/to-qualify" % group
print "getting {}".format(url)
soup = Beau... | decimal"}).text)
table = soup.find(attrs={"class":"eventTable"})
sitesrow = table.find_all("tr", {"class": "eventTableHeader"})
sitelinks = sitesrow[0].find_all(lambda t: t.has_attr("title"))
sites = [t["title"] for t in sitelinks]
teamrows = table.find_al | l(attrs={"class": "eventTableRow"})
for row in teamrows:
cols = [t.text for t in row.find_all("td")]
name = cols[1]
if 'any other' in name.lower(): continue
odds = []
isanodd = lambda t: (t.name=="td" and t.has_attr("class") and
... |
_autoconfig=None):
return client(request).node_group_templates.create(
name=name,
plugin_name=plugin_name,
hadoop_version=hadoop_version,
flavor_id=flavor_id,
description=description,
volumes_per_node=volumes_per_node,
volumes_size=volumes_size,
node_p... | ra=extr | a)
def job_binary_list(request, search_opts=None):
return client(request).job_binaries.list(search_opts=search_opts)
def job_binary_get(request, jb_id):
return client(request).job_binaries.get(job_binary_id=jb_id)
def job_binary_delete(request, jb_id):
client(request).job_binaries.delete(job_binary_id... |
from bson.objectid import ObjectId
import json
class Room():
def __init__(self, players_num, objectid, table, current_color='purple'):
if players_num:
self.players_num = players_num
else:
self.players_num = 0
for el in ['p', 'b', 'g', 'r']:
if ... | olor changing')
colors = self.colors
self.current_color = colors[
(colors.index(self.current_color) + 1) % self.players_num]
i = 1
while ((not self.players_dict[self.color_player_dict[self.current_color]]) or (not self.can_move(table))) and (i < | = 5):
self.current_color = colors[
(colors.index(self.current_color) + 1) % self.players_num]
i += 1
if not self.can_move(table):
return None
return self.current_color
class RoomsManager():
def __init__(self, db):
# dict of rooms by th... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# anchor extraction from html document
from bs4 import BeautifulSoup
import urllib2
import urlparse
import re
import csv
import time
cityId='712'
webpage = urllib2.urlopen('http://domofoto.ru/list.php?cid='+cityId)
soup = BeautifulSoup(webpage)
maxST=0
for eleme... | a'):
url=element.get('href', '/')
| if url.find('house')>0: #TODO rename
#print url
houseId=url[7:-1]
#print houseId
housesIds.append(houseId)
#print housesIds
webpage=0
from time import gmtime, strftime
csvFileName='domofoto_'+strftime("%Y-%m-%d-%H-%M-%S", gmtime())
writer = csv.writer(open(csvFileName+'.csv', 'w'))
writer.writerow(['x... |
from xmlrpclib import Fault
from yaml import dump
from twisted.internet.defer import succeed, inlineCallbacks
from juju.errors import ProviderError
from juju.lib.testing import TestCase
from juju.providers.orchestra.machine import OrchestraMachine
from juju.providers.orchestra.tests.common import OrchestraTestMixin
... | eeper-instances": ["winston-uid"]})
self.mock_fs_put("http://somewhe.re/webdav/provider-state", data)
def mock_surprise_shutdown(self):
self.proxy_m.callRemote("get_systems")
self.mocker.result(succeed([{ |
"uid": "winston-uid",
"ks_meta": {
"MACHINE_ID": "blah",
"USER_DATA_BASE64": "userdata",
"KEEP": "keep"},
"mgmt_classes": ["acquired", "PRESERVE"]}]))
self.proxy_m.callRemote("find_system", {"uid": "winston-uid"})
self.... |
# -*- coding: utf-8 -*-
# HORTON: Helpful Open-source Research TOol for N-fermion systems.
# Copyright (C) 2011-2015 The HORTON Development Team
#
# This file is part of HORTON.
#
# HORTON is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by th... | assert abs(mol.exp_alpha.energies - [0.102709, 0.606458, 0.606458, 0.606458]).max() < 1e-4
assert abs(mol.energy - -15.464982778766) < 1e-10
assert (mol.obasis.shel | l_types == [0, 0, 1, 1, -2]).all()
olp = mol.obasis.compute_overlap(mol.lf)
ca = mol.exp_alpha.coeffs
assert abs(np.dot(ca.T, np.dot(olp._array, ca)) - np.identity(4)).max() < 1e-5
|
#!/usr/bin/python
from cm_api.api_client import ApiResource
import time
api = ApiResource(sys.argv[1], 7180, "acm", "SCALE42secretly", version=15)
cluster = None
try:
cluster = api.get_cluster(name = "ACM Cluster")
except Exception, e:
if e.message[-10:-1].lower() == "not found":
print "<ACM CLUSTER> NOT FOUND !... | ot proceeding any further..."
exit()
#Find available parcels...
available_parcels = cluster.get_all_parcels()
CDH_TARGET = None
for p in available_parcels:
if p.product.lower() == "cdh" and p.version[:1] == "5":
CDH_TARGET = { "name" : p.product, "version" : p.version }
break... | CDH_TARGET is not None:
parcel = cluster.get_parcel(CDH_TARGET['name'] , CDH_TARGET['version'])
if parcel.stage == "ACTIVATED":
print "Parcel <{0}-v{1}> is already <ACTIVATED> across the entire cluster !".format(CDH_TARGET['name'] , CDH_TARGET['version'])
elif parcel.stage == "DISTRIBUTED":
try:
print "Activa... |
と経度の設定は、以下の地図をクリックすることでも可能です:',
'You can click on the map to select the Lat/Lon fields. Longitude is West - East (sideways). Latitude is North-South (Up-Down). Latitude is zero on the equator and positive in the northern hemisphere and negative in the southern hemisphere. Longitude is zero on the prime meridian (Green... | ny site to receive a shipment.': '物資の輸送を受け取る権限がありません',
'You do not have permission for any site to send a shipment.': '物資の輸送をする権限がありません',
'You do not have permission to send a shipment from this site.': 'あなたはこのサイトから物資を送る権限はありません',
'You have a personal map configuration. To change your personal configuration, click '... | しましたか?',
'You must be logged in to register volunteers.': 'ボランティアとして登録するには、ログインする必要があります',
'You must be logged in to report persons missing or found.': '行方不明者の発見状況を登録するには、ログインする必要があります。',
'You must provide a series id to proceed.': '処理を行うにはシリーズIDを指定する必要があります。',
'You should edit OpenStreetMap settings in models/000_... |
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2018 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed ... | lic
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import unicode_literals
import argparse
import dnf.conf
import dnf.conf.read
import dnf.exceptions
from dnf.conf import Option, BaseConfig, Conf, RepoConf
import tests.support
from tests.support import ... | acheTest(tests.support.TestCase):
@mock.patch('dnf.util.am_i_root', return_value=True)
@mock.patch('dnf.const.SYSTEM_CACHEDIR', '/var/lib/spinning')
def test_root(self, unused_am_i_root):
conf = dnf.conf.Conf()
self.assertEqual(conf.system_cachedir, '/var/lib/spinning')
self.assertE... |
# -*- coding: utf-8 -*-
# Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
#
# This file is part of FIWARE project.
#
# 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://w... | _.debug("Init Keystone Client")
self.keystone_client = KeystoneClient(username=username, password=password, tenant_id=tenant_id,
auth_url=auth_url)
def _get_auth_token(self):
"""
Get token from Keystone
:return: Token (String)
""... | etting auth Token")
return self.keystone_client.auth_ref['token']['id']
def get_tenant_id_resource_client(self):
"""
Create an API resource REST client
:return: Rest client for 'TenantId' API resource
"""
__logger__.info("Creating TenantIdResource")
return ... |
#!/usr/bin/env python
#import logging
from webserver im | port *
if __name__ == '__main__':
#logging.basicConfig(
# format="[%(asctime)s] %(name)s/%(levelname)-6s - %(message)s",
# level=logging.CRITICAL,
# datefmt='%Y-%m-%d %H:%M:%S'
#)
# Only enable debug level for bbot
#logger = logging.getLogger('bastardbot')
#logger.setLevel(log... | stardBot server stopped.")
|
# -*- coding: utf-8 -*-
import logging
# define here the methods needed to be run at install time
def importVarious(context):
if context.readDataFile(' | sc.blueprints.soundcloud_various.txt') is None:
return
| logger = logging.getLogger('sc.blueprints.soundcloud')
# add here your custom methods that need to be run when
# sc.blueprints.soundcloud is installed
|
import os, sys
import json
import copy
import numpy as np
import random
from multiprocessing import Pool
import ipdb
################################################################################################
utils_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'nlp scripts')
source_vh_dir = '/ho... | ##################################################################
################################################################################################
if __name__=='__main__':
vh_dict = LabelDict()
file_dict = LabelDict()
graph = np.zeros([30,30])
vhsByFile = [set() for i in range(30)]
freq_major = n... | ='ing':
# continue
p = f.find('_mineria')
#p = f.find('_mantto_mineria')
file_name = f[3:p] # vh_name_mineria
#file_name = f[14:] # mantto_min_vh_name
id_file = file_dict.add(file_name)
for line in open(os.path.join(source_vh_dir,f)):
line = line.strip('\n')
if line!='':
id_v... |
pers. 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 law or agreed to in writing, so... | ls1 = (shls[0] + mol.nbas, shls[1])
ref = (mol1.intor_by_shell('ECPscalar_cart', shls1) -
mol2.intor_by_shell('ECPscalar_cart', shls1)) / 0.0002 * lib.param.BOHR
| dat = mol.intor_by_shell('ECPscalar_ipnuc_cart', shls, comp=3)
self.assertAlmostEqual(abs(-dat[2]-ref).max(), 0, 4)
def test_ecp_iprinv(self):
mol = gto.M(atom='''
Cu 0. 0. 0.
H 1. 0. 0.
''',
basis={'Cu':'lanl2dz', 'H':'ccpvdz'},
... |
import numpy as np
from numpy.testing import (assert_equal, assert_array_almost_equal,
assert_raises)
from skimage.transform._geometric import _stackcopy
from skimage.transform._geometric import GeometricTransform
from skimage.transform import (estimate_transform, matrix_transform,
... | [6.7905, -6.3765],
[-6.1695, -0.8235],
])
DST = np.array([
[0, 0],
[0, 5800],
[4900, 5800],
[4900, 0],
[4479, 4580],
[1176, 3660],
[3754, 790],
| [1024, 1931],
])
def test_stackcopy():
layers = 4
x = np.empty((3, 3, layers))
y = np.eye(3, 3)
_stackcopy(x, y)
for i in range(layers):
assert_array_almost_equal(x[..., i], y)
def test_estimate_transform():
for tform in ('similarity', 'affine', 'projective', 'polynomial'):
... |
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.proc | ess_artificial | _dataset as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 12, transform = "BoxCox", sigma = 0.0, exog_count = 20, ar_order = 12); |
"""
Given an array of integers, find out whether there are two distinct indices i
and j in the array such that the difference between nums[i] and nums[j] is at
most t and the difference between i and j is at most k.
"""
class Solution(object):
def containsNearbyAlmostDuplicate(self, nums, k, t):
"""
... | """
if nums is None or nums == []:
return False
if k < 1 or t < 0:
return False
buckets = collections.defaultdict(int)
| length = len(nums)
width = t + 1
for i in range(length):
key = nums[i] // width
if key in buckets:
return True
if key - 1 in buckets and abs(nums[i] - buckets[key - 1]) < width:
return True
if key + 1 in buckets and abs(nu... |
import os
import numpy
from numpy import *
import math
from scipy import | integrate, linalg
from matplotlib import pyplot
from pylab import *
class Freestream:
"""
Freestream conditions.
"""
def __init__(self, u_inf=1.0, alpha=0.0):
"""
Sets the freestream speed and angle (in degrees).
Parameters
----------
u_inf: float, opti... | alpha: float, optional
Angle of attack in degrees;
default 0.0.
"""
self.u_inf = u_inf
self.alpha = alpha*numpy.pi/180.0 # degrees to radians
|
from pkg_resources import parse_version
from pyramid.interfaces import (
PHASE1_CONFIG,
PHASE2_CONFIG,
)
import venusian
def includeme(config):
config.registry['migrator'] = Migrator()
config.add_directive('add_upgrade', add_upgrade)
config.add_directive('add_upgrade_step', add_upgrade_step)
c... | step = self.upgrade_steps[parse_version('')]
except KeyError:
pass
else:
if parse_version(step.dest) >= parse_version(version):
steps.append(step)
version = step.dest
while parse_version(version) < parse_versi... | try:
step = self.upgrade_steps[parse_version(version)]
except KeyError:
break
steps.append(step)
version = step.dest
if version != target_version:
raise UpgradePathNotFound(
self.__name__, current_version, t... |
import tsp.algorithms
import time
if __name__ == "__main__":
cities_number = 5
max_distance = 100
distances_matrix = tsp.algorithms.get_random_distances_matrix(cities_number, max_distance)
start = time.time()
optimal_path = tsp.algorithms.BruteForceTSPSolver(distances_matrix).solve()
print(... | is: {0:.2f} seconds".format(time.time() - start))
start = time.time()
worst_path = tsp.algorithms.BruteForceTSPWorstPathSolver(distances_matrix).solve()
print("\nWorst path is " + str(worst_path))
print("Distance is " + str(tsp.algorithms.get_trip_distance(distances_matrix, worst_path)))
print("Com... |
start = time.time()
boltzmann_path = tsp.algorithms.BoltzmannMachineTSPSolver(distances_matrix).solve()
print("\nBoltzmann path is " + str(boltzmann_path))
print("Distance is " + str(tsp.algorithms.get_trip_distance(distances_matrix, boltzmann_path)))
print("Computational time is: {0:.2f} seconds".... |
import os
import re
from nose.tools import raises
import seqpoet
class TestSequence:
def setup(self):
self.seq1 = 'ACATacacagaATAgagaCacata'
self.illegal = 'agagcatgcacthisisnotcorrect'
def test_sequence_length(self):
s = seqpoet.Sequence(self.seq1)
assert len(s) == len(self... | g(self):
s = seqpoet.Sequence(self.seq1)
assert re.match('^[acgt]+$', str(s))
def test_reverse_complement(self):
s = seqpoet.Sequence(self.seq1)
s2 = seqpoet.Sequence('acct')
assert s.revcomp() == 'tatgtgtctctattctgtgtatgt', \
'"{0}" is not "tatgtgtctctattctgtgta... | s.revcomp().seq)
assert s2.revcomp() == 'aggt', \
'"{0}" is not "aggt"'.format(s2.revcomp().seq)
def test_str(self):
s = seqpoet.Sequence(self.seq1)
assert str(s) == self.seq1.lower()
def test_repr(self):
s = seqpoet.Sequence(self.seq1)
assert repr(s) == '<S... |
from twython import Twython, TwythonError, TwythonAuthError
from .config import app_key, app_secret, screen_name
import unittest
class TwythonAuthTestCase(unittest.TestCase):
def setUp(self):
self.api = Twython(app_key, app_secret)
self.bad_api = Twython('BAD_APP_KEY', 'BAD_APP_SECRET')
... | ')
def test_get_authorized_tokens_invalid_or_expired_tokens(self):
"""Test getting final token fails when i | nvalid or expired tokens have been passed"""
self.assertRaises(TwythonError, self.bad_api_invalid_tokens.get_authorized_tokens,
'BAD_OAUTH_VERIFIER')
def test_get_authentication_tokens_raises_error_when_oauth2(self):
"""Test when API is set for OAuth 2, get_authentication_t... |
holds a mapping of *name* to *Expectation*, where *Expectation* has
the following fields:
*name*
key name in the song dictionary (equal to the *name* keying ``md_expectations``).
*type*:
a string holding a `validictory <https://github.com/sunlightlabs/validictory>`__ type.
Possible values:
:'string'... | possible
*mutable*:
``True`` if client can change the value.
*optional*:
``True`` if the key is not guaranteed to be present.
*volatile*:
``True`` if the key's value can change between observations without client mutation.
*depends_on*:
the name of the key we transform to take our value from, or ``None``.
... | ependent_transformation*:
``None``, or a function ``lambda dependent_value: our_value``.
For example, the ``artistNorm`` field is automatically set to the lowercase
of the ``artist`` field.
So, ``artistNorm.depends_on == 'artist'``, and the *dependent_transformation* for
``artistNorm`` can be written as ``la... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.