prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
lgorithms.graph.graph import wgraph_from_3d_grid
from ..algorithms.statistics import empirical_pvalue
from .glm import glm
from .group.permutation_test import \
permutation_test_onesample, permutation_test_twosample
# FIXME: rename permutation_test_onesample class
#so that name starts with upper case
##########... | mulated_pvalue(c['size'], nulls['s'])
c['cluster_pvalue'] = p
# General info
info = {'nvoxels': nvoxels,
'threshold_z': zth,
'threshold_p': pth,
'threshold_pcorr': bonfer | roni(pth, nvoxels)}
return clusters, info
###############################################################################
# Peak_extraction
###############################################################################
def get_3d_peaks(image, mask=None, threshold=0., nn=18, order_th=0):
"""
returns all... |
import ConfigParser as configparser
import os
import sys
from pyspark import SparkContext, SparkConf, SparkFiles
from pyspark.sql import SQLContext, Row
from datetime import datetime
from os_utils imp | ort make_directory, preparing_path, time_execution_log, check_file_exists |
from subprocess import Popen, PIPE
from vina_utils import get_files_pdb, get_name_model_pdb
if __name__ == '__main__':
sc = SparkContext()
sqlCtx = SQLContext(sc)
config = configparser.ConfigParser()
config.read('config.ini')
pythonsh = config.get('VINA', 'pythonsh')
script_receptor4 = con... |
if hedge_mid_amount < self.min_amount_mid:
"""bitfinex限制btc_krw最小可交易amount为0.005, liqui限制单次交易btc的amount为0.0001, 所以这里取0.005"""
logging.debug("forward======>hedge_mid_amount is too small! %s" % hedge_mid_amount)
return
else:
"""余额限制base最多能买多少... | rward======>t_price: %s, t_price_percent: %s, profit: %s" % (t_price, t_price_percent, profit))
if profit > 0:
if t_price_percent < self.trigger_percent:
logging.debug("forward======>profit percent should >= %s" % self.trigger_percent)
return
self.count_fo... | forward, self.count_reverse))
logging.debug(
"forward======>find profit!!!: profit:%s, quote amount: %s and mid amount: %s, t_price: %s" %
(profit, hedge_quote_amount, hedge_mid_amount, t_price))
current_time = time.time()
if current_time - self.las... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
destination.factory
'''
from destination.zeus import ZeusDestination
from destination.aws import AwsDestination
from exceptions import AutocertError
from config import CFG
from app import app
class DestinationFactoryError(AutocertError):
def __init__(self, destin... | destination}'
super(DestinationFactoryError, self).__init__(msg)
def create_destination(destination, ar, cfg, timeout, verbosity):
d = None
if destination == 'aws':
d = AwsDestination(ar, cfg, verbosity)
elif destination == 'zeus':
d = ZeusDestination(ar, cfg, verbosity)
else:
... | s = list(CFG.destinations.zeus.keys())
if d.has_connectivity(timeout, dests):
return d
|
# -*- coding: utf8 -*-
from django.db import models
from django.db.models import F
class Revision(models.Model):
"""
A blank model (except for ``id``) that is merely an implementation detail
of django-revisionfield.
"""
number = models.PositiveIntegerField()
@staticmethod
def next():
... | e next revision.
:returns: next available revision
:rtype: ``int``
"""
try:
current = Revision.objects.get().number
except Revision.DoesNo | tExist:
revision, created = Revision.objects.get_or_create(number=1)
current = revision.number
while Revision.objects.filter(number=current).update(number=F('number') + 1) != 1:
current = Revision.objects.get().number
return current + 1
|
iles. See SchemaValidationTestCasesV1
for an example of how this was done for schema version 1.
Because decorators can only access class properties of the class they are
defined in (even when overriding values in the subclass), the decorators
need to be placed in the subclass. This is why there are tes... | elf, config):
self.run_test_validation_success(config)
def test_schema_version_matching(self):
self.run_schema_version_matching(self.MIN_SCHEMA_VERSION,
self.MAX_SCHEMA_VERSION) |
@ddt.ddt
class ValidateProviderConfigTestCases(base.BaseTestCase):
@ddt.unpack
@ddt.file_data('provider_config_data/validate_provider_good_config.yaml')
def test__validate_provider_good_config(self, sample):
provider_config._validate_provider_config(sample, "fake_path")
@ddt.unpack
@ddt.... |
##############################################################################
# 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... | tions 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, I | nc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
import re
import pytest
from spack.url import UndetectableVersionError
from spack.main import SpackCommand
from spack.cmd.url import name_parsed_correctly, version_parsed_correctly
f... |
from __future__ import print_function, division, unicode_literals
import operator
from pymatgen.core.periodic_table import Element
from pymatgen.core.structure import Structure
from mpinterfaces.mat2d.intercalation.analysis import get_interstitial_sites
__author__ = "Michael Ashton"
__copyright__ = "Copyright 2017... | re object to
intercalate into.
ion (str): name of atom to intercalate, e.g. 'Li', or 'Mg'.
atomic_fraction (int): This fraction of the final intercalated
structure will be intercalated atoms. Must be < 1.0.
Returns:
structure. Includes intercalated atoms.
TODO:
... | # If the structure isn't big enough to accomodate such a small
# atomic fraction, multiply it into a supercell.
n_ions = 1.
while not n_ions / (structure.num_sites+n_ions) <= atomic_fraction:
# A supercell in all 3 dimenions is not usually necessary,
# but is the most reliable for findin... |
def exec_after_process(app, inp_data, out_data, param_di | ct, tool, stdout, stderr):
for name,data in out_data.items():
if name == "seq_file2":
data.dbkey = param_dict['dbkey_2']
app.model.context.add( data )
app | .model.context.flush()
break |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
| os.environ.setdefault("DJANGO_SETTINGS_MODULE", " | craken_project.settings.local")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
elf.assertIn("IgnoreMeImInnocent@sender.com", values)
self.assertEqual(types['email-thread-index'], 1)
self.assertIn('AQHSR8Us3H3SoaY1oUy9AAwZfMF922bnA9GAgAAi9s4AAGvxAA==', values)
self.assertEqual(types['email-message-id'], 1)
self.assertIn("<4988EF2D.408... | l_malformed_header_CJK_encoding(self):
query = {"module":"email_import"}
query["config"] = {"unzip_attachments": None,
"guess_zip_attachment_passwords": None,
"extract_urls": None}
| # filenames = os.listdir("tests/test_files/encodings")
# for encoding in ['utf-8', 'utf-16', 'utf-32']:
message = get_base_email()
text = """I am a test e-mail
the password is NOT "this string".
That is all.
"""
message.attach(MIMEText(text, 'plain'))
j... |
#!/usr/bin/env python
from sys import argv
from os import system
from php_tester impor | t php_tester
if __name__ == "__main__":
assert(len(argv) > 3);
repo_src = argv[1];
repo_test = argv[2];
revision = argv[3];
if (len(argv) == 4):
out_file = "revlog" + revision + | ".txt";
revision2 = revision + "^1";
deps_dir = "php-deps";
else:
assert(len(argv) > 6);
revision2 = argv[4];
out_file = argv[5];
deps_dir = argv[6];
workdir = "__tmp" + revision;
system("mkdir " + workdir);
repo1 = workdir + "/tmp1";
repo2 = workdir ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011, 2012 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum 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 ... | hich calls this class for the Cerebrum
functionality.
This class is instantiated for each incoming call, and closed and destroyed
after each call. Note that we should explicitly shut down db connect | ions,
since the server could run many connections in parallell.
Note that this class should be independent of what server and communication
form we are using.
"""
def __init__(self):
self.db = Factory.get('Database')()
self.co = Factory.get('Constants')(self.db)
def close(sel... |
# phppo2pypo unit tests
# Author: Wil Clouser <wclouser@mozilla.com>
# Date: 2009-12-03
from io import BytesIO
from translate.convert import test_convert
from | translate.tools import phppo2pypo
class TestPhpPo2PyPo:
def test_single_po(self):
inputfile = b"""
# This user comment refers to: %1$s
#. This developer comment does too: %1$s
#: some/path.php:111
#, php-format
msgid "I have %2$s apples and %1$s oranges"
msgstr "I have %2$s apples and %1$s orange | s"
"""
outputfile = BytesIO()
phppo2pypo.convertphp2py(inputfile, outputfile)
output = outputfile.getvalue().decode("utf-8")
assert "refers to: {0}" in output
assert "does too: {0}" in output
assert 'msgid "I have {1} apples and {0} oranges"' in output
a... |
#
# acute-dbapi setup
# Ken Kuhlman (acute at redlagoon dot net), 2007
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages, Extension
import sys
import os
setup(
name="acute-dbapi",
version="0.1.0",
description="Python DB-API testsuite",
author="Ken Kuhlma... | project summary page on google code. Keep in sync.
long_description = """
Welcome to the home page for acute-dbapi, a DB-API compliance test suite. Acute is still in it's infancy, but it's reached the level of maturity that it would benefit from community input. It currently contains 71 | tests, and many more will be added soon.
Comments, suggestions, and patches are all warmly welcome. There are several TODOs listed in the [TODO] file, and many more generously sprinkled throughout the code; if you'd like to help out but don't know where to begin, feel free to take a crack at one of them!
Please read... |
ute, sub license,
# 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 above copyright notice and this permission notice (including the
# next paragraph) shall be included in all copies or substantial portions
# of the Sof... | IC:
raise ValueError('Magic value %08x not recognized (should be %08x)' % (magic, FDR_MAGIC))
if version != FDR_VERSION:
raise ValueError('Version %08x not recognized (should be %08x)' % (version, FDR_VERSION))
# Stored memory ranges
self.stored = []
# Active mem... | self.updated_ranges = []
# Temporary data
self.temp_ranges = []
# Cached list of starting addresses for bisection
self.updated_ranges_start = []
self.temp_ranges_start = []
# IMPORTANT precondition: all ranges must be non-overlapping
def _flush_temps(self):
s... |
import re,json
def isValid(number):
match=re.match(r'[456]\d{3}-?\d{4}-?\d{4}-?\d{4}$',number)
if not match: return False
else:
digits=number.replace("-","")
result=re.search(r'(\d)\ | 1\1\1',d | igits)
if result: return False
return True
records=json.load(open("greenparadise.json"))
for record in records:
valid=isValid(record["card"])
if not valid:
print("Invalid card:",record["card"])
if valid != record["valid"]:
print("Unmatched valid tag:",record["card"],valid,record[... |
#!/bin/python
from __future__ import print_function
import subprocess
import sys
import os
import json
from util import appendline, get_ip_address
if __name__ == "__main__":
path = os.path.dirname(os.path.realpath(__file__))
config = json.load(op | en(path+'/cluster-config.json'));
for node in config['nodes']:
files = subprocess.check_output(["ssh", "cloud-user@"+node['ip'], 'ls /home/cloud-user']).split('\n')
if 'StreamBench' not in files:
p = subprocess.Popen('ssh cloud-user@'+node['ip']+' "git clone https://github.com/wangyangjun/StreamBench.git"', she... | eckout .;git pull;"', shell=True)
|
import json
import copy
formtable = {"name":[u'name'],
"gender":[u'gender'],
"contact":[u'contact'],
"address":[u'address']}
def is_reserved_layer(dict,reserved_word):
for key in dict:
if len(reserved_word)<=len(key) and reserved_word == key[:len(reserved_word)]:
... | [u'name', 'parallel_dict0', u'given', 'parallel_dict0', u'Peter'])
testlist.append([u'name', 'par | allel_dict0', u'given', 'parallel_dict1', u'James'])
testlist.append([u'name', 'parallel_dict0', u'fhir_comments', 'parallel_dict0', u" Peter James Chalmers, but called 'Jim' "])
testlist.append([u'name', 'parallel_dict0', u'family', 'parallel_dict0', u'Chalmers'])
testlist.append([u'name', 'parallel_dict1'... |
# pylint: disable=g-bad-file-header
# Copyright 2015 The TensorFlow 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/LICENS... | tored in a separate
checkpoint file), and outputs a new GraphDef with the optimizations applied.
If the input graph is a text graph file, make sure to include the node that
restores the variable weights in output_names. That node is usually named
"restore_all".
An example of command-line usage is:
bazel build tensor... | && \
bazel-bin/tensorflow/python/tools/optimize_for_inference \
--input=frozen_inception_graph.pb \
--output=optimized_inception_graph.pb \
--frozen_graph=True \
--input_names=Mul \
--output_names=softmax
"""
import argparse
import os
import sys
from absl import app
from google.protobuf import text_format
from te... |
import math
from param import *
class Sample:
def __init__(self):
self.time = 0
self.home1_x = 0.0
self.home1_y = 0.0
self.home1_theta = 0.0
self.home2_x = 0.0
self.home2_y = 0.0
self.home2_theta = 0.0
self.away1_x = 0.0
self.away1_y = 0.0
... | x = pixelToMeter(data.home1_x)
home1_y | = pixelToMeter(data.home1_y)
angleField = math.atan2(home1_y, home1_x)
mag = math.sqrt(home1_x**2+home1_y**2)
angleCamera = math.atan(HEIGHT_CAMERA/mag)
offset = HEIGHT_ROBOT / math.tan(angleCamera)
home1_x = home1_x - offset * math.cos(angleField)
home1_y = home1_y - of... |
from django.contrib import admin
from .models import (
Store,
Seller
)
admin.site.register(Store)
| admin.sit | e.register(Seller)
|
# -*- coding: utf-8 -*-
"""
Created on Mon May 05 23:10:12 2014
@author: Sudeep Mandal
"""
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
def histfit(data, ax=None, **kwargs):
"""
Emulates MATLAB histfit() function. Plots histogram & Gaussian fit to data
Currently ... | = kwargs['bins'] if 'bins' in kwargs else np.sqrt(len(data))
color = kwargs['color'] if 'color' in kwargs else 'g'
if ax is None:
ax = plt.gca()
# Plot histogram
n, bins, patches = ax.hi | st(data, bins=bins, alpha=0.6, color=color)
bin_centers = (bins[:-1] + bins[1:])/2
# Define model function to be used to fit to the data above:
def gauss(x, *p):
A, mu, sigma = p
return A*np.exp(-(x-mu)**2/(2.*sigma**2))
# p0 is the initial guess for the fitting coefficients (A... |
from zope.i18nmessageid import MessageFactory
PloneMessageFactory = MessageFactory('plone')
from Products.CMFCore.permissions import setDefaultRoles
setDefaultRoles('signature.portlets.gdsignature: Add GroupDocs Signature portlet',
('Manager', 'Site Administrator', ' | Owner',))
| |
#
# Copyright (c) 2009-2015, Jack Poulson
# All rights reserved.
#
# This file is part of Elemental and is under the BSD 2-Clause License,
# which can be found in the LICENSE file in the root directory, or at
# http://opensource.org/licenses/BSD-2-Clause
#
import El, math, time
|
m = 10
cutoff = 1000
output = True
worldRank = El.mpi.WorldRank()
worldSize = El.mpi.WorldSize()
# Construct s and z in the (product) cone
# ================= | ======================
def ConstructPrimalDual(m):
s = El.DistMultiVec()
z = El.DistMultiVec()
orders = El.DistMultiVec(El.iTag)
firstInds = El.DistMultiVec(El.iTag)
sampleRad = 1./math.sqrt(1.*m)
El.Uniform( s, 3*m, 1, 0, sampleRad )
El.Uniform( z, 3*m, 1, 0, sampleRad )
s.Set( 0, 0, 2. )
s.Set( m, 0... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2013-2014, Nigel Small
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You m | ay 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, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License f... | -2014, Nigel Small"
__email__ = "nigel@nigelsmall.com"
__license__ = "Apache License, Version 2.0"
__version__ = "1.2.0"
from .http import *
|
# rock_n_roll/apps.py
from d | jango.apps import AppConfig
class BibliographyConfig(AppConfig):
name = 'bibliography'
v | erbose_name = "bibliography"
#pippio = "pippo"
|
#!/usr/bin/env python
import dateutil.parser
import dateutil.tz
import feedparser
import re
from datetime import datetime, timedelta
from joblist import JobList
class FilterException(Exception):
pass
class IndeedJobList(JobList):
'''Joblist class for Indeed
This joblist is for the indeed.com rss feed. I... | tinue
new.append(entry['id'])
entry_date = dateutil.parser.parse(entry['published'])
if oldest_cuto | ff > entry_date:
return None
entry_title = entry['title']
entry_location = 'Unspecified'
try:
entry_location = entry_title.split(' - ')[-1]
except IndexError:
pass
try:
... |
import ntpath
import mp3parser
from modifyTag import TagWrapper
from glob import glob
from os.path import join
def pathLeaf(path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)
class Runner():
def __init__(self, configs):
# We do this here to make it clear what data we need
... | 't need to reassign at the | end
mp3parser.artistList = self.artistList
finished = 0
for fileName in self.files:
finished += 1
raw = pathLeaf(fileName)[:-4]
dlg.Update(finished, "Current Song: " + raw)
with TagWrapper(fileName) as tag:
if tag.tag is None:
... |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The nealcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test running nealcoind with the -rpcbind and -rpcallowip options."""
from test_framework.test_framewo... | odes = start_nodes(self.num_nodes, self.options.tmpdir, [base_args + binds], connect_to)
pid = nealcoind_processes[0].pid
assert_equal(set(get_bind_addrs(pid)), set(expected))
stop_nodes(self.nodes)
def run_allowip_test(self, allow_ips, rpchost, rpcport):
'''
Start a node wi... | '''
base_args = ['-disablewallet', '-nolisten'] + ['-rpcallowip='+x for x in allow_ips]
self.nodes = start_nodes(self.num_nodes, self.options.tmpdir, [base_args])
# connect to node through non-loopback interface
node = get_rpc_proxy(rpc_url(0, "%s:%d" % (rpchost, rpcport)), 0)
... |
# -*- coding: UTF-8 -*-
from base import TestCase
from jinja2_maps.base import _normalize_location
class Location(object):
def __init__(self, **kw):
for k, v in kw.items():
setattr(self, k, v)
class TestBase(TestCase):
def test_normalize_location_dict(self):
d = {"latitude": 42.... | assertEquals({"latitude": 42.3, "longitude": 17.1},
_normalize_location(Location(latitude=42.3, longitude=17.1)))
self.assertEquals({"latitude": 4 | 1.3, "longitude": 16.1},
_normalize_location(Location(lat=41.3, lng=16.1)))
|
def | f2():
def f3():
print("f3")
f3()
f2( | )
|
from GenericStore import GenericStore
class ChangeOverStore(GenericStore):
"""Store used to manage Source entities.
BookingSync doc : http://developers.bookingsync.com/reference/endpoints/change_over | s/
""" |
def __init__(self,credential_manager):
super(ChangeOverStore, self).__init__(credential_manager, "change_overs")
|
import sys
class outPip(object):
def __init__(self, fileDir):
self.fileDir = fileDir
self.console = sys.stdout
def write(self, s):
self.co | nsole.write(s)
with open(self.fileDir, 'a') as f: f.write(s)
def flush(self):
self.console.flush()
new_input = input
def inPip(fileDir):
def _input(hint):
s = new_input(hint)
with open(fileDir, 'a') as f: f.write(s)
return s
r | eturn _input
sys.stdout = outPip('out.log')
input = inPip('out.log')
print('This will appear on your console and your file.')
print('So is this line.')
input('yo')
|
allocate jobs as much as possible.
Otherwise, the allocation will stop after the first fail.
"""
seed(_seed)
self._counter = 0
self.allocator = None
self._logger = logging.getLogger('accasim')
self._system_capacity = None
... | ted_resources = _job.requested_resources
| _requested_nodes = _job.requested_nodes
_fits = 0
_diff_node = 0
for _node, _attrs in self._nodes_capacity.items():
# How many time a request fits on the node
_nfits = min([_attrs[_attr] // req for _attr, req in _requested_resources.item... |
# This file is part of Shuup.
#
# Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
import datetime
import pytest
from shuup.simple_cms.models import Page
from shuup.si | mple_cms.views import PageView
from shuup.testing.factories import get_default_shop
from shuup.testing.utils import apply_request_middleware
from shuup_tests.simple_cms.utils im | port create_page
@pytest.mark.django_db
@pytest.mark.parametrize("template_name", ["page.jinja", "page_sidebar.jinja"])
def test_superuser_can_see_invisible_page(rf, template_name):
template_path = "shuup/simple_cms/" + template_name
page = create_page(template_name=template_path, available_from=datetime.date... |
# -*- coding=utf-8 -*-
#Copyright 2012 Daniel Osvaldo Mondaca Seguel
#
#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 appli... | License",
keywords = "web scraping",
url = "http://github.com/Nievous/pyscrap",
packages=["pyscrap"],
install_requires = ["lxml", "simplejson"],
long_description=read("README.txt"),
package_data = {"package": files},
classifiers=[
"Development Status :: 4 - Beta",
"Topic :: ... | |
__version__ | = '0.3.0'
| |
turn word
def lang_button_image():
return files.resource_path('', 'images\\' + lang() + '_' + switch_language(False) + '.png')
def switch_language(doSwitch=True):
global CURRENT_LANGUAGE
if CURRENT_LANGUAGE == 'ger':
if doSwitch:
CURRENT_LANGUAGE = 'eng'
return 'eng'
elif... | le Frog', 'Gscheide Frog', 'Dauerfrog',
'Schmarrnfrog', 'Oide Frogn'],
}
shortNames = {'ger': ['S', 'M', 'H', 'P', 'J', 'A'],
'eng': ['S', 'M', 'H', 'P', 'J', 'A'],
'bay': ['S', 'M', 'H', 'P', 'J', 'A'],
}
startButtonText = {'ger': ['Start', 'S... | 'eng': ['Go!', 'Close'],
'bay': ["Af geht's!", 'A Rua is!'],
}
linkLabelText = {'ger': 'AGV Webseite',
'eng': 'AGV website',
'bay': "Webseitn",
}
errorTitle = {'ger': 'Bierjunge!',
'eng': 'Error!',
... |
from __future__ import absolute_import, division, print_function, unicode_literals
import string
import urllib
try:
from urllib.parse import urlparse, urlencode, urljoin, parse_qsl, urlunparse
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urlpars... | """Return a URL with the query component removed.
:param url: URL to dequery.
:type url: str
:rtype: str
"""
url = urlparse(url)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
... | '',
url.fragment))
def build_url(base, additional_params=None):
"""Construct a URL based off of base containing all parameters in
the query portion of base plus any additional parameters.
:param base: Base URL
:type base: str
::param additional_params: ... |
#
# Copyright 2015 Free Software Foundation, Inc.
#
# This file is part of PyBOMBS
#
# PyBOMBS 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.
#
# PyB... | mplied warranty of
# MERCHANTABILITY or FITNES | S 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 PyBOMBS; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
"""
System Uti... |
"""Tables, Widgets, and Groups!
An example of tables and most of the included widgets.
"""
import pygame
from pygame.locals import *
# the following line is not needed if pgu is installed
import sys; sys.path.insert(0, "..")
from pgu import gui
# Load an alternate theme to show how it is done. You can also
# speci... |
c.tr()
c.td(gui.Label("Select"))
e = gui.Select()
e.add("Goat",'goat')
e.add("Horse",'horse')
e.add("Dog",'dog')
e.add("Pig",'pig')
c.td(e,colspan=3)
c.tr()
c.td(gui.Label("Tool"))
g = gui.Group(value='b')
c.td(gui.Tool(g,gui.Label('A'),value='a'))
c.td(gui.Tool(g,gui.Label('B'),value='b'))
c.td(gui.Tool(g,gui.Label(... | activate", cb)
c.td(w,colspan=3)
c.tr()
c.td(gui.Label("Slider"))
c.td(gui.HSlider(value=23,min=0,max=100,size=20,width=120),colspan=3)
c.tr()
c.td(gui.Label("Keysym"))
c.td(gui.Keysym(),colspan=3)
c.tr()
c.td(gui.Label("Text Area"), colspan=4, align=-1)
c.tr()
c.td(gui.TextArea(value="Cuzco the Goat", width=150, h... |
#!/usr/bin/env python
# encoding: utf-8
from django.db import models,connection
from django.contrib.auth.models import User,UserManager
class UserProfile(models.Model):
GENDER_CHOICES = (
(1, '男'),
(2, '女'),
)
PROVINCE_CHOICES = (
('JiangSu','江苏'),
('ShangHai','上海'),
('ShangHai','上海... | Field("学历", max_length=10)
indus | try = models.CharField("行业", max_length=10)
incoming = models.IntegerField("收入", choices=INCOMING_CHOICES,default=1,null=True)
smoking = models.CharField("抽烟", max_length=10, choices = DEGREE_CHOICES,default=1)
drinking = models.CharField("喝酒", max_length=10, choices = DEGREE_CHOICES,default=1)
family =... |
= np.dot(R[i],alpha_p[(6*i):(6*(i+1))])
#
# x_out_p.append(x10 - x11 + x2)
# print( "||x_out - x_out_p || = %e " % np.linalg.norm(x_out[i] - x_out_p[i]))
Ac_clust_python = np.hstack((Fc_clust,Gc_clust))
Z = np.zeros((Gc_clust.shape[1],Ac_clust_python.shape[1]))
print ( Z.shape)
Ac_c... | r)]
##PR,LR,UR = scipy.linalg.lu(AcR)
##nnzR = LR.nonzero()[0].shape[0] + UR.nonzero()[0].shape[0]
###
###
##plt.subplot(2,2,1)
##plt.spy(L,markersize=0.1);
##plt.subplot(2,2,2)
##plt.spy(U,markersize=0.1);
##plt.subplot(2,2,3)
##plt.spy(LR,markersize=0.1);
##plt.subplot(2,2,4)
##plt.spy(UR,markersize=0.1);
#
##print ... | #
##plt.show()
#
##ker_Ac = load_matrix(path0,"dump_ker_Ac_","",str(0),False,True,1)
##ker_GcTGc = load_matrix(path0,"dump_ker_GcTGc_","",str(0),False,True,1)
##R0 = load_matrix(path0,"dump_R_","",str(0),False,True,1)
#
##Gc_H = np.dot(GcTGc.toarray(),ker_GcTGc)
#
##r = sparse.csgraph.reverse_cuthill_mckee(Ac_clust.... |
ile is part of volcasample.
#
# volcasample is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# volcasample is distributed in the hope ... | or tgt, keep in zip(targets, initial)
if "path" in tgt and keep is False
])
jobs.update(OrderedDict([(
tgt["slot"],
(volcasample.syro.DataType.Sample_Compress, tgt["path"]))
for tgt, keep in zip(targets, initial)
if "path" in tgt and keep is Tr... | stop = min(100, (start + span) if span is not None else 101)
Project.progress_point(
"Creating project tree at {0}".format(path),
quiet=quiet
)
for i in range(start, stop):
os.makedirs(
os.path.join(path, "{0:02}".format(i)),
e... |
#!/usr/bin/python -S
#
# Cop | yright 2009 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Perform auto-approvals and auto-blocks on translation import queue"""
import _pythonpath
from lp.translations.scripts.import_queue_gardener import ImportQueueGardener
if __name__... | ions_import_queue_gardener')
script.lock_and_run()
|
__author__ = 'Mario'
import wx
import wx.xrc
###########################################################################
## Class MainPanel
###########################################################################
class MainPanel ( wx.Panel ):
def __init__( self, parent ):
wx.Panel.__init__ ( self, pa... | ate', pos = wx.Point(125, 110))
self.Volatility = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
txtCtrlSizer.Add( self.Volatility, 0, wx.ALL, 5 )
self.VolatilityText = wx.StaticText(self, -1, 'Input Volatility', pos = wx.Point(125, 142))
buttonS... | self.computeButton = wx.Button( self, wx.ID_ANY, u"Compute", wx.DefaultPosition, wx.DefaultSize, 0 )
buttonSizer.Add( self.computeButton, 0, wx.ALL, 5 )
self.clearButton = wx.Button( self, wx.ID_ANY, u"Clear", wx.DefaultPosition, wx.DefaultSize, 0 )
buttonSizer.Add( self.clearButton, 0, wx... |
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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/licens | es/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi | ng, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import functools
import inspect
from oslo_utils... |
# Copyright 2016 F5 | Networks 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 or agreed to in writing, software
| # distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from requests import HTTPError
TESTDESCRIPTION = "TESTDESCRIPTION"
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-12-09 21:59
from __future__ import unicode_literals
from | django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('osf', '0025_preprintprovider_social_instagram'),
]
operations = [
migrations.AddField(
model_name='preprintservice',
name='license',
... | _NULL, to='osf.NodeLicenseRecord'),
),
]
|
ride)
port_dict = self.create_port_dict(
net_id, subnet_dict.id,
mac_address=str(self._DHCP_PORT_MAC_ADDRESS),
ip_version=ip_version)
port_dict.device_id = common_utils.get_dhcp_agent_device_id(
net_id, self.conf.host)
net_dict = self.create_networ... | rk.namespace))
common_utils.wait_until | _true(predicate, 10)
ip_list = self._ip_list_for_vif(vif_name, network.namespace)
cidr = ip_list[0].get('cidr')
ip_addr = str(netaddr.IPNetwork(cidr).ip)
self.assertEqual(port.fixed_ips[0].ip_address, ip_addr)
def assert_bad_allocation_for_port(self, network, port):
vif_nam... |
70,
56,
-52,
10]
self.BossOffice_SuitPositions = [Point3(0, 15, 0),
Point3(10, 20, 0),
Point3(-10, 6, 0),
Point3(-17, 34, 11)]
self.BossOffice_SuitHs = [170,
120,
12,
38]
self.waitMusic = loader.loadMusi... | self.__addToon(toon)
else:
self.notify.warning('setToons() - no toon: %d' % toonId)
for toon in oldtoons:
if self.toons.count(toon) == 0:
self.__removeToon(toon)
def setSuits(self, suitIds, reserveIds, values):
| oldsuits = self.suits
self.suits = []
self.joiningReserves = []
for suitId in suitIds:
if suitId in self.cr.doId2do:
suit = self.cr.doId2do[suitId]
self.suits.append(suit)
suit.fsm.request('Battle')
suit.buildin... |
e_id'))
self.object.stage = current_stage
self.object.save()
# Good to make note of that
messages.add_message(self.request, messages.SUCCESS, 'Configuration %s created' % self.object.key)
return super(ProjectConfigurationCreate, self).form_valid(form)
def get_success_... | return super(DeploymentCreate, self).form_valid(form)
def get_context_data(self, **kwargs):
context = super(DeploymentCreate, self).get_context_data(**kwargs) |
context['configs'] = self.stage.get_queryset_configurations(prompt_me_for_input=False)
context['stage'] = self.stage
context['task_name'] = self.task_name
context['task_description'] = self.task_description
return context
def get_success_url(self):
return reverse('... |
from django.conf import settings
from djang | o.conf.urls.defaults import *
urlpatterns = patterns('',
url(
regex = '^(?P<prefix>%s)(?P<tiny>\w+)$' % '|'.join(settings.SHO | RTEN_MODELS.keys()),
view = 'shorturls.views.redirect',
),
) |
f | rom typing import List, Optional
from backend.common.consts.ranking_sort_orders import SORT_ORDER_INFO
from backend.common.models.event_details import EventDetails
from backend.common.models.event_ranking import EventRanking
from backend.common.models.event_team_status import WLTRecord
from backend.common.models.keys ... | ORD_YEARS = {2010, 2015, 2021}
QUAL_AVERAGE_YEARS = {2015}
@classmethod
def build_ranking(
cls,
year: Year,
rank: int,
team_key: TeamKey,
wins: int,
losses: int,
ties: int,
qual_average: Optional[float],
matches_played: int,
d... |
up, (2) configure ingress to the broker backend (currently
Redis, as used by Dramatiq). It then (3) creates as many worker instances as requested and runs 'user-data' scripts
after startup, which is to say, bash scripts that set up and the required software (Redis, CSAOpt Worker, etc.).
After the run AWSToo... | ad()
broker_instance = self.__map_ec2_instance(
instance=self.broker, is_broker=True, port=self.broker_port, password=self.broker_password)
worker_instances = [self.__map_ec2_instance(w, queue_id=w.id) for w in self.workers]
return broker_instance, worker_instances
def _termin... | None:
"""Terminate all instances managed by AWSTools
Args:
timeout_ms: Timeout, in milliseconds, for the termination
"""
instance_ids = [self.broker.id] + [instance.id for instance in self.workers]
self.ec2_client.terminate_instances(InstanceIds=instance_ids)
de... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft | (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# ------------------------------------------------------------- | -------------
VERSION = "5.6.130"
|
# Copyright (C) 2015 Ross D Milligan
# GNU GENERAL PUBLIC LICENSE Version 3 (full notice can be found at https://github.com/rdmilligan/SaltwashAR)
from rockyrobotframes import *
from sportyrobotframes import *
from constants import *
class Robot:
def __init__(self):
self.body_frame = None
self.he... | self.head_angry_frames = rocky_robot_head_angry_frames(is_animated)
self.degrees_90_frame = rocky_robot_degrees_90_frame()
self.degrees_180_frame = rocky_robot_degrees_180_frame()
self.degrees_270_frame = rocky_robot_degrees_270_frame()
class SportyRobot(Robot):
# load f | rames
def load_frames(self, is_animated):
self.body_frame = sporty_robot_body_frame()
self.head_passive_frames = sporty_robot_head_passive_frames(is_animated)
self.head_speaking_frames = sporty_robot_head_speaking_frames(is_animated)
self.head_happy_frames = sporty_robot_head_happy_f... |
from . import Cl, conformalize
layout_orig, blades_orig = Cl(3)
layout, bl | ades, stuff = conformalize(layout_orig | )
locals().update(blades)
locals().update(stuff)
# for shorter reprs
layout.__name__ = 'layout'
layout.__module__ = __name__
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2018 jem@seethis.link
# Licensed under the MIT license (http://opensource.org/licenses/MIT)
from keyplus.utility import inverse_map
AES_KEY_LEN = 16
EP_VENDOR_SIZE = 64
VENDOR_REPORT_LEN = 64
FLASH_WRITE_PACKET_LEN = EP_VENDOR_SIZE - 5
SETTINGS_RF_INFO_SIZE =... | _HARD_CODED = 0x03
MATRIX_SCANNER_INTERNAL_VIRTUAL = 0x04
MATRIX_SCANNER_INTERNAL_CUSTOM = 0xff
INTERNAL_SCAN_METHOD_NAME_TABLE = {
"none": MATRIX_SCANNER_INTERNAL_NONE,
"fast_row_col": MATRIX_SCANNER_INTERNAL_FAST_ROW_COL,
"basic_scan": MATRIX_SCANNER_INTERNAL_BASIC_SCAN,
"hard_coded": MATRIX_SCANNER_... | = inverse_map(INTERNAL_SCAN_METHOD_NAME_TABLE)
VIRTUAL_MAP_TABLE_SIZE = 0x300
|
"""
WSGI config for captain project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` ... | ult("DJANGO_SETTINGS_MODULE", "captain.settings")
# Add the app dir to the python path so we can import manage.
wsgidir = os.path.dirname(__file__)
site.addsitedir(os.path.abspath(os.path.join(wsgidir, '../')))
# Manage adds /vendor to the Python path.
import manage
# This application object is used by any WSGI serv... | er, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
# -*- coding: utf-8 -*-
# Copyright (C) 2010 Samalyse SARL
# Copyright (C) 2010-2014 Parisson SARL
# This file is part of Telemeta.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, eithe... | pus'
children_type = 'collections'
children = models.ManyToManyField(MediaCollection, related_name="corpus",
verbose_name=_('collections'), blank=True)
recorded_from_year = IntegerField(_('recording year (from)'), help_text=_(... | wnload corpus EPUB"),)
@property
def public_id(self):
return self.code
@property
def has_mediafile(self):
for child in self.children.all():
if child.has_mediafile:
return True
return False
def computed_duration(self):
duration = Duration... |
from rest_framework import serializers
from .models import Foto
class FotoSerializer(serializers | .HyperlinkedModelSerializer):
c | lass Meta:
model = Foto
fields = (
'id',
'name',
'location',
'date',
'image',
'created',
'updated'
)
|
############################################################################## |
# 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-647188
#
# For details, see https://github.com/spack/spack
# Please also see the... | the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# 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... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 NEC Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# ... | e License.
import logging
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import api
from horizon import exceptions
from horizon import forms
from horizon import messages
LOG = logging.getLogger(__name__)
|
class UpdateNetwork(forms.SelfHandlingForm):
name = forms.CharField(label=_("Name"), required=False)
tenant_id = forms.CharField(widget=forms.HiddenInput)
network_id = forms.CharField(label=_("ID"),
widget=forms.TextInput(
attrs={'reado... |
osoft Corporation.
# Licensed under the MIT license.
import json
import os
from typing import Any, Dict, Iterator, List
from dataflow.core.utterance_tokenizer import UtteranceTokenizer
from dataflow.multiwoz.create_programs import create_programs_for_trade_dialogue
from dataflow.multiwoz.salience_model import DummySa... | ricerange (?= "none") :stars (?= "none") :type (?= "none")))""",
# turn 2
"""(ReviseCons | traint :new (Constraint[Hotel] :name (?= "hilton") :pricerange (?= "cheap") :type (?= "guest house")) :oldLocation (Constraint[Constraint[Hotel]]) :rootLocation (roleConstraint #(Path "output")))""",
# turn 3
"""(ReviseConstraint :new (Constraint[Hotel] :name (?= "none")) :oldLocation (Constraint[Constr... |
#!/usr/bin/env python
# Thomas Nagy, 2005-2013
# Modifications by Hans-Martin von Gaudecker for econ-project-templates
"""
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the ab... | provided with the distri | bution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND ... |
# -*- coding: utf-8 -*-
import datetime
from kivy.app import App
from kivy.uix.widget import Widget
import random
from kivy.clock import Clock
from kivy.properties import StringProperty, NumericProperty
from webScrape import webScraper
class MirrorWindow(Widget):
dayPrint = ['Sön', 'Mån', 'Tis', 'Ons', 'Tors', ... | self.secondsAnim = self.secondsAnim + 6
else:
self.secondsAnim = 0
#self.minute = int (datetime.datetime.today().strftime('%S') )
if self.minute < 360:
self.minute = self.minute + 0.1
else:
self.minute = 0.1
class MirrorApp(App):
def build(self):... | Clock.schedule_interval(mirrorWindow.update, 0.01)
return mirrorWindow
if __name__ == '__main__':
MirrorApp().run()
|
import os
import sys
import time
from django.db import models
'''
@author: lbergesio,omoya,CarolinaFernandez
@organization: i2CAT, OFELIA FP7
Django RuleTable Model class
'''
#Django is required to run this model
class PolicyRuleTableModel(models.Model):
class Meta:
"""Rul... | h = 120, default="", unique=True) # name
defaultParser = models.CharField(max_length = 64, default="", blank =True, null =True)
defaultPersistence = models.CharField(max_length | = 64, default="", blank =True, null =True)
defaultPersistenceFlag = models.BooleanField()
|
# Copyright 2016 Pinterest, 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 or agreed to in... | OG_FILENAME = self.fdout_fn
executor.MAX_RUNNING_TIME = 4
executor.MIN_RUNNING_TIME = 2
executor.DEFAULT_TAIL_LINES = 1
executor.MAX_RETRY = 3
executor.PROCESS_POLL_INTERVAL = 2
executor.BACK_OFF = 2
executor.MAX_SLEEP_INTERVAL = 60
executor.MAX_TAIL_BYTES... | entStatus.SCRIPT_TIMEOUT)
def test_run_command_with_shutdown_timeout(self):
cmd = ['sleep', '5m']
ping_server = mock.Mock(return_value=PingStatus.PLAN_CHANGED)
os.killpg = mock.Mock()
executor = Executor(callback=ping_server)
executor.LOG_FILENAME = self.fdout_fn
exe... |
from . import census |
class Stats(census.Stats):
namespace = "eq2"
def __str__(self):
return "EVERQUST 2 STATS API" | |
'%s' AND deviceCentral.code = '%s'"
#Type device
selectGetTypeDevice = "SELECT type FROM device WHERE id = '%s' AND code ='%s'"
#Get User id
selectUserId = "SELECT id FROM user WHERE login = '%s' AND password = '%s'"
#Check users and mails
selectUserExists = "SELECT login FROM user WHERE login = '%s'"
selectMailExis... | evice, device.pipeSend AS pipeSend, device.pipeRecv AS pipeRecv, device.code AS code, device.connectionMode AS connectionMode, device.version AS version FROM user, location, device, userLocation, locationDevice WHERE device.id = locationDevice.idDevice AND locationDevice.idLocation = location.id AND location.id = '%s' ... | S name FROM user, location, userLocation WHERE userLocation.idUser = user.id AND userLocation.idLocation = location.id AND user.id = '%s' AND location.name = '%s'"
insertLocation = "INSERT INTO location (name, security) VALUES ('%s','1')"
insertLocationUser = "INSERT INTO userLocation (idUser, idLocation) VALUES ('%s',... |
either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import logging
import sys
from typing import Any
from typing import Callable
from typing import List
from typing import Optional
from typing import Sequence
from typing impo... | action="store_true",
dest="dry_run",
help="Print Sensu alert events and metrics instead of sending them",
)
options = parser.parse_args()
return options
def check_services_replication(
soa_dir: str,
cluster: str,
service_instances: Sequence[str],
instance_type_class:... | check_service_replication: CheckServiceReplication,
replication_checker: ReplicationChecker,
all_tasks_or_pods: Sequence[Union[MarathonTask, V1Pod]],
dry_run: bool = False,
) -> Tuple[int, int]:
service_instances_set = set(service_instances)
replication_statuses: List[bool] = []
for service ... |
#!/usr/bin/env python
import sys, os, os.path, signal
import jsshellhelper
from optparse import OptionParser
from subprocess import Popen, PIPE, STDOUT
# Uses jsshell https://developer.mozilla.org/en/Introduction_to_the_JavaScript_shell
class Packer(object):
toolsdir = os.path.dirname(os.path.abspath(__file__))
... | print stderr
tmpFile = jsshellhelper.cleanUp(tmpFile)
def main():
parser = OptionParser()
options, args = parser.parse_args()
if len(args) < 2:
print >>sys.stderr, """Usage: %s <path to jsshell> <js file>""" % sys.argv[0]
sys.exit(1)
packer = Packer()
packer.run(args[0], ... | |
#!/usr/bin/env python3
import sys
from os import listdir, chdir
from os.path import isfile, abspath
UNTIL = '/build/'
REPLACE_WITH = '/b/f/w'
def bangchange(file_path):
script = File(file_path)
if script.flist[0].find("#!") == 0:
if script.flist[0].find(UNTIL) > 0:
print("\033[92m" + "[M... | g.split("\n")
def flush(self):
self.fstring = "\n".join(self.flist)
self.fh.seek(0)
self.fh.write(self.fstring)
self.fh.close()
def main():
if len(sys.argv) != 2:
print("\033[91m"+"[FAIL] Invalid arguments")
return 1
chdir(sys.argv[1])
for filename in l... | ir("."):
if isfile(abspath(filename)):
bangchange(filename)
main()
|
cloc | k.addListener("clockSt | opped", "python", "clock_stopped")
def clock_stopped():
print("The clock has been stopped") |
o(_config, None, 0, 0, IPPROTO_UDP)
for item in socket_info:
if item[0] == 2:
ipv4 = item[4][0]
elif item[0] == 30:
ipv6 = item[4][0]
if ipv4:
return ipv4
if ipv6:
return ipv6
return 'invalid address'
def build_config(_config_file):
... | E': '',
# These items are used to create the multi-byte FLAGS field
'AUTH_ENABLED': config.getboolean(section, 'AUTH_ENABLED'),
'CSBK_CALL': config.getboolean(section, 'CSBK_CALL'),
'RCM': | config.getboolean(section, 'RCM'),
'CON_APP': config.getboolean(section, 'CON_APP'),
'XNL_CALL': config.getboolean(section, 'XNL_CALL'),
'XNL_MASTER': config.getboolean(section, 'XNL_MASTER'),
'DATA_CALL': config.getbo... |
'''
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, Version 2.0 (the
"License"); you may not use this ... | configuration=None):
TraversalStrategy.__init__(self)
if graph_computer is not None:
self.configuration["graphComputer"] = graph_computer
if workers is not None:
self.configuration["workers"] = workers
if persist is not None:
self.configuratio... | es"] = vertices
if edges is not None:
self.configuration["edges"] = edges
if configuration is not None:
self.configuration.update(configuration)
###########################
# FINALIZATION STRATEGIES #
###########################
class MatchAlgorithmStrategy(TraversalStrategy):... |
# -*- coding: utf-8 -*-
#
# geoloc.py
#
# Copyright (C) 2010 Antoine Mercadal <antoine.mercadal@inframonde.eu>
# Copyright, 2011 - Franck Villaume <franck.villaume@trivialdev.com>
# This file is part of ArchipelProject
# http://archipelproject.org
#
# This program is free software: you can redistribute it and/or modify... | reply = self.iq_get(iq)
if reply:
conn.send(reply)
raise xmpp.protocol.NodeProcessed
def iq_get(self, iq):
"""
Return the geolocalization information.
@type iq: xmpp.Protocol.Iq
@param iq: the received IQ
"""
reply = iq.buildRe... | ocalization_information])
except Exception as ex:
reply = build_error_iq(self, ex, iq, ARCHIPEL_ERROR_CODE_LOCALIZATION_GET)
return reply
def message_get(self, msg):
"""
Return the geolocalization information asked by message.
@type msg: xmpp.Protocol.Message
... |
import sys
import os
import numpy as np
sys.path.append(os.path.join(os.getcwd(), ".."))
from run_utils import run_kmc, parse_input
from ParameterJuggler import ParameterSet
def main():
controller, path, app, cfg, n_procs = parse_input(sys.argv)
alpha_values = ParameterSet(cfg, "alpha\s*=\s*(.*)\;")
| alpha_values.initialize_set(np.linspace(0.5, 2, 16))
heights = ParameterSet(cfg, "confiningSurfaceHeight\s*=\s*(.*)\;")
heights.initialize_set([20.])
diffusions = ParameterSet(cfg, "diffuse\s*=\s*(.*)\;")
diffusions.initialize_set([3])
controller.register_parameter_set(alpha_values)
contro... | ter_parameter_set(diffusions)
controller.set_repeats(20)
controller.run(run_kmc, path, app, cfg, ask=False, n_procs=n_procs, shuffle=True)
if __name__ == "__main__":
main()
|
'''
c++ finally
'''
def myfunc():
b = False
try:
print('trying something that w | ill fail...')
print('some call that fails at runtime')
f = open('/tmp/nosuchfile')
except:
print('got exception')
finally:
pr | int('finally cleanup')
b = True
TestError( b == True )
def main():
myfunc()
|
# Copyright (c) 2013 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality ... | value
intlv_low_bit = int(math.log(rowbuffer_size, 2)) - 1
# We got all we need to configure the appropriate address
# range
ctrl.range = m5.objects.AddrRange(r.start, size = r.size(),
intlvHighBit = \
intlv_low_bi... | lv_bits,
intlvBits = intlv_bits,
intlvMatch = i)
return ctrl
def config_mem(options, system):
"""
Create the memory controllers based on the options and attach them.
If requested, we make a multi-channel configuration of the
... |
#!/usr/bin/env python
'''Check a queue and get times and info for messages in q'''
import sys
import os
import logging
import json
import datetime
import boto.sqs as sqs
QUEUE_OAI_HARVEST = os.environ.get('QUEUE_OAI_HARVEST', 'OAI_harvest')
QUEUE_OAI_HARVEST_ERR = os.environ.get('QUEUE_OAI_HARVEST_ERR', 'OAI_harvest_e... | visibility_timeout=10, attributes='All') #copied from boto implementation of save_to_file
while(msgs):
for m in msgs:
msg_dict = json.loads(m.get_body())
print 'ID:', m.id, '\n'
sent_dt = datetime.datetime.fromtimestamp(float(m.attributes['SentTimestamp'])/1000)
| print 'SENT AT: ', sent_dt
print 'IN QUEUE FOR:', datetime.datetime.now()-sent_dt
print msg_dict
print '\n\n'
msgs = q_harvesting.get_messages(num_messages=10, visibility_timeout=10, attributes='All')
if __name__=="__main__":
if len(sys.argv) < 2:
print 'Usa... |
"""
IndicoService Authentication Route
Creating and Maintaining Users
"""
from indico.utils.auth.auth_utils import auth, user_hash
from indico.utils.auth.facebook_utils import check_access_token
from indico.error import FacebookTokenError
fro | m indico.utils import unpack, mongo_callback, type_check
| from indico.routes.handler import IndicoHandler
from indico.db import current_time
import indico.db.user_db as UserDB
import indico.db.auth_db as AuthDB
class AuthHandler(IndicoHandler):
# Create User if doesn't exist
@unpack("access_token", "oauth_id", "user")
@type_check(str, str, dict)
def login(se... |
related.ManyToManyField', [], {'to': "orm['sentry.Project']", 'through': "orm['sentry.EnvironmentProject']", 'symmetrical': 'False'})
},
'sentry.environmentproject': {
'Meta': {'unique_together': "(('project', 'environment'),)", 'object_name': 'EnvironmentProject'},
'environment'... | d', [], {'null': 'True'})
},
'sentry.eventmapping': {
| 'Meta': {'unique_together': "(('project_id', 'event_id'),)", 'object_name': 'EventMapping'},
'date_added': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'event_id': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'group... |
wargs=kwargs)
def run_func(self, func, *args, **kwargs):
try:
result = func(*args, **kwargs)
self.queue.put((True, result))
except Exception as e:
self.queue.put((False, e))
def done(self):
return self.queue.full()
def result(self):
retu... | = list:
new_targets[targets[0]] = targets[1:]
else:
assert type(targets) == dict
new_targets = targets
from copy import deepcopy
new_task = deepcopy(self)
new_task.__init__(mode=mode,
... | ig=ci_config,
fast=fast,
pkgs=pkgs, srcs=new_srcs, targets=new_targets,
cmake_cmd=cmake_cmd,
cmake_args=cmake_args,
make_cmd=make_cmd,
make_... |
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2020 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the h... | f.assertThat(
schema,
Equals(
{
"$schema": "http://json-schema.org/draft-04/schema#",
"additionalProperties": False,
"properties": {
"meson-parameters": {
"default": [ | ],
"items": {"type": "string"},
"type": "array",
"uniqueItems": True,
},
"meson-version": {"default": "", "type": "string"},
},
"required": ["source... |
if (hasattr(other, "__getitem__")):
self.x = f(self.x, other[0])
self.y = f(self.y, other[1])
else:
self.x = f(self.x, other)
self.y = f(self.y, other)
return self
# Addition
def __add__(self, other):
if isinstance(other, Ve... | atan2(cross, dot))
def normalized(self):
length = self.length
if length != 0:
return self/length
return Vec2d(self)
def normalize_return_length(self):
length = self.len | gth
if length != 0:
self.x /= length
self.y /= length
return length
def perpendicular(self):
return Vec2d(-self.y, self.x)
def perpendicular_normal(self):
length = self.length
if length != 0:
return Vec2d(-self.y/leng... |
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
import pytest
from shuup.simple_cms.plugins import PageLinksPlugin
from shuup_tests.front... | one
page.save()
assert page in plugin.get_context_data(context)["pages"]
plugin.config["hide_expired"] = True
pages_in_context = plugin.get_context_data(context)["pages"]
assert page not in p | ages_in_context
assert another_page in pages_in_context
@pytest.mark.django_db
def test_page_links_plugin_show_all():
"""
Test that show_all_pages forces plugin to return all visible pages
"""
context = get_jinja_context()
page = create_page(eternal=True, visible_in_menu=True)
plugin = Pag... |
# What if | you just wanted to split a word in half and return each half on its own:
# You could do the following:
def reverse(st):
words = list(st.split(' | '))
print(words)
rev_word = words[::-1]
print(rev_word)
return ' '.join(rev_word)
# but this can be condensed to one sentence:
def reverse(st):
return ' '.join(st.split(' ')[::-1])
# or like this:
def reverse(st):
return ' '.join(reversed(st.split(' ')))
|
import os |
import pusher
CHANNEL = "response-updates"
client = pusher.Pusher(
app_id=os.environ.get("PUSHER_APP_ID"),
key=os.environ.get("PUSHER_KEY"),
secret=os.environ.get("PUSHER_SECRET"),
cluster='eu',
ssl=True
) if "IS_PROD" in os.environ else None
def notify(msg_type, payload):
"""Notifies that ... | L, msg_type, payload)
|
import os
from datetime import datetime
class HQ(object):
def __init__(self, fpath, kpath):
self.people_in_hq = 0
self.keys_in_hq = 0
self.joined_users = []
self.hq_status = 'unknown'
self.status_since = datetime.now().strftime('%Y-%m-%d %H:%M')
self.is_clean = True... | open'
self.update_time()
if setStatus:
self.status.setStatus('open')
def hq_close(self, setStatus=True):
self.hq_status = 'closed'
self.update_time()
self.people_in_hq = 0
self.keys_in_hq = 0
del(self.joined_users[:])
del(self.joined_keys[... | self, setStatus=True):
self.hq_status = 'private'
self.update_time()
if setStatus:
self.status.setStatus('private')
def hq_clean(self):
self.is_clean = True
self.savestates()
def hq_dirty(self):
self.is_clean = False
self.savestates()
de... |
# -*- coding: utf-8 -*-
#
# Copyright(c) 2010 poweredsites.org
#
# 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... | Error(403)
else:
return method(self, *args, **kwargs)
return wrapper
def staff(method):
"""De | corate with this method to restrict to site staff."""
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if not self.current_user:
if self.request.method == "GET":
url = self.get_login_url()
if "?" not in url:
url += "?" + ... |
# import copy
# import sys
import unittest
from rdflib.graph import Graph
# from rdflib.namespace import NamespaceManager
from rdflib import (
# RDF,
# RDFS,
Namespace,
# Variable,
# Literal,
# URIRef,
# BNode
)
from rdflib.util import first
from FuXi.Rete.RuleStore import (
# N3RuleStore,
Setup... | constructNetwork=False)
# self.assertEqual(len(rules),
# 1,
# "There should be 1 rule: %s"%rules)
# rule=rules[0]
# self.assertEqual(repr(rule.formula.body),
# "ex:Foo(?X)")
# self.assertEqual(len(rule.... | GCI = (someProp | value | EX.fish) & EX.Bar
foo = EX.Foo
foo += leftGCI
self.assertEqual(repr(leftGCI),
'ex:Bar THAT ( ex:someProp VALUE <http://example.com/fish> )')
ruleStore, ruleGraph, network = SetupRuleStore(makeNetwork=True)
rules = network.setupDe... |
imp | ort tables
from numpy import *
from matplotlib.pyplot import *
from matplotlib.widgets import Button
#Open HDF5 data file
db = lambda x: 20*log10(x)
ax1 = subplot(2,2,1)
ax2 = subplot(2,2,2)
ax3 = subplot(2 | ,2,3)
def update(event):
f = tables.open_file('data.h5', mode='r')
data_2d = array(f.root.data)
c_coord = array(f.root.column_coordinate)
r_coord = array(f.root.row_coordinate)
ind = int(len(c_coord)/2)+2
ref = array(f.root.ref)
data_2d = data_2d/ref
ax1.clear()
m1=ax1.pcolormesh( c_coord, r_coord, db(abs(d... |
# Copyright 2019 The TensorFlow 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 applica... | ch
dimension.
"""
strategy = create_mirrored_strategy()
# Create the layers
assert f32_layer.dtype == f32_layer._compute_dtype == 'float32'
config = f32_layer.get_config()
distributed_f32_layer = f32_layer.__class__.from_config(config)
config['dtype'] = policy.Policy('mixed_float16'... | e for the distributed models
global_batch_size = input_shape[0]
assert global_batch_size % strategy.num_replicas_in_sync == 0
per_replica_batch_size = (
global_batch_size // strategy.num_replicas_in_sync)
per_replica_input_shape = list(input_shape)
per_replica_input_shape[0] = per_replica_ba... |
from setuptools import setup, find_packages
from orotangi import __version__ as version
install_requires = [
'Django==1.11.18',
'djangorestframework==3.6.2',
'django-cors-headers==2.0.2',
'django-filter==1.0.2',
'python-dateutil==2.6.0'
]
setup(
name='orotangi',
version=version,
descri... | 'Framework :: Django',
'Framework :: Django :: 1.11',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD Lice | nse',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.6',
'Topic :: Internet',
'Topic :: Communications',
'Topic :: Database',
],
install_requires=install_requires,
include_package_data=True,
)
|
# (c) 2019 Telstra Corporation Limited
#
# 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) any later version.
#
#... | print(chain['pem_text'])
print("Cert after split")
pprint(chain['split'])
print("path: %s" % chain['path'])
print("Expected chain length: %d" % chain['length'])
| print("Actual chain length: %d" % len(chain['split']))
raise AssertionError("Chain %s was not split properly" % chain['path'])
for chain_a in test_chains:
for chain_b in test_chains:
expected = (chain_a['same_as'] == chain_b['same_as'])
# Now test the comparison functi... |
n updated version of the application has been made available. That's
# just a simple matter of retrievin | g some data from a URL to retrieve the
# current version number and a download URL for the latest installer.
#
# Given the way that web access to the source repository in Google Code works
# in principle that could be used instead, but there are a couple of advantages |
# to having a service like this instead, in addition to the fact that as with
# the NSIS installer for the limiter client it's a handy example of how to do
# such things.
#
# For instance, an additional thing I could add to this is to have an installer
# extension for the limiter client app which can retrieve the clie... |
#!/usr/bin/python
#coding: utf-8 -*-
# (c) 2013, Benno Joy <benno@ansible.com>
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later ... | rams['tenant_name']:
_os_tenant_id = _os_keystone.tenant_id
else:
tenant_name = module.params['tenant_name']
for tenant in _os_keystone.tenants.list():
if tenant.name == tenant_name:
| _os_tenant_id = tenant.id
break
if not _os_tenant_id:
module.fail_json(msg = "The tenant id cannot be found, please check the parameters")
def _get_router_id(module, neutron):
kwargs = {
'name': module.params['name'],
'tenant_id': _os_tenant_id,
}
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.