prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
import graph
import dot
from core import *
import dataflow
def make_inst(g, addr, dest, op, *args):
def make_arg(a):
if a is None:
return None
if isinstance(a, int):
return VALUE(a)
if isinstance(a, str):
return REG(a)
return a
b = BBlock(add... | KILL_LV = {
1: {REG("x")},
2: {REG("y")},
3: {REG("x")},
4: set(),
5: {REG("z")},
6: {REG("z")},
7: {REG("x")},
}
for i, info in g.iter_sorted_nodes():
assert info["live_gen"] == GEN_LV[i]
assert info["live_kill"] == KILL_LV[i]
a... | t"] == LV_exit[i]
|
from ecgmeasure import ECGMeasure
import pandas as pd
import numpy as np
# need to test what happens when have too little data to create a chunk
# need to throw an exception if have too little data
def get_raw_data():
""".. function :: get_raw_data()
Creates dataframe with raw data.
"""
times = [x*0.... | eshold is the same for all chunks of the raw data.
"""
thr = []
for x in range(0, 10):
thr.append(0.9*25)
thresholds = np.array(thr)
chunk = 50
num_chunks = 10
biomeasure = ECGMeasure(file_bool=True, argument="test_hr.csv")
# biomeasure.__hr_rawdata = get_raw_data()
#print | (biomeasure.__hr_rawdata)
biomeasure.thresholdhr()
[t, c, n] = biomeasure.data
t_list = t.values.T.tolist()[0]
assert (t_list == thresholds).all()
assert c == chunk
assert n == num_chunks
def get_test_hr1():
""".. function:: get_test_hr1()
Adds heartrate information to dataframe.
... |
from django.db import models
f | rom versatileimagefield.fields import VersatileImageField
from versatileimagefield.placeholder import OnStoragePlaceholderImage
class VersatileImagePostProcessorTestModel(models.Model):
"""A model for testing VersatileImageFields."""
image = VersatileImageField(
upload_to='./',
blank=True,
... | ss Meta:
verbose_name = 'foo'
verbose_name_plural = 'foos'
|
from os import walk
from os.path import basename, splitext, dirname, join, exists
from glob import glob
import importlib
from inspect import getmembers, isclass
import sverchok
from sverchok.utils.testing import *
from sverchok.utils.logging import debug, info, error
from sverchok.node_tree import SverchCustomTreeNod... | th)
py_name, ext = splitext(py_file)
module = importlib.import_module(f"sverchok.nodes.{category}.{py_name}")
for node_class_name, node_class in getmembers(module, isclass):
if node_class.__module__ != module.__name__:
continue
... | continue
debug("Check: %s: %s: %s", node_class, node_class.__bases__, SverchCustomTreeNode in node_class.__bases__)
if SverchCustomTreeNode in node_class.mro():
with self.subTest(node = node_class_name):
if not has_icon(node... |
# Define your item pipelines here
#
# Don | 't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pip | eline.html
class KyzsPipeline(object):
def process_item(self, item, spider):
return item
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#important: before running this demo, make certain that you import the library
#'paho.mqtt.client' into python (https://pypi.python.org/pypi/paho-mqtt)
#also make certain that ATT_IOT is in the same directory as this script.
import traceback ... | g, shutting down preview.")
setPreview(Fa | lse)
if value == "true":
camera.resolution = (1920, 1080) #set to max resulotion for record
camera.start_recording('video' + datetime.date.today().strftime("%d_%b_%Y_%H_%M%_S") + '.h264')
elif value == "false":
camera.stop_recording()
camera.resolution = (640, 480) ... |
ot context in synapse_sheets:
raise cherrypy.HTTPError("400 Bad Request", "Invalid Context specified (%s)" % context)
self.__cells = get_cell_engine(context)
if prop:
j['value'] = self.__cells.set_prop(key, prop, value)
else:
j['value'] = self.__cells.set_cell(key, value)
return json.dumps... | def set_cell(self, key, value=None):
"""Set the contents of the cell"""
data = {'action':'set_cell', 'key':key, 'value':value, 'context':self.context}
self.response = requests.post(self.__url__, data={'data':j | son.dumps(data)})
return self.__response()
def get_prop(self, key, prop, value=None):
"""Returns the contents of the cell"""
data = {'action':'get_prop', 'key':key, 'prop':prop, 'value':value, 'context':self.context}
self.response = requests.get(self.__url__, params={'data':json.dumps(data)})
return ... |
h_ops.less_equal),
("Maximum", math_ops.maximum),
("Minimum", math_ops.minimum),
("Mod", math_ops.mod),
("Mul", math_ops.multiply),
("NotEqual", math_ops.not_equal),
("Polygamma", safe_polygamma),
("Pow", math_ops.pow),
("RealDiv", math_ops.divide),
("SquareDifferen... | h"])
optimized = _make_dataset(["Batch", map_node_name]
| if expect_optimized else [map_node_name, "Batch"])
options = dataset_ops.Options()
options.experimental_map_vectorization = True
optimized = optimized.with_options(options)
return unoptimized, optimized
@parameterized.named_parameters(_generate_optimization_test_cases())
def testOptimizati... |
"""
Script to fetch historical data (since 2011) for matches (global, public).
Gives results in a chronological order (ascending), as they happened.
"""
from __future__ import print_function
from dota2py import api
from time import sleep as wait_for_next_fetch
def public_match_history(start_at_match_seq_num=None, mat... | 'statusDetail']
break
else:
# successful data fetch
cur_matches = cur_response['result']['matches']
if len(cur_response['result']['matches']) >= 1:
if not match_history:
# very first fetch
match_history.exten... | istory.extend(cur_matches[1:])
matches_fetched += len(cur_matches) - 1
if len(cur_matches) == 1 and cur_matches[0]['match_id'] == last_match_id:
break
else:
break
last_match_seq_num = cur_matches[-1]['match_seq_num']
... |
# Copyright 2008-2015 Nokia Solutions and Networks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtai | n 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 ... | language governing permissions and
# limitations under the License.
|
"Server does not support secure communication "
"via TLS / SSL"))
d = self.sendShort('STLS', None)
d.addCallback(self._startedTLS, contextFactory, tls)
d.addCallback(lambda _: self.capabilities())
return d
def _startedTLS(self, result, context, tls):... | }
@param useCache: If set, and if capabilities have been
retrieved previously, just return the previously retrieved
results.
@return: A Deferred which fires with a C{dict} mapping C{str}
to C{None} or C{list}s of C{str}. For example::
C: CAPA
S: +OK Cap... | ES
S: LOGIN-DELAY 900
S: PIPELINING
S: EXPIRE 60
S: UIDL
S: IMPLEMENTATION Shlemazle-Plotz-v302
S: .
will be lead to a result of::
| {'TOP': None,
| 'USER': None,
| 'SASL': ['CRAM-MD5', 'KERBEROS_V4']... |
ICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are inc... | repo_modify = modify[:]
if (hasattr(self.cli, 'repo_setopts')
and repo.id in self.cli.repo_setopts):
repo_modify.extend(self.cli.repo_setopts[repo.id].items)
if self.opts.save and modify:
dnfpluginscore.lib.write_raw_configfile(repo.repofile... | repo.cfg.options,
repo.iteritems,
repo.optionobj,
repo_modify)
def add_repo(self):
""" process --a... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('catalogue', '0001_initial'),
]
operations = [
migrati | ons.RenameModel(
old_name='Cd',
new_ | name='Release',
),
]
|
MatchInfo(match_dict, self._route),
allowed_methods)
return None, allowed_methods
def get_info(self):
return self._route.get_info()
def __len__(self):
return 1
def __iter__(self):
yield self._route
class Resource(AbstractResource):
def __init... | assert prefix.endswith('/'), prefix
super().__init__(
'GET', self.handle, name, expect_handler=expect_handler)
self._prefix = prefix
self._prefix_len = len(self._prefix)
try:
directory = Path(directory)
if | str(directory).startswith('~'):
directory = Path(os.path.expanduser(str(directory)))
directory = directory.resolve()
if not directory.is_dir():
raise ValueError('Not a directory')
except (FileNotFoundError, ValueError) as error:
raise ValueErr... |
# -*- coding: utf-8 -*-
"""Umgang mit mehrdimensionalen Arrays.
Im Folgenden wird der Umgang mit mehrdimensionalen Arrays
veranschaulicht. Die Beispiele zeigen zweidimensionale Arrays
(Matrizen), das Verhalten lässt | sich jedoch auf Arrays höherer
Dimensionen übertragen.
"""
import numpy as np
# Definition zufälliger Matrizen
A = np.random.random_integers(0, 10, (3, 3))
B = np.random.random_integers(0, 10, (3, 3))
# Rechenarten
A + B # Addition
A - B # Subraktio | n
A * B # Multiplikation
A @ B # Matrixmultiplikation
np.cross(A, B) # Kreuzprodukt
A.T # Transponieren einer Matrix
|
# coding: utf-8
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: api-support@onshape.zendesk.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
im... | {
"key": (str,), # noqa: E501
"value": (str,), # noqa: E501
}
@staticmethod
def discriminator():
return None
attribute_map = {
"key": "key", # noqa: E501
"value": "value", # noqa: E501
}
@staticmethod
def _composed_schemas():
... | None
required_properties = set(
[
"_data_store",
"_check_type",
"_from_server",
"_path_to_item",
"_configuration",
]
)
def __init__(
self,
_check_type=True,
_from_server=False,
_path_to_item=(),
... |
#!/usr/bin/env python
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import re
from calibre.ebooks.docx.names import XPath, get
class Field(obje... | parse_hyperlink(field.instructions[0][1], log)
if hl:
if 'target' in hl and hl['target'] is None:
hl['target'] = '_blank'
all_runs = []
current_runs = []
# We | only handle spans in a single paragraph
# being wrapped in <a>
for x in field.contents:
if x.tag.endswith('}p'):
if current_runs:
all_runs.append(current_runs)
current_... |
ermissions and
# limitations under the Licens | e.
#
"""Files API.
.. deprecated:: 1.8.1
Use Google Cloud Storage Client library instead.
Lightweight record format.
This format implements log file format from leveldb:
http://leveldb.googlecode.com/svn/trunk/doc/log_format.txt
Full specification of format follows in case leveldb decides to change it.
T | he log file contents are a sequence of 32KB blocks. The only
exception is that the tail of the file may contain a partial block.
Each block consists of a sequence of records:
block := record* trailer?
record :=
checksum: uint32 // masked crc32c of type and data[]
length: uint16
type: uint8 ... |
from django.db.models import Min
from django.http import Http404
from django.utils.encoding import force_str
from django.utils.translation import gettext as _
from django.views.generic import DetailView, YearArchiveView
from django.views.generic.detail import SingleObjectMixin
from spectator.core import app_settings
f... | '" % slug)
else:
self.kind_slug = slug
return super().get(request, *args, **kwargs)
def get_work_kind(self):
"""
We'll have a kind_s | lug like 'movies'.
We need to translate that into a work `kind` like 'movie'.
"""
slugs_to_kinds = {v: k for k, v in Work.Kind.slugs().items()}
return slugs_to_kinds.get(self.kind_slug, None)
class WorkListView(WorkMixin, PaginatedListView):
model = Work
def get_queryset(self)... |
"""
.. module:: CreateProfileForm
:synopsis: A form for completing a user's profile.
.. moduleauthor:: Dan Schlosser <dan@schlosser.io>
"""
from flask.ext.wtf import Form
from wtforms import StringField, HiddenField
from wtforms.validators import URL, Email, Required
EMAIL_ERROR = 'Please provide a valid email a... | ` profile after they
login to Eventum for the firs | t time.
:ivar email: :class:`wtforms.fields.StringField` - The user's email
address.
:ivar name: :class:`wtforms.fields.StringField` - The user's name.
:ivar next: :class:`wtforms.fields.HiddenField` - The URL that they should
be redirected to after completing their profile.
"""
nam... |
False
#----------------------------------------------------------------------
def __init__(self, points, wkid, hasZ=False, hasM=False):
"""Constructor"""
if isinstance(points, list):
self._points = points
elif isinstance(points, arcpy.Geometry):
self._points = sel... | o a common.Geometry object """
if isinstance(geom, arcpy.Multipoint):
feature_geom = []
fPart = []
for part in geom:
fPart = []
| for pnt in part:
fPart.append(Point(coord=[pnt.X, pnt.Y],
wkid=geom.spatialReference.factoryCode,
z=pnt.Z, m=pnt.M))
feature_geom.append(fPart)
return feature_geom
#---------------------------------------... |
game_type = 'input_output'
parameter_list = [['$x1','int'], ['$y0','int'], ['$y1','int']]
tuple_list = [
['KnR_1-7b_',[-3,None,None]]
]
global_code_template = '''\
d #include <stdio.h>
x #include <stdio. | h>
dx
dx /* power: raise base to n-th power; n >= 0 */
dx /* (old-style version) */
dx power(base, n)
dx int base, n;
dx {
dx int i, p;
dx
dx p = 1;
dx for (i = 1; i <= n; ++i)
dx p = p * base;
dx return p;
d | x }
dx
dx /* test power function */
'''
main_code_template = '''\
dx int i;
dx
dx for (i = 0; i < 3 ; ++i)
dx printf("%d %d %d\\n", i, power(2,i), power($x1,i));
'''
argv_template = ''
stdin_template = ''
stdout_template = '''\
0 1 1
1 2 $y0
2 4 $y1
'''
|
__author__ = 'jtsreinaldo'
from radio_constants import *
from validation_constants import *
class TXConfigRadioGenerator(object):
"""
A class for the reception configuration of a radio.
"""
def __init__(self):
"""
CTOR
"""
pass
@staticmethod
def tx_generator(... | ol={samples_per_symbol}, bt={bt})"
modulator = modulator.format(samples_per_symbol=samples_per_symbol, bt=bt)
except:
modulator = DEFAULTS[TX][GMSK][MOD | ULATOR]
tx_arch = "PacketGMSKTx(modulator={modulator})"
tx_arch = tx_arch.format(modulator=modulator)
ip = radio[USRP][IP]
# Checks if the user passed the usrp ip address.
if ip is None:
uhd_sink = "UHDSink()"
else:
uhd_sink = "UHDSink(... |
d_format,
| self.process_list.processes.values()))
key = IOTopUI.sorting_keys[self.sorting_key][0]
if self.options.accumulated:
stats_lambda = lambda p: p.stats_accum
else:
stats_lambda = lambda p: p.stats_delta
processes.sort(key=lambda p: key(p, st | ats_lambda(p)),
reverse=self.sorting_reverse)
if not self.options.batch:
del processes[self.height - 2:]
return list(map(format, processes))
def refresh_display(self, first_time, total, current, duration):
summary = [
'Total DISK READ : %s ... |
"""
mbed SDK
Copyright (c) 2011-2013 ARM Limited
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 wr... | g permissions and
limitations under the License.
"""
class HostRegistry:
""" Class stores reg | istry with host tests and objects representing them
"""
HOST_TESTS = {} # host_test_name -> host_test_ojbect
def register_host_test(self, ht_name, ht_object):
if ht_name not in self.HOST_TESTS:
self.HOST_TESTS[ht_name] = ht_object
def unregister_host_test(self):
if ht_... |
timeoper = idt_dtoper.DateTimeOperator()
# Unix time
self.assertEqual(
'2019-01-11T10:40:15Z',
datetimeoper.process_time_point_str(
'Fri 11 Jan 10:40:15 UTC 2019',
print_format=datetimeoper.CURRENT_TIME_DUMP_FORMAT_Z))
# Basic
self.... | r.process_time_point_str(point_str, ['-P1DT1H']))
# Multiple offsets
self.assertEqual(
point_str_3,
datetimeoper.process_time_point_str(point_str, ['-P1D', '-PT1H']))
# Bad time point string
self.assertRaises(
ValueError,
datetimeoper.proce... | time_point_str, 'teatime')
# Bad offset string
with self.assertRaises(
idt_dtoper.OffsetValueError,
) as ctxmgr:
datetimeoper.process_time_point_str(point_str, ['ages'])
self.assertEqual('ages: bad offset value', str(ctxmgr.exception))
# Bad offset string,... |
ique": "True",
},
),
"user": ("django.db.models.fields.CharField", [], {"max_length": "64"}),
},
"locations.event": {
"Meta": {"object_name": "Event"},
"admin_id": (
"django.db.models.fields.related.ForeignKey",
... | odels.fields.related.ForeignKey",
| [],
{"to": "orm['locations.Location']", "to_field": "'uuid'"},
),
"pipeline": (
"django.db.models.fields.related.ForeignKey",
[],
{"to": "orm['locations.Pipeline']", "to_field": "'uuid'"},
),
},
... |
##
# Copyright (c) 2010-2017 Apple Inc. 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, 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
# l... | efer import inlineCallbacks, returnValue
from twisted.web.client import Agent
from twisted.web.http_headers import Headers
from twisted.web.http import CREATED
from contrib.performance.httpauth import AuthHandlerAgent
from contrib.performance.httpclient import StringProducer
from contrib.performance.benchlib import i... |
"""Output formatters using shell syntax.
"""
from .base import SingleFormatter
import argparse
import six
class ShellFormatter(SingleFormatter):
def add_argument_group(self, parser):
| group | = parser.add_argument_group(
title='shell formatter',
description='a format a UNIX shell can parse (variable="value")',
)
group.add_argument(
'--variable',
action='append',
default=[],
dest='variables',
metavar='VARIABL... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Test suite for language_check."""
from __future__ import unicode_literals
import unittest
import warnings
from collections import namedtuple
import language_check
class TestLanguageTool(unittest.TestCase):
CheckTest = namedtuple('CheckTest', ('text', 'matches'))... | for expected_match in expected_matches:
for match in matches:
if (
(match.fromy, match.fromx, match.ruleId) ==
(expected_match.fromy, expected_match.fromx,
expected_match.ruleId)
... | break
else:
raise IndexError(
'can’t find {!r}'.format(expected_match))
def test_correct(self):
lang_check = language_check.LanguageTool()
for language, tests in self.correct_tests.items():
try:
lang... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import re
import unicodedata
import datetime
import subprocess
from py3compat import string_types, text_type
from django.utils impo... | , 53, 54, 55, 56, 57, 58,
590, 591, 592, 593, 595, 597, 598, 599, 60, 61, 62, 63,
64, 65, 66, 670, 672, 673, 674, 675, 676, 677, 678, 679,
680, 681, 682, 683, 685, 686, 687, 688, 689, 690, 691,
692, 7, 81, 82, 84, 850, 852, 853, 855, 85... | 4, 95, 960, 961, 962, 963,
964, 965, 966, 967, 968, 970, 971, 972, 973, 974, 975,
976, 977, 98, 992, 993, 994, 995, 996, 998]
MONTHS = ['J', 'F', 'M', 'A', 'Y', 'U', 'L', 'G', 'S', 'O', 'N', 'D']
ALPHA = 'abcdefghijklmnopqrstuvwxyz'
def phonenumber_isint(number):
''' whet... |
import csv
from numpy import h | istogram
def review_stats(count_ratings, length):
# print "in extract_rows"
ip_csv = "data\input\yelp_academic_dataset_review_ext.csv"
with open(ip_csv, "rb") as source:
| rdr = csv.reader(source)
firstline = True
for r in rdr:
if firstline: # skip first line
firstline = False
continue
count_ratings[int(r[2])] += 1
length.append(len(r[0]))
def business_stats(categories, category_count):
ip_... |
from code_intelligence import graphql
import fire
import github3
import json
import logging
import os
import numpy as np
import pprint
import retrying
import json
TOKEN_NAME_PREFERENCE = ["INPUT_GITHUB_PERSONAL_ACCESS_TOKEN", "GITHUB_PERSONAL_ACCESS_TOKEN", "GITHUB_TOKEN"]
for token in TOKEN_NAME_PREFERENCE:
if os.... | or the | repository
output: The directory to write the results
Writes the issues along with the first comments to a file in output
directory.
"""
client = graphql.GraphQLClient()
num_issues_per_page = 100
query_template = """{{
repository(owner: "{org}", name: "{repo}") {{
issues(first:{num_is... |
# | -*- coding: utf-8 -*-
from django.conf.urls import url
from . import views
urlpatterns = [
url(r"^/android/setup$", views.android_setup_view, name="notif_android_setup"),
url(r"^/chrome/setup$", views.chrome_setup_view, name="notif_chrome_se | tup"),
url(r"^/chrome/getdata$", views.chrome_getdata_view, name="notif_chrome_getdata"),
url(r"^/gcm/post$", views.gcm_post_view, name="notif_gcm_post"), url(r"^/gcm/list$", views.gcm_list_view, name="notif_gcm_list")
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-04 09:25
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
... | e, verbose_name='ID')),
('external_job_id', models.IntegerField(default=-1)),
('plugin', models.CharField(max_length=256)),
('name', models.CharField(max_length=256)),
('value', models.CharField(max_length=256)),
('instance', models.Foreign... | rations.AlterUniqueTogether(
name='job',
unique_together=set([('instance', 'external_job_id')]),
),
]
|
# Copyright (c) 2001-2016, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and open public tr... | 4T120000'
def test_stif_max_successive_buses(self):
"""
BUS Bus Bus Bus
stopP ----> stopQ ----> stopR ----> stopS ----> stopT
15:00 16:00 17:00 18:00 19:00
Bus
stopP --------------------... |
15:00 20:00
Test of request with parameter "_max_successive_physical_mode":
* we want to make at least 2 journey calls (not only the best journey, but also try next)
* we don't want the journey using more than 3 Buses
So here we want jo... |
# The MIT License (MIT)
# Copyright (c) 2009 Max Polk
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, ... | or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE L... | UT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import errno
import fcntl
import os
class FLock:
'''
Ensures application is running only once, by using a lock file.
Ensure call to lock works. Then call unlock at program exit.
You cannot read or write to ... |
#!/usr/bin/python
# AUTHOR : liuxu-0703@163.com
# used to extract keyword sets from xml
# used by aplog_helper.sh and adblogcat.sh
import os
import sys
import getopt
from xml.dom.minidom import parse, parseString
#=======================================
class KeywordSet:
def __init__(self, xml_node):
... | KeywordSet instance
$a and $b should be instance of KeywordSet
return -1, 0, 1
'''
if a.type != b.type:
if a.type == 'include':
| return -1
if a.type == 'exclude':
return 1
if a.project != b.project:
if a.project == 'None':
return -1
if b.project == 'None':
return 1
cmp_result = cmp(a.project, b.project)
if cmp_result... |
"""# Components.
You can adapt some component functions from the `gdsfactory.components` module.
Each func | tion there returns a Component object
Here are two equivalent functions
"""
import gdsfactory as gf
def straight_wide1(width=10, **kwargs) -> gf.Component:
return gf.components.straight(width=width, **kwargs)
straight_wide2 = gf.partial(gf.components.straight, width=10)
if __name__ == "__main__":
# c =... | e1()
c = straight_wide2()
c.show()
|
from PyQt5 import QtCore, QtWidgets
import chigger
import peacock
from peacock.ExodusViewer.plugins.ExodusPlugin import ExodusPlugin
from MeshBlockSelectorWidget import MeshBlockSelectorWidget
class BlockHighlighterPlugin(peacock.base.PeacockCollapsibleWidget, ExodusPlugin):
"""
Widget for controlling the visi... | f onWindowUpdated(self):
"""
Update boundary/nodeset visibility when window is updated.
"""
if self._reader:
self.blockSignals(True)
self.BlockSelector.updateBlocks(self._reader)
self.SidesetSelector.updateBlocks(self._reader)
self.NodesetS... | Block(self):
"""
Highlights a block and resets nodesets/sidesets
"""
block = self.BlockSelector.getBlocks()
self.SidesetSelector.reset()
self.NodesetSelector.reset()
self.highlight.emit(block, None, None)
def setSideset(self):
"""
Highlights a... |
"""
Handle logging in a Message Box?
"""
from PyQt4 import QtGui, QtCore
import logging
import sys
class MyQWidget(QtGui.QWidget):
def center(self):
frameGm | = self.frameGeometry()
screen = QtGui.QApplication.desktop().screenNumber(QtGui.QApplication.desktop().cursor().pos())
centerPoint = QtGui.QApplication.desktop().screenGeometry(screen).center()
frameGm.moveCenter(centerPoint)
self.move(frameGm.topLeft())
class ConsoleWindowLogHandler(l... | dowLogHandler, self).__init__()
self.sigEmitter = sigEmitter
def emit(self, logRecord):
message = str(logRecord.getMessage())
self.sigEmitter.emit(QtCore.SIGNAL("logMsg(QString)"), message)
|
force_defaults=True, skip_passwords=False,
data_formencode_form=None, data_formencode_ignore=None,
):
"""
Render the ``form`` (which should be a string) given the ``defaults``
and ``errors``. Defaults are the values that go in the input fields
(overwriting any values th... | inline in the form (and also effect input classes). Returns the
rendered string.
If ``auto_insert_errors`` is true (the default) then any errors
for which ``<form:error>`` tags can't be found will be put just
above the associated input field, or at the top of the form if no
field can be found.
... | faults or errors that couldn't be used in the form it will be an
error.
``error_formatters`` is a dictionary of formatter names to
one-argument functions that format an error into HTML. Some
default formatters are provided if you don't provide this.
``error_class`` is the class added to input fie... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
# import codecs
# import json
# class stokeScrapyPipeline(object):
# def __init__(self):
# self.file=codecs.open... | ction.insert( dict (item))
log.msg( "Stoke added to MongoDB database!" ,
| level = log.DEBUG, spider = spider)
return item
# def process_item(self, item, spider):
# line = json.dumps(dict(item))+","
# self.file.write(line.decode("unicode_escape"))
# return item
|
# Copyright 2017 BrainPad Inc. 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... | t_data_json = os.path.join(os.path.dirname(__file__), 'adjust_data.json')
f = open(out_data_json, 'w')
f.write(json.dumps(out_data, sort_keys=True, indent=4))
| f.close()
except Exception as e:
raise e
def adjust(self, x, y):
if -1 <= x <= 1 and -1.5 <= y <= 1.5:
pass
else:
message = "Error: x=%s y=%s coordinate is out of range in sheet." % (x, y)
raise Exception(message)
x_round ... |
# -*- coding: utf-8 -*-
from django import forms
from django.core.validators import RegexValidator
from ...models import EighthBlock
block_letter_validator = RegexValidator(r"^[a-z A-Z0-9_-]{1,10}$",
"A block letter must be less than 10 characters long, and include only alphan... | .CharField(max_length=10, validators=[block_letter_validator])
class Meta:
model = EighthBlock
fields = | ["date", "block_letter"]
class BlockForm(forms.ModelForm):
block_letter = forms.CharField(max_length=10, validators=[block_letter_validator])
class Meta:
model = EighthBlock
fields = [
"date",
"block_letter",
"locked",
# "override_blocks",
... |
# bgscan tests
# Copyright (c) 2014, Jouni Malinen <j@w1.fi>
#
# This software may be distributed under the terms of the BSD license.
# See README for more details.
import time
import logging
logger = logging.getLogger()
import os
import hosta | pd
def test_bgscan_simple(dev, apdev):
"""bgscan_simple"""
hostapd.add_ap(apdev[0]['ifname'], { "ssid": "bgscan" })
hostapd.add_ap(apdev[1]['ifname'], { "ssid": "bgscan" })
dev[0].connect("bgscan", key_mgmt="NONE", scan_freq="2412",
bgscan="simple:1:-20:2")
dev[1].connect("bgsca... | bgscan="simple:1:-45:2")
dev[2].connect("bgscan", key_mgmt="NONE", scan_freq="2412",
bgscan="simple:1:-45")
dev[2].request("REMOVE_NETWORK all")
dev[2].wait_disconnected()
dev[2].connect("bgscan", key_mgmt="NONE", scan_freq="2412",
bgscan="simple:0... |
"" | "
WSGI config for lot project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MOD... | |
"""
Django settings for systematic_review project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DI... | gistration',
'bootstrapform'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.Sess... | 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'systematic_review.urls'
WSGI_APPLICATION = 'systematic_review.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
... |
##############################################################################
# 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 | -647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# 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 Software Foundatio | n) 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 the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You sho... |
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2009 Douglas S. Blank <doug.blank@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License... | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA... | = _("Set an attribute to a given value."),
version = '0.0.32',
gramps_target_version = "5.1",
status = STABLE, # not yet tested with python 3
fname = 'SetAttributeTool.py',
authors = ["Douglas S. Blank"],
authors_email = ["doug.blank@gmail.com"],
category ... |
import signal
import weakref
from functools import wraps
__unittest = True
class _InterruptHandler(object):
def __init__(self, default_handler):
self.called = False
self.original_handler = default_handler
if isinstance(default_handler, (int, long)):
if default_handler == sign... | ):
return bool(_results.pop(result, None))
_interrupt_handler = None
def installHandler():
gl | obal _interrupt_handler
if _interrupt_handler is None:
default_handler = signal.getsignal(signal.SIGINT)
_interrupt_handler = _InterruptHandler(default_handler)
signal.signal(signal.SIGINT, _interrupt_handler)
def removeHandler(method=None):
if method is not None:
@wraps(method... |
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2020, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software you can redistribute it and/or modify
# it under... | model_args=dict(conf | ig=dict(
num_classes=1000,
defaults_sparse=True,
activation_params_func=my_auto_sparse_activation_params,
conv_params_func=my_auto_sparse_conv_params,
linear_params_func=my_auto_sparse_linear_params
)),
lr_scheduler_args=dict(
max_lr=6.0,
div_factor=6, #... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import multiprocessing
import gunicorn.app.base
from gunicorn.six import iteritems
def number_of_workers():
return (multiprocessing.cpu_count() * 2) + 1
class StandaloneApplication(gunicorn.app.base.BaseApplication):
de... | }
self.application = app
super(StandaloneApplication, self).__init__()
de | f load_config(self):
config = dict([(key, value) for key, value in iteritems(self.options)
if key in self.cfg.settings and value is not None])
for key, value in iteritems(config):
self.cfg.set(key.lower(), value)
def load(self):
return self.application
i... |
# | flake8: noqa
from . import html, richtext, snippet
try:
import requests
except ImportError: # pragma: no cover
pass
else:
from . import external
try:
import imagefield
except ImportError: # pragma: no cover
pass
else:
fro | m . import image
|
#!/usr/bin/env python
"""
Match input spectrum to ID lines
"""
from __future__ import (print_function, absolute_import, division, unicode_literals)
import pdb
try: # Python 3
ustr = unicode
except NameError:
ustr = str
def parser(options=None):
import argparse
# Parse
parser = argparse.ArgumentP... | plotlib import pyplot as plt
from linetools import utils as ltu
from arclines import io as arcl_io
from arclines.holy import utils as arch_utils
from arclines.holy.grail import general, semi_brute
from arclines.holy import patterns as arch_pa | tt
from arclines.holy import fitting as arch_fit
if pargs.outroot is None:
pargs.outroot = 'tmp_matches'
# Defaults
# Load spectrum
spec = arcl_io.load_spectrum(pargs.spectrum)
if pargs.show_spec:
plt.clf()
ax = plt.gca()
ax.plot(spec)
plt.show()
#... |
#!/usrbin/python
#encoding:utf-8
'''
Author: wangxu
Email: wangxu@oneniceapp.com
任务更新
'''
import sys
reload(sys)
sys.setde | faultencoding("utf-8")
import logging
import tornado.web
import json
import os
import time
CURRENTPATH = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(CURRENTPATH, '../../'))
from job_define import Job
#指标处理类
class JobUpdateHandler(tornado.web.RequestHandler):
#统一调用post方法
def get(s... |
#需要先从azkaban登陆
session_id = self.get_argument('session_id','')
login_user = self.get_argument('login_user','')
if session_id=='' or login_user=='':
self.render('to_login.html')
return
#参数
query_name = self.get_argument('query_name','')
que... |
#from distutils.core import setup
from setuptools import setup, find_packages
# http://guide.python-distribute.org/quickstart.html
# python setup.py sdist
# python setup.py register
# python setup.py sdist upload
# pip install epub_meta
# pip install epub_meta --upgrade --no-deps
# Manual upload to PypI
# http://pypi.... | 'Operating System :: OS Independent',
'Topic :: Software Development',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
| 'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: Implementation :: PyPy',
],
version=VERSION,
install_requires=... |
#!/usr/bin/env python
#
# Problem definition:
# A-R Hedar and M Fukushima, "Derivative-Free Filter Simulated Annealing
# Method for Constrained Continuous Global Optimization", Journal of
# Global Optimization, 35(4), 521-549 (2006).
#
# Original Matlab code written by A. Hedar (Nov. 23, 2005)
# http://www-optima.amp.... | chnology.
# License: 3-clause BSD. The full license text is available at:
# - http://trac.mystic.cacr.caltech.edu/project/mys | tic/browser/mystic/LICENSE
def objective(x):
x0,x1,x2,x3,x4,x5,x6 = x
return (x0-10)**2 + 5*(x1-12)**2 + x2**4 + 3*(x3-11)**2 + \
10*x4**6 + 7*x5**2 + x6**4 - 4*x5*x6 - 10*x5 - 8*x6
bounds = [(-10.,10.)]*7
# with penalty='penalty' applied, solution is:
xs = [2.330499, 1.951372, -0.4775414, 4.365726... |
#!/usr/bin/env python
import os
from setuptools import setup
setup(name='pymarkdown',
version='0.1.4',
description='Evaluate code in markdown',
url='http://github.com/mrocklin/pymarkdown',
author='Matthew Rockl | in',
author_email='mrocklin@gmail.com',
license='BSD',
keywords='markdown documentation',
packages=['pymarkdown'],
install_requires=['toolz'],
long_description=(open('README.rst').read() if os.path.exists('READ | ME.rst')
else ''),
zip_safe=False,
scripts=[os.path.join('bin', 'pymarkdown')])
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright: (2013-2017) Michael Till Beck <Debianguru@gmx.de>
# License: GPL-2.0+
import http.server
import socketserver
import importlib
import sys
import getopt
bind = 'localhost'
port = 8000
configMod = 'config'
t | ry:
opts, args = getopt.getopt(sys.argv[1:], 'hc:b:p:', ['help', 'config=', 'bind=', 'port='])
except getopt.GetoptError:
print('Usage: FeedServer.py --config=config --port=8000 --bind=localhost')
sys.exit(1)
for opt, arg in | opts:
if opt == '-h':
print('Usage: FeedServer.py --config=config --bind=localhost --port=8000')
exit()
elif opt in ('-c', '--config'):
configMod = arg
elif opt in ('-b', '--bind'):
bind = arg
elif opt in ('-p', '--port'):
port = int(arg)
config = importlib.impor... |
#!/u | sr/bin/env python3
# -*- coding: utf-8 -*-
# TerminalRoastDB, released under GPLv3
# Roaster Set Time
import Pyro4
import sys
new_roaster_time = sys.argv[1]
roast_control = Pyro4.Proxy("PYRONAME:roaster.sr700")
if int(new_roaster_time) > 0 and int(new_roaster_time) | <1200:
roast_control.set_time(new_roaster_time)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('wiki', '0001_initial'),
('userstories', '0009_remove_userstory_is_archived'),
('issues', '0005_auto_20150623_1923'),
... | dx";"""
),
migrations.RunSQL(
"""
CREATE INDEX "tasks_full_text_idx" ON tasks_task USING gin(to_tsvector('simple', coalesce(subject, '') || ' ' || coalesce(ref) || ' ' || coalesce(description, '')));
""",
reverse_sql | ="""DROP INDEX IF EXISTS "tasks_full_text_idx";"""
),
migrations.RunSQL(
"""
CREATE INDEX "issues_full_text_idx" ON issues_issue USING gin(to_tsvector('simple', coalesce(subject, '') || ' ' || coalesce(ref) || ' ' || coalesce(description, '')));
""",
rever... |
import os
import json
from urlparse import urlparse
from pymongo import uri_parser
def get_private_key():
with open('mistt-solution-d728e8f21f47.json') as f:
return json.loads(f.read()).items()
# Flask
CSRF_SESSION_KEY = os.getenv('FLASK_SESSION_KEY', 'notsecret')
SECRET_KEY = os.getenv('FLASK_SECRET_KEY'... | LE_SERVICE_ACCOUNT_EMAIL')
# GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY=get_private_key()[0][1]
GOOGLE_ANALYTICS_CLIENT_ | SECRET=os.getenv('GOOGLE_ANALYTICS_CLIENT_SECRET')
GOOGLE_ANALYTICS_CLIENT_ID=os.getenv('GOOGLE_ANALYTICS_CLIENT_ID')
UPLOAD_FOLDER=os.path.join(os.getcwd(),'uploads')
|
from ovito import *
from ovito.io import *
from ovito.modifiers import *
from ovito.vis import *
import matplotlib
# Activate 'agg' backend for off-screen plotting.
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import PyQt5.QtGui
node = import_file("../../files/CFG/fcc_coherent_twin.0.cfg")
node.modifiers.a... | difier not found.')
# G | et size of rendered viewport image in pixels.
viewport_width = painter.window().width()
viewport_height = painter.window().height()
# Compute plot size in inches (DPI determines label size)
dpi = 80
plot_width = 0.5 * viewport_width / dpi
plot_height = 0.5 * viewport_height / dpi
# Create figure
fig, ax = ... |
': 'Componente și plugin-uri',
'Confirmation Time': 'Confirmation Time',
'Confirmed': 'Confirmed',
'Contact': 'Contact',
'contains': 'conține',
'Continue Shopping': 'Continue Shopping',
'Controller': 'Controlor',
'Controllers': 'Controlori',
'controllers': 'controlori',
'Copyright': 'Drepturi de autor',
'Correct Altern... | Interested? Submit your email below to be notified for the next open class.',
'Interests': 'Interests',
'internal error': 'eroare internă',
'Internal State': ' | Stare internă',
'Introduction': 'Introducere',
'Invalid action': 'Acțiune invalidă',
'Invalid email': 'E-mail invalid',
'invalid password': 'parolă invalidă',
'Invalid password': 'Parolă invalidă',
'Invalid Query': 'Interogare invalidă',
'invalid request': 'cerere invalidă',
'invalid ticket': 'tichet invalid',
'Key': '... |
# urllib3/_collections.py
# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
#
# This module is part of urllib3 and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from collections import deque
from threading import RLock
__all__ = ['RecentlyUsedContai... | og entry by the key to invalidate it so we can
# insert a new authorative entry at the head without having to dig and
# find the old entry for removal immediately.
self.access_lookup = {}
# Trigger a heap cleanup when we get past this size
| self.access_log_limit = maxsize * self.CLEANUP_FACTOR
def _invalidate_entry(self, key):
"If exists: Invalidate old entry and return it."
old_entry = self.access_lookup.get(key)
if old_entry:
old_entry.is_valid = False
return old_entry
def _push_entry(self, key):
... |
"""Unit test for treadmill.runtime.
"""
import errno
import socket
import unittest
import mock
import treadmill
import treadmill.rulefile
import treadmill.runtime
from treadmill import exc
class RuntimeTest(unittest.TestCase):
"""Tests for treadmill.runtime."""
@mock.patch('socket.socket.bind', mock.Mock... | bind', mock.Mock())
def test__allocate_sockets_fail(self):
"""Test allocating sockets when all are taken.
"""
# access protected module _allocate_sockets
# pylint: disable=w0212
socket.socket.bind.side_effect = socket.error(errno.EADDRINUSE,
... | self.assertRaises(exc.ContainerSetupError):
treadmill.runtime._allocate_sockets(
'prod', '0.0.0.0', socket.SOCK_STREAM, 3
)
@mock.patch('socket.socket', mock.Mock(autospec=True))
@mock.patch('treadmill.runtime._allocate_sockets', mock.Mock())
def test_allocate_netwo... |
"""
Author: Maneesh Divana <mdaneeshd77@gmail.com>
Interpreter: Python 3.6.8
Quick Sort
Worst Case: O(n^2)
Average Case: O(nlog n)
Best Case: O(nlog n)
"""
from random import shuffle
def partition(arr: list, left: int, right: int) -> int:
"""Partitions the given array based on a pivot element,
then sorts the... | QuickSort algorithm."""
if left < right:
# Partition the array and get the partition index
p_idx = partition(arr, left, right)
# Recursively partition and sort the sub-arrays
qsort(arr, left, p_idx - 1)
qsort(arr, p_idx + 1, right)
if __name__ == "__main__":
ARR = lis... | LEFT, RIGHT)
print("\nSorted array:", ARR, "\n")
|
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def cre | ate(kernel):
result = Tangible()
result.template = "object/tangible/wearables/base/sha | red_base_sleeve_both.iff"
result.attribute_template_id = 11
result.stfName("wearables_name","default_sleeves")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
# s | ee ex50 | .py |
# Python 2 and 3:
try:
# Python 3 only: |
from urllib.parse import urlencode, urlsplit, parse_qs, unquote
except ImportError:
# | Python 2 only:
from urlparse import parse_qs, urlsplit
from urllib import urlencode, unquote
|
# (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
# 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/LI... | HTTPNotFound(Exception):
http_status = 404
message = "Not found"
class HTTPForbidden(ClientException):
http_status = 403
message = "Forbidden"
class HTTPBadRequest(Exception):
http_status = 400
message = "Bad request"
class HTTPServerError(Exception):
http_status = 500
message = "E... | error:
self._error_desc = error['message']
def get_description(self):
return self._error_desc
|
",
"invisible": "OPT_INVISIBLE",
"radioitem": "OPT_RADIOITEM",
"exitmenu" : "OPT_EXITMENU",
"login" : "login", # special type
"submenu" : "OPT_SUBMENU"}
entry_init = { "item" : "",
"info" : "",
"data" : "",
... | '%s' in line %d" % (value,self.lineno) ]
msg.append("REASON: Valid values are [A-Za-z0-9]")
return "\n".join(msg)
elif value != "-1": value = "'%s'" % | value
elif name in ["state","helpid","ipappend"]:
try:
value = int(value)
except:
return "Value of %s in line %d must be an integer" % (name,self.lineno)
self.entry[name] = value
self.entry["_updated"] = 1
return ""
def set_menu(self,name,... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-08-17 00:40
from __future__ import | unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('turnos', '0004_auto_20160519_0134'),
]
operations = [
migrations.RenameField('Turno', 'asistio', 'no_asistio'),
migrations.RenameField('Turno', 'aviso', 'no_aviso')
] | |
nd = begin + (config.recording.margin_before.value*60) + 1
return begin, end
def selectChannelSelector(self, *args):
self.session.openWithCallback(
self.finishedChannelSelectionCorrection,
ChannelSelection.SimpleChannelSelection,
_("Select channel to record from")
)
def finishedChannelSelectionC... | ce" and self.timerentry_starttime.value == [0, 0]:
self.timerentry_date.value += 86400
self["config"].invalidate(self.entryDate)
d | ef decrementStart(self):
self.timerentry_starttime.decrement()
self["config"].invalidate(self.entryStartTime)
if self.timerentry_type.value == "once" and self.timerentry_starttime.value == [23, 59]:
self.timerentry_date.value -= 86400
self["config"].invalidate(self.entryDate)
def incrementEnd(self):
if ... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012, Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
... | sion_uses_v1(self):
v1 = self.API1()
disp = dispatcher.RpcDispatcher([v1])
disp.dispatch( | self.ctxt, None, 'test_method', arg1=1)
self.assertEqual(v1.test_method_ctxt, self.ctxt)
self.assertEqual(v1.test_method_arg1, 1)
|
from unittest import TestCase
from unittest.mock import Mock
from grapher import errors
from grapher.parsers import QueryParser
from grapher.parsers import query
from nose_parameterized import parameterized
class QueryParserTest(TestCase):
| def setUp(self):
r = Mock()
r.args = Mock()
r.args.get = Mock()
query.request = r
@parameterized.expand([
({},
{'query': {}, 'skip': 0, 'limit': None}),
({'skip': '2'},
{'query': {}, 'skip': 2, 'limit': None}),
({
'query': '{"t... | 'limit': '10'
},
{'query': {'test': 'test 1'}, 'skip': 0, 'limit': 10}),
])
def test_parse(self, request_query, expected):
query.request.args.get.side_effect = lambda e: request_query[e] if e in request_query else None
actual = QueryParser.parse()
self.asser... |
# To make print working for Python2/3
from __future__ import print_function
import ystockquote as ysq
def _main():
for s in ["NA.TO", "XBB.TO", "NOU.V", "AP-UN.TO", "BRK-A", "AAPL"]:
print("=============================================")
print("s: {}".format(s))
print("get_name: {}".for... | ".format(ysq.get_dividend_yield(s)))
print("get_price_earnings_ratio: {}".format(ysq.get_price_earnings_ratio(s)))
print("get_52_week_low: {}".format(ysq.get_52_week_low(s)))
print("get_52_week_high: {}".format(ysq.get_52_week_high(s)))
print("get_currency: { | }".format(ysq.get_currency(s)))
if __name__ == '__main__':
_main()
|
# coding=utf-8
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from urllib import urlencode
try:
from urlparse import parse_qs
except ImportError:
from cgi import parse_qs
class SimplePaginator(object):
"""A simple wrapper around the Django paginator."""
def __init__(self, request... | # range, deliver last p | age of results.
try:
items = self.paginator.page(page)
except (EmptyPage, InvalidPage):
items = self.paginator.page(self.paginator.num_pages)
# Get base url
baseurl = self.get_base_url()
return items, order, baseurl
def paginate(*args, **kwargs):
"... |
fr | om .discre | te import DiscreteSimulation
|
imp | ort | asyncio
import gta.utils
# The following metadata will not be processed but is recommended
# Author name and E-Mail
__author__ = 'Full Name <email@example.com>'
# Status of the script: Use one of 'Prototype', 'Development', 'Production'
__status__ = 'Development'
# The following metadata will be parsed and should a... |
yright (C) 2013 Yahoo! Inc. 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 appl... | value: %s' % rebind_args)
def _check_args_mapping(task_name, rebind, args, accepts_kwargs):
args = set(args)
rebind = set(rebind.keys())
extra_args = rebind - args
missing_args = args - rebind
if not accepts_kwargs and extra_args:
raise ValueError('Extra arguments given to task %s: %s'
... | sorted(extra_args)))
if missing_args:
raise ValueError('Missing arguments for task %s: %s'
% (task_name, sorted(missing_args)))
def _build_arg_mapping(task_name, reqs, rebind_args, function, do_infer):
task_args = reflection.get_required_callable_args(function)
accepts_kw... |
act Tracing
"""
if not settings.has_module(c):
raise HTTP(404, body="Module disabled: %s" % c)
# -----------------------------------------------------------------------------
def index():
"Module's Home Page"
module_name = settings.modules[c].get("name_nice")
response.title = module_name
return {... | elds = [("", "value")],
filterby = {"field": "contact_method",
"options": "SMS",
| },
label = settings.get_ui_label_mobile_phone(),
multiple = False,
name = "phone",
),
S3SQLInlineComponent(
... |
#!/usr/bin/env python
imp | ort sys
from fireplace import cards
from fireplace.exceptions import GameOver
from fireplace.utils import play_full_game
sys.path.append("..")
def test_full_game():
try:
play_full_game()
except GameOver:
print("Game completed normally.")
def main():
cards.db.initialize()
if len(sys.argv) > 1:
numgames ... | )
exit(1)
for i in range(int(numgames)):
test_full_game()
else:
test_full_game()
if __name__ == "__main__":
main()
|
)
blenderbim.bim.handler.setDefaultProperties(None)
bpy.ops.bim.create_project()
def scenario(function):
def subfunction(self):
run(function(self))
return subfunction
def scenario_debug(function):
def subfunction(self):
run_debug(function(self))
return subfunction
... | "An opening was found"
def the_object_name_is_not_a_void(name):
ifc = IfcStore.get_file()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.i | fc_definition_id)
if any(element.VoidsElements):
assert False, "A void was found"
def the_void_name_is_filled_by_filling(name, filling):
ifc = IfcStore.get_file()
element = ifc.by_id(the_object_name_exists(name).BIMObjectProperties.ifc_definition_id)
if any(rel.RelatedBuildingElement.Name == f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright 2013 Kitware 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 cop... | Status(resp, 400)
self.assertEqu | al(resp.json['message'], 'Invalid resource: unknown')
def testRouteOrder(self):
# Check that the resources and operations are listed in the order we
# expect
resp = self.request(path='/describe/foo', method='GET')
self.assertStatusOk(resp)
listedRoutes = [(method['httpMethod... |
ecords with 'recID' system number between low
and high from memory words index table."""
write_message("%s fetching existing words for records #%d-#%d started" % \
(self.table_name, low, high), verbose=3)
self.recIDs_in_mem.append([low, high])
query = """SELECT id_bibr... | TMP FUT: add TMP to memory and del FUT from memory
flush (revert to old state)
TMP : very bad things have happened: warn!
| FUT: very bad things have happended: warn!
"""
state = {}
query = "SELECT id_bibrec,type FROM %sR WHERE id_bibrec BETWEEN %%s AND %%s"\
% self.table_name[:-1]
res = run_sql(query, (low, high))
for row in res:
if row[0] not in state:
... |
ef assertNotValid(value):
self.assertFalse(validator.validate(value))
with self.assertRaises(ValidationError):
validator(value)
assertValid('1 * 3 ** 5')
assertValid('a * b ** c')
assertValid('x * y ** z')
assertNotValid('*')
assertNotVali... | ('Mixed_Case_With_Underscores')
assertNotValid('123_variable')
assertNotValid('z%.# +ç@')
assertNotValid('UPPER-CASE-WITH-DASHES')
assertNotValid('lower-case-with-dashes')
assertNotValid('Mixed-Case-With-Dashes')
def test_phone_number(self):
validator = PhoneNumberVa... | )
validator(value)
def assertNotValid(value):
self.assertFalse(validator.validate(value))
with self.assertRaises(ValidationError):
validator(value)
assertValid('+9-999-999-9999')
assertValid('999-999-999-9999')
assertValid('999 999 99... |
#!/usr/bin/env python
"""Setup file for HT-BAC Tools.
"""
__author__ = "Ole Weidner"
__email__ = "ole.weidner@rutgers.edu"
__copyright__ = "Copyright 2014, The RADICAL Project at Rutgers"
__license__ = "MIT"
""" Setup script. Used by easy_install and pip. """
import os
import sys
import subprocess
from s... | 'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Utilities',
'Topic :: System :: Distributed Computing',
'Operating System :: MacOS :: MacOS X',
'Op | erating System :: POSIX',
'Operating System :: Unix'
],
#'entry_points': {
# 'console_scripts':
# ['htbac-fecalc = radical.ensemblemd.htbac.bin.fecalc:main',
# 'htbac-sim = radical.ensemblemd.htbac.bin.sim:main']
#},
#'dependency_links': ['https://gith... |
n object representing the master course key id
Returns:
bool: whether or not all the course module strings belong to the master course
"""
course_chapters = get_course_chapters(master_course_key)
if course_chapters is None:
return False
return set(course_module_list).intersection(se... | ter+block@week4",
"block-v1:Organization+EX101+RUN-FALL2099+type@chapter+block@week5"
]
}
"""
authentication_classes = (OAuth2Authentication, SessionAuthentication,)
permission_classes = (IsAuthenticated, permissions.IsMasterCourseStaffInstructor)
| serializer_class = CCXCourseSerializer
pagination_class = CCXAPIPagination
def get(self, request):
"""
Gets a list of CCX Courses for a given Master Course.
Additional parameters are allowed for pagination purposes.
Args:
request (Request): Django request object.... |
# Copyright (c) 2017, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
from mixbox import entities
from mixbox import fields
import cybox.bindings.win_service_object as win_serv | ice_binding
from cybox.common import HashList
from cybox.objects.win_process_object import WinProcess
from cybox.common import ObjectProperties, String
class ServiceDescriptionList(entities.EntityList):
_binding = win_service_bin | ding
_binding_class = win_service_binding.ServiceDescriptionListType
_namespace = "http://cybox.mitre.org/objects#WinServiceObject-2"
description = fields.TypedField("Description", String, multiple=True)
class WinService(WinProcess):
_binding = win_service_binding
_binding_class = win_service_bin... |
import cPickle
import os
import tarfile
import PIL.Image
from downloader import DataDownloader
class Cifar100Downloader(DataDownloader):
"""
See details about the CIFAR100 dataset here:
http://www.cs.toronto.edu/~kriz/cifar.html
"""
def urlList(self):
return [
'http://www.... | t 'Extracting images file=%s ...' % input_file
# Read the pickle file
with open(input_file, 'rb') as infile:
pickleObj = cPickle.load(infile)
# print 'Batch -', pickleObj['batch_label']
data = pickleObj['data']
assert d | ata.shape[1] == 3072, 'Unexpected data.shape %s' % (data.shape,)
count = data.shape[0]
fine_labels = pickleObj['fine_labels']
assert len(fine_labels) == count, 'Expected len(fine_labels) to be %d, not %d' % (count, len(fine_labels))
coarse_labels = pickleObj['coarse_label... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2008 - 2012 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/... | press or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# usage: %prog | file [ file [ file [...]]]
# This script merges the timing data from several files into a single
# aggregate which is sent to stdout.
class stamp:
def __init__(this, time, weight):
this.time = long(time)
this.weight = long(weight)
def weighted_time(this):
return this.time * this.weigh... |
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib | import auth
admin.autodiscover()
import templog.urls
import control.urls
from thermoctrl import views
urlpatterns = [
# Examples:
# url(r'^$', 'thermoctrl.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', views.index, name='index'),
url(r'^admin/', include(admin.site.u... | url(r'^log/', include(templog.urls), name='log'),
url(r'^control/', include(control.urls), name='control'),
url(r'^login/', auth.views.login, {"SSL": True, "template_name": "main/login.html"}, name='login'),
]
|
# -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2017 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | #
#########################################################################
import logging
from django.utils.translation import ugettext_noop as _
from django.conf import settings
from functools import wraps
from six import string_types
from geonode.notifications_helper import NotificationsAppConfigBase, has_notifica... | _setup_hooks(*args, **kwargs):
if not has_notifications:
log.warning("Monitoring requires notifications app to be enabled. "
"Otherwise, no notifications will be send")
from geonode.monitoring.models import populate
populate()
class MonitoringAppConfig(NotificationsAppConfigBas... |
item_callback_based_on_type(item, type_, j, next_page_item=None):
# First try to populate label
if 'label' in j:
item.label = j['label']
elif 'title' in j:
item.label = j['title']
else:
item.label = 'No title'
if 'description' in j:
item.info['plot'] = j['description... | m)
return True
return False
def populate_images(item, images):
all_images = {}
for image in images:
if 'type' in image:
type_ = image['type']
if type_ == 'carre':
all_images['carre'] = image['urls']['w:400']
elif type_ == 'vignette_16x9'... | == 'background_16x9':
all_images['background_16x9'] = image['urls']['w:2500']
elif type_ == 'vignette_3x4':
all_images['vignette_3x4'] = image['urls']['w:1024']
if 'vignette_3x4' in all_images:
item.art['thumb'] = item.art['landscape'] = all_images['vignette_3x4... |
riations[i], self.variations[i + 1]
def remove_variation(self, move):
"""Removes a variation by move."""
self.variations.remove(self.variation(move))
def add_variation(self, move, comment="", starting_comment="", nags=()):
"""Creates a child node with the given attributes."""
n... | = "*"
self.errors = []
def board(self, _cache=False):
"""
Gets the starting position of the game.
Unless the `SetUp` and `FEN` header tags are set this is the default
starting position.
"""
chess960 = self.headers.get("Variant", "").lower() == "chess960"
... | from chess.variant import find_variant
VariantBoard = find_variant(self.headers["Variant"])
fen = self.headers.get("FEN") if self.headers.get("SetUp", "1") == "1" else None
board = VariantBoard(fen or VariantBoard.starting_fen, chess960)
board.chess960 = board.chess960 or bo... |
##############################################################################
# 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... | e 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 PARTI | CULAR 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##... |
# coding: utf-8
"""
Server API
Reference for Server API (REST/Json)
| OpenAPI spec version: 2.0.6
Gen | erated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import kinow_client
from kinow_client.rest import ApiException
from kinow_client.models.subtitle_file import SubtitleFile
class TestSubtitleFile(unittest.TestCase):
"""... |
"""
Trends library module.
"""
import datetime
from lib import database as db
from lib.twitter_api import authentication
# Global object to be used as api connection. During execution of the insert
# function, this can be setup once with default app then reused later,
# to avoid time calling Twitter API. It can be l... | skip the default behaviour of generating
and using an app-authorised connection.
:param delete: Boolean, default False. If set to True, delete item after
it is inserted into db. This is useful for testing.
:param verbose: Print details for each tre | nd added.
"""
global appApi
now = datetime.datetime.now()
print(f"{now.strftime('%x %X')} Inserting trend data for WOEID {woeid}")
assert isinstance(
woeid, int
), f"Expected WOEID as type `int` but got type `{type(woeid).__name__}`."
if userApi:
# Use user token.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.