prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
"""Graph debug results dumping class.""" import os import json import tvm GRAPH_DUMP_FILE_NAME = '_tvmdbg_graph_dump.json' class DebugResult(object): """Graph debug data module. Data dump module manage all the debug data formatting. Output data and input graphs are formatted and dumped to file. Front...
ut_list.append(self._nodes_list[input_node[0]]['name']) node['inputs'] = input_list dtype = str("type: " + self._dtype_list[1][i]) if 'attrs' not in node: node['attrs'] = {} node['op'] = "param" else: node['op'] = node['attr...
] node['attrs'].update({"T": dtype}) node['shape'] = self._shapes_list[1][i] def _cleanup_tensors(self): """Remove the tensor dump file (graph wont be removed) """ for filename in os.listdir(self._dump_path): if os.path.isfile(filename) and not filename.e...
import sys import os import pandas as pd import multiprocessing as mp import csv # this code is written for the merged file with combined pval & fdr. although it could have been written for the file without comb fisher and fdr, # it is easier to have the output with the comb pval and fdr and use what we need rather t...
hich (analysis) columns to use header_line = '' with open(infile, 'r') as f: header_line = f.readline().strip() selcted_cols = [i for i, s in enumerate(header_line.split(',')) if analysis in s] #[s for s in header_line.split(',') if analysis in s] # get the lowest and highest and make range out of it # this way y...
s = range(min(selcted_cols), max(selcted_cols)+1) selcted_cols.insert(0, 0) # explicitly adding the row id cols print selcted_cols header_for_print = [header_line.split(',')[i] for i in selcted_cols] print header_for_print def process(df): res = list() for row in df.itertuples(): #print row ...
#!/usr/bin/python3 import os import urllib import socket from gi.repository import GObject, Nautilus class ownCloudExtension(GObject.GObject, Nautilus.ColumnProvider, Nautilus.InfoProvider): nautilusVFSFile_table = {} registered_paths = {} remainder = '' connected = False watch_id = 0 d...
) > 0: data = self.remainder+data self.rema
inder = '' if len(data) > 0: # remember the remainder for next round lastNL = data.rfind('\n'); if lastNL > -1 and lastNL < len(data): self.remainder = data[lastNL+1:] data = data[:lastNL] for l in data.split('\n'): self.handle_server_response( l ) else: return Fa...
""" PyroScope - Controller "torrent". Copyright (c) 2009 The PyroScope Project <pyroscope.project@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 L...
LAR PURPOSE. See the GNU General Public License for more details. You should have received a co
py 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. """ import logging from pylons import request, response, session, tmpl_context as c from pylons.controllers.util import abort, redirect...
# 24.05.2007, c # last revision: 25.02.2008 from sfepy import data_dir from sfepy.fem.periodic import * filename_mesh = data_dir + '/meshes/2d/special/channels_symm944t.mesh' if filename_mesh.find( 'symm' ): region_1 = { 'name' : 'Y1', 'select' : """elements of group 3""", } region_2 = { ...
elements of group
4) +n (elements of group 1 *n elements of group 4) +n (elements of group 7 *n elements of group 6) +n (elements of group 2 *n elements of group 6) +n ...
#!/usr/bin/env python from datetime import date import os import re SRC_DIR = 'src/main/java/' ABSTRACT = re.compile(r'public abstract class Abstract') TYPE = re.compile(r'class [A-Za-z0-9]+(<[^>]+?(?: extends ([A-Za-z0-9_]+))?>)?') TARGET = re.compile(r'\s[A-Z][A-Za-z0-9_]+<[A-Z][A-Za-z0-9_]+(?:<.+?>)?, (([A-Z][A-...
= re.compile(r'import (?:static )?((?:com\.google\.)?android\..*?);') ASSERTIONS = 'Assertions.java' projects = [] for candidate in filter(os.path.isdir, os.listdir('.')): if candidate.startswith('assertj-android'): projects.append(candidate) print('Projects: %s\n' % projects) def _fin
d_assertions(path): for root, dirs, files in os.walk(path): if ASSERTIONS in files: return os.path.join(root, ASSERTIONS) raise Exception('Could not locate Assertions.java in %s.' % path) for project in projects: src_dir = os.path.join(project, SRC_DIR) assertions_file = _find_assertions(src_dir) ...
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-03-01 09:32 from __future__ import unicode_literals import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("modelview", "0009_auto_20160301_1030")] operations = [ mig...
io", name="tools_models", field=models.ForeignKey( help_text="Which model(s) and other tools have been used?", null=True, on_delete=django.db.models.deletion.CASCADE, to="modelview.Energymodel", verbose_name="Tools",...
), ) ]
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # 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 applicab...
stack being updated) existing_snippet = self.existing_snippets[existing_res.name] new_snippet = self.existing_stack.resolve_runtime_data(new_res.t) prev_res = self.previous_stack.get(new_res.name) return existing_res.update(new_snippet, existing_snippet
, prev_resource=prev_res) @scheduler.wrappertask def _process_existing_resource_update(self, existing_res): res_name = existing_res.name if res_name in self.previous_stack: yield self._remove_backup_resource(self.previous_stack[res_name]) ...
""" USA-specific Form helpers """ from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select, EMPTY_VALUES from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ import re phone_digits_re = re.compile(r'^(?:1-?)?(\d{3})[-\.]?(\d{...
in the promotional block 987-65-43
20 through 987-65-4329, which are permanently invalid. * The number is not one known to be invalid due to otherwise widespread promotional use or distribution (e.g., the Woolworth's number or the 1962 promotional number). """ default_error_messages = { 'invalid': _(...
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2015-12-19 18:47 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('judge', '0018_django_1_9'), ] operations = [ migrations.AddField( ...
field=models.CharField(default=b'', help_text='', max_length=150, verbose_name=b'OpenGraph image'), ),
migrations.AddField( model_name='contest', name='og_image', field=models.CharField(default=b'', help_text='', max_length=150, verbose_name=b'OpenGraph image'), ), ]
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst # # Astropy documentation build configuration file. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this file. # # All configurati...
p.py build_sphinx" is used). # Thus, any C-extensions that are needed to build the documentation will *not* # be accessible, and the documentation will not build correctly. import datetime import os import sys try: from sphinx_astropy.conf.v1 import * # noqa except ImportError: print('ERROR: the documentatio...
ires the sphinx-astropy package to be installed') sys.exit(1) # Get configuration information from setup.cfg try: from ConfigParser import ConfigParser except ImportError: from configparser import ConfigParser conf = ConfigParser() conf.read([os.path.join(os.path.dirname(__file__), '..', 'setup.cfg')]) se...
from __future__ import absolute_import, division, print_function import ast from jaspyx.ast_util import ast_load, ast_call from jaspyx.visitor import BaseVisitor class BinOp(BaseVisitor): def visit_BinOp(self, node): attr = getattr(self, 'BinOp_%s' % node.op.__class__.__name__, None) attr(node.lef...
in { 'Add': '+', 'Sub': '-', 'Mult': '*', 'Div': '/',
'Mod': '%', 'BitAnd': '&', 'BitOr': '|', 'BitXor': '^', 'LShift': '<<', 'RShift': '>>', }.items(): def gen_op(op): def f_op(self, left, right): self.group([left, op, right]) return f_op exec('BinOp_%s = gen_op("%s")' % ...
age": "sql" } }, { "name": "dep", "class": "org.apache.zeppelin.spark.DepInterpreter", "defaultInterpreter": false, "editor": { "language": "scala" } }, { "name": "pyspark", "class": "org.apache.z...
tInterpreter": false, "editor": { "language": "python", "editOnDblClick": false } }, { "name": "pyspark3", "class": "org.apache.zeppelin.livy.LivyPySpark3Inte
rpreter", "defaultInterpreter": false, "editor": { "language": "python", "editOnDblClick": false } }, { "name": "sparkr", "class": "org.apache.zeppelin.livy.LivySparkRInterpreter", "defaultInterpreter": false, ...
e must also match it. Raises RuntimeError if output capturing was never one for this test. """ check_msg_func = self._GenCheckMsgFunc(OutputCapturer.WARNING_MSG_RE, regexp) return self._AssertOutputEndsInMsg(check_msg_func, ...
p in reversed(self._patchers)] + [mock.patch.stopall]) def StartPatcher(self, patcher): """Call start() on the patcher, and stop() in tearDown.""" m = patcher.start() self._patchers.append(patcher) return m def PatchOb
ject(self, *args, **kwargs): """Create and start a mock.patch.object(). stop() will be called automatically during tearDown. """ return self.StartPatcher(mock.patch.object(*args, **kwargs)) # MockTestCase must be before TempDirTestCase in this inheritance order, # because MockTestCase.StartPatcher() ...
import sys import math as ma import numpy as np params = ["$\\varepsilon_{sph}$ & ", "$q$ & ", "$\\varepsilon$ & ", "$\mu$ & ", "R & ", "$\\theta$ & ", "$\phi$ &", " $\sigma$ & ", "$\\varepsilon$ & ", "$\mu$ & ", "R & ", "$\\theta$ & ", "$\phi$ & ", "$\sigma$ & ", "$\\varepsilon$ & ", "$\mu$ & ", "R & ", "$\\theta$ & ...
1}{|c}{" + a[2] + "} " placeholder[8-i] = "& \multicolumn{1}{|c}{---}" if count == 2: a[8] = "\multicolumn{1}{|c}{" + a[8] + "}" placeholder[14-i] = "& \multicolumn{1}{|c}{---}" if count == 3: a[14] = "\multicolumn{1}{|c}{" + a[14] + "}" #print str(a[:i]).replace('[', '').rep...
int params[i-1] + str(a[:i]).replace('[', '').replace(',', ' &').replace("'",'').replace(']', ' ') + str(placeholder).replace('[', '').replace(',', '').replace("'",'').replace(']', '\\\\')
from setuptools import setup setup( name="SULI", packages=['SULI'], version='0.0.1', description="SULI project", author='Kelin Kurzer-Ogul', author_email='kelin.kurzerogul@gmail.com',
url='https://github.com/k340/SULI', keywords=['SULI', 'Fermi', 'LAT', 'transients'], classifiers=[],
install_requires=['numpy','astropy'], )
import os from itertools import imap from multiprocessing import Pool from config import config from document_topic import Document, Topic class Collection(object): def __init__(self, list_file, prefix=''):
self.names_list = [os.path.join(prefix, file_name.strip()) for file_name in list_file] def __iter__(self): pool = Pool(mi
n(config.workers,len(self.names_list))) return pool.imap(self.type, self.names_list) #return imap(self.type, self.names_list) class TopicCollection(Collection): type = Topic class DocumentCollection(Collection): type = Document
# Copyright 2014 Google Inc. All rights reserved. # Licensed u
nder 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 perm...
""" Various tests for class members access. """ # pylint: disable=R0903,print-statement,no-absolute-import, metaclass-assignment,import-error,no-init,missing-docstring, wrong-import-order,wrong-import-position from missing import Missing class MyClass(object): """class docstring""" def __init__(self): ...
etaclass__ = Metaclass #TestMetaclass.register(int) #UsingMetacla
ss.test() TestMetaclass().register(int) # [no-member] UsingMetaclass().test() # [no-member] class NoKnownBases(Missing): """Don't emit no-member if we don't know the bases of a class.""" NoKnownBases().lalala() # Should be enabled on astroid > 1.4.0 #class MetaClass(object): # """Look some methods in the imp...
# This python module is part of the oocs scanner for Linux. # Copyright (C) 2015 Davide Madrisan <davide.madrisan.gmail.com> import glob from os import sep from os.path import join from pwd import getpwuid from oocs.filesystem import Filesystems, UnixCommand, UnixFile from oocs.io import Config, message_add, quote, u...
for uid in self.uid():
owners.append(getpwuid(int(uid)).pw_name) return owners def threads(self): threads_num = 0 for pid in self.pid(): threads_num += int(self.fullstatus.get(pid)['threads'][0]) return threads_num def check_services(verbose=False): services = Services(verbose=verbose...
import zeit.newsletter.testing class MetadataTest(zeit.newsletter.testing.SeleniumTestCase): def test_form_should_save_entered_data_on_blur(self): s = self.selenium self.open('/repository/newsletter/@@checkout') s.waitForElementPresent('id=metadata
.subject') s.assertValue('id=metadata.subject', '') s.type('id=metadata.subject', 'flubber\t') s.waitForElementNotPresent('css=.field.dirty') # Re-open the page and verify that the data is still there s.clickAndWait('link=Edit contents') s.waitForElementPresent('id=metada...
.assertValue('id=metadata.subject', 'flubber')
""" ==================================================================== Linear and Quadratic Discriminant Analysis with confidence ellipsoid ==================================================================== Plot the confidence ellipsoids of each class and decision boundary """ print(__doc__) from scipy import lin...
d, fig_index): splot = plt.subplot(2, 2, fig_index) if fig_index == 1: plt.title('Linear Discriminant Analysis') plt.ylabel('Data with fixed covariance') elif fig_index == 2: plt.title('Quadratic Discriminant Analysis') elif fig_index == 3: plt.ylabel('Data with varying c...
== y_pred) # True Positive tp0, tp1 = tp[y == 0], tp[y == 1] X0, X1 = X[y == 0], X[y == 1] X0_tp, X0_fp = X0[tp0], X0[~tp0] X1_tp, X1_fp = X1[tp1], X1[~tp1] xmin, xmax = X[:, 0].min(), X[:, 0].max() ymin, ymax = X[:, 1].min(), X[:, 1].max() # class 0: dots plt.plot(X0_tp[:, 0], X0_tp[:...
num_points_delta': 800, 'hdawg_ch0_amplitude': 1.0, 'hdawg_ch1_amplitude': 1.0, 'hdawg_ch2_amplitude': 0.8, 'hdawg_ch3_amplitude': 0.8, 'hdawg_ch4_amplitude': 1.0, 'hdawg_ch5_amplitude': 1.0, ...
witch('rf_switch', address=self.device_settings['rf_switch_address']) self.sa = Agilent_N9030A('pxa', address=self.device_settings['sa_address']) self.hdawg = Zurich_HDAWG180
8(self.device_settings['hdawg_address']) self.dummy_awg = dummy_awg.DummyAWG(channels=1) self.coil_device = self.hdawg self.adc_device = TSW14J56_evm() self.adc_device.timeout = self.device_settings['adc_timeout'] self.adc = TSW14J56_evm_reducer(self.adc_device) self.adc...
the License, or # (at your option) any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have ...
], disk=module.params['disk'], flavorid=module.params[
'flavorid'], ephemeral=module.params['ephemeral'], swap=module.params['swap'], rxtx_factor=module.params['rxtx_factor'], is_public=module.params['is_public'] ) changed=True else: c...
from .. utils import TranspileTestCase, BuiltinFunctionTestCase class InputTests(TranspileTestCase): pass # FIXME: This test can't run without a redirecti
on for stdin. # class BuiltinInputFunctionTests(BuiltinFunctionTestCase, TranspileTestCase): # functions = ["input"] # not_implemented = [ #
'test_bool', # 'test_bytearray', # 'test_bytes', # 'test_class', # 'test_complex', # 'test_dict', # 'test_float', # 'test_frozenset', # 'test_int', # 'test_list', # 'test_None', # 'test_NotImplemented', # 'test_set'...
# -*- coding: utf-8 -*- """ """ import logging import logging.handlers import sys STANDARD_FORMAT = '%(name)s [%(levelname)s] %(message)s' MESSAGE_ONLY_FORMAT = '%(message)s' def get_level(level_string): """ Returns an appropriate logging level integer from a string name """ levels = {'debug': loggi...
encoding='utf-8', mode=mode) if level is None: handler.setLevel(logging.WARNING) else: handler.setLevel(get_level(level)) if filtr is not None: handler.addFilter(logging.Filter(filtr)) if fr...
er.setFormatter(logging.Formatter(STANDARD_FORMAT)) else: handler.setFormatter(logging.Formatter(frmt)) log.addHandler(handler) #def deactivate_logging(): #log = logging.getLogger('npyscreen2')
# Copyright (C) 2008-2012 Chris Ball <cjb@laptop.org> # Gianluca Montecchi <gian@grys.it> # W. Trevor King <wking@tremily.us> # # This file is part of Bugs Everywhere. # # Bugs Everywhere is free software: you can redistribute it and/or modify it # under the terms of the ...
>>> dummy.time = 2 >>> ret = ui.run(cmd
, args=['/a', '/b']) Merged bugs #abc/a# and #abc/b# >>> bd.flush_reload() >>> a = bd.bug_from_uuid('a') >>> a.load_comments() >>> a_comments = sorted([c for c in a.comments()], ... cmp=libbe.comment.cmp_time) >>> mergeA = a_comments[0] >>> mergeA.time = 3 >>> pri...
HttpResponse from django.template import loader import random import string #import user from .forms import UserForm from stack_configs.stack_functions import createInfluxDB from stack_configs.ldap_functions import addToLDAPGroup,resetLDAPpassword,createLDAPuser from stack_configs.grafana_functions import GrafanaUser,...
ters() @never_cache def zibawa_password_reset_confirm(request, uidb64=None, tok
en=None, template_name='registration/password_reset_confirm.html', token_generator=default_token_generator, set_password_form=SetPasswordForm, post_reset_redirect=None, extra_context=No...
from __future__ import ( unicode_literals, absolute_import, division, print_function, ) # Make Py2's str type like Py3's str = type('') # Rules that take into account part of speech to alter text structure_rules = [ ((["JJ*","NN*"],), (["chuffing",0,1],), 0.1), ((["."],),...
,"joyful","joyous","jubilant","lively","merry","overjoyed", "peaceful","pleasant","pleased","thrilled","upbeat","blessed", "blest","blissful","captivated","gleeful","gratified","jolly", "mirthful","playful","proud",), ("chuffed","buzzin'")), (("things","stuff","elements",...
",)), (("attractive","alluring","beautiful","charming","engaging","enticing", "glamorous","gorgeous","handsome","inviting","tempting","adorable", "agreeable","enchanting","enthralling","hunky","pretty","seductive", "provocative","tantalizing","teasing","stunning",), ("fit...
########################################################################## # # Copyright (c) 2015, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistrib...
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ####################
###################################################### import Gaffer import GafferTest class ApplicationTest( GafferTest.TestCase ) : def testTaskSchedulerInitDoesntSuppressExceptions( self ) : def f() : import Gaffer._Gaffer as _Gaffer with _Gaffer._tbb_task_scheduler_init( _Gaffer._tbb_task_scheduler_in...
#
-*- coding: utf-8 -*- from __future__ import unicode_literals from django.apps import AppConfig class ConsultantformConfig(AppConfig): name = 'consultantform'
cla
ss Runt
imeValidationError(Exception): pass
"""Provides the constants needed for com
ponent.""" from typing import Final SUPPORT_ALARM_ARM_HOME: Final = 1 SUPPORT_ALARM_ARM_AWAY: Final = 2 SUPPORT_ALARM_ARM_NIGHT: Final = 4 SUPPORT_AL
ARM_TRIGGER: Final = 8 SUPPORT_ALARM_ARM_CUSTOM_BYPASS: Final = 16 SUPPORT_ALARM_ARM_VACATION: Final = 32 CONDITION_TRIGGERED: Final = "is_triggered" CONDITION_DISARMED: Final = "is_disarmed" CONDITION_ARMED_HOME: Final = "is_armed_home" CONDITION_ARMED_AWAY: Final = "is_armed_away" CONDITION_ARMED_NIGHT: Final = "is_...
# -*
- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.core.urlresolvers import reverse from django.views.generic import DetailView, ListView,
RedirectView, UpdateView from django.contrib.auth.mixins import LoginRequiredMixin from .models import User class UserDetailView(LoginRequiredMixin, DetailView): model = User # These next two lines tell the view to index lookups by username slug_field = "username" slug_url_kwarg = "username" clas...
# This file is part of fedmsg. # Copyright (C) 2012 Red Hat, Inc. # # fedmsg 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 Foundation; either # version 2.1 of the License, or (at your option) any later version. #...
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #
# Authors: Ralph Bean <rbean@redhat.com> #
#!/usr/bin/python # System of three linear equations # ax + by + cz = j # dx + ey + fz = k # gx + hy + iz = l # System of three linear equations in matrix notation # - - - - - - # | a b c | | x | | j | # | | | | | | # | d e f | | y | = | k | # | | | | |...
x['k'] * y_numerator_matrix['i'] + y_numerator_matrix['j'] * y_numerator_matrix['f'] * y_numerator_matrix['g'] + y_numerator_matrix['c'] * y_numerator_matrix['d'] * y_numerator_matrix['l'] - y_numerator_matrix['g'] * y_numerator_matrix['k'] * y_numerator_matrix['c'] - y_numerator_matrix['l'] * y_numerator_matri...
# Rule of Sarrus for det_z_numerator_matrix # a b j|a b # d e k|d e # g h l|g h # det_z_numerator_matrix = (z_numerator_matrix['a'] * z_numerator_matrix['e'] * z_numerator_matrix['l'] + z_numerator_matrix['b'] * z_numerator_matrix['k'] * z_numerator_matrix['g'] + z_numerator_matrix['j'] * z_numerator_mat...
# -*- coding: utf-8
-*- # This software may be modified and distributed under the terms # of the BSD license. See the LICENSE file for details. from aniso8601 import compat class DateResolution(object): Year, Month, Week, Weekday, Day, Ordinal = list(compat.range(6)) class TimeResolution(object): Seconds, Minutes, Hours = lis...
3))
attributes and items:: def _object_getattr(obj, field): # check whether this key is an attribute if hasattr(obj, field): value = getattr(obj, field) # if not, perhaps it is an item (raw dicts, etc) elif field in obj: value = obj[...
d self.op == other.op def __ne__(self, other): return not self.__eq__(other) def __hash__(self): return hash(repr(self)) def isAscending(self): return self.op == '+' def isDescending(self): return not self.isAscending() def keyfn(self, obj): """A key func...
self.field) @classmethod def multipleOrderComparison(cls, orders): """Returns a function that will compare two items according to `orders`""" comparers = [(o.keyfn, 1 if o.isAscending() else -1) for o in orders] def cmpfn(a, b): for keyfn, ascOrDesc in comparers: ...
"decodebin", connectToOutput=rtsp, connectWhenAvailable="audio", async_handling=True) self.addElement("audioconvert") self.addElement("audiorate") self.addElement("voaacenc") self.addElement("aacparse") self.mp3src = self.addElemen...
y: self.addElement("omxh264enc", interval_intraframes=int( (self.config.get('device.fps', '4') or '4'))) except Exception: self.addElement("x264enc", tune="zerolatency", rc_lookahead=0, bitrate=int(self.dev.config['device.bi...
", caps="video/x-h264, profile=main") self.addElement("h264parse") self.h264source = self.addElement("tee") # Tested # rtspsrc location=rtsp://192.168.1.6:8080/h264_pcm.sdp latency=100 ! queue ! rtph264depay ! h264parse return s import iot_devices.device as devices ...
def
main(): a1="X" TextOut(10, LCD_LI
NE1, a1)
# # Copyright (c) 2017 Intel Corporation # # 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 t...
== 'N-Step': # N-Step Q learning if batch.game_overs()[-1]: R = 0 else: R = np.max(self.networks['main'].target_network.predict(last_sample(batch.next_states(network_keys)))) for i in reversed(range(batch.size)): R = batch....
assert True, 'The available values for targets_horizon are: 1-Step, N-Step' # add Q value samples for logging self.q_values.add_sample(state_value_head_targets) # train result = self.networks['main'].online_network.accumulate_gradients(batch.states(network_keys), [state_value_head_targ...
from pycp2k.inputsection import InputSection class _each438(InputSection): def __init__(self): InputSection.__init__(self) self.Just_energy = None self.Powell_opt = None self.Qs_scf = None self.Xas_scf = None self.Md = None self.Pint = None self.Meta...
'GEO_OPT', 'Spline_find_coeffs': 'SPLINE_FIND_COEFFS', 'Powell_opt': 'POWELL_OPT'
, 'Qs_scf': 'QS_SCF', 'Ep_lin_solver': 'EP_LIN_SOLVER'}
# 2015.09.05 18:13:46 ora legale Europa occidentale # Embedded file name: b.py from a import x def x(): print 'b' x() from a import x x() # okay decompyling C:\Users\nicola user\wotmods\files\originals\tests\
overriding\b.pyc # decompiled 1 files: 1
okay, 0 failed, 0 verify failed # 2015.09.05 18:13:46 ora legale Europa occidentale
) class BinarySensorSchema: """Voluptuous schema for KNX binary sensors.""" CONF_STATE_ADDRESS = CONF_STATE_ADDRESS CONF_SYNC_STATE = CONF_SYNC_STATE CONF_IGNORE_INTERNAL_STATE = "ignore_internal_state" CONF_AUTOMATION = "automation" CONF_HOOK = "hook" CONF_DEFAULT_HOOK = "on" CONF_...
E_ADDRESS): cv.string, vol.Optional(CONF_MIN_KELVIN, default=DEFAULT_MIN_KELVIN): vol.All( vol.Co
erce(int), vol.Range(min=1) ), vol.Optional(CONF_MAX_KELVIN, default=DEFAULT_MAX_KELVIN): vol.All( vol.Coerce(int), vol.Range(min=1) ), } ) class ClimateSchema: """Voluptuous schema for KNX climate devices.""" CONF_SETPOINT_SHIFT_ADDRESS = "setp...
from networkx.al
gorithms.flow.maxflow import * from networkx.algorithms.flow
.mincost import *
# -*- coding: utf-8 -*- # # Clawpack documentation build configuration file, created by # sphinx-quickstart on Wed Mar 25 12:07:14 2009. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickle...
ensions.append('sphinx.ext.jsmath') extensions.append('s
phinx.ext.pngmath') # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8' # The master toctree document. master_doc = 'index' # General information ...
from dj
ango.forms import HiddenInput from .base import WidgetTest class HiddenInputTest(WidgetTest): widget = HiddenInput() def test_render(self): self.check_html(self.widget, 'email', '', html='<input type="hidden" name="email" />') def test_use_required_attribute(self): # Always False to avo...
(''), False) self.assertIs(self.widget.use_required_attribute('foo'), False)
################################################################################ # # # Folding@Home Client Control (FAHControl) # # Copyright (C) 2016-2020 foldingathome.org ...
self.execute('DROP TABLE IF EXISTS projects') self.set_current_version(self.get_version()
) self.commit()
# -*- coding: utf-8 -*- """ Written by Daniel M. Aukes and CONTRIBUTORS Email: danaukes<at>asu.edu. Please see LICENSE for full license. """ import sys import popupcad import qt.QtCore as qc import qt.QtGui as qg i
f __name__=='__main__': app = qg.QApplication(sys.argv[0]) filename_from = 'C:/Users/danaukes/Dropbox/zhis sentinal 11 files/modified/sentinal 11 manufacturing_R08.cad' filename_to = 'C:/Users/danaukes/Dropbox/zhis sentinal 11 files/modified/sentinal 11 manufacturing_R09.cad' d = popupcad...
layout = qg.QVBoxLayout() layout1 = qg.QHBoxLayout() layout2 = qg.QHBoxLayout() list1 = qg.QListWidget() list2 = qg.QListWidget() button_ok = qg.QPushButton('Ok') button_cancel = qg.QPushButton('Cancel') subdesign_list = list(d.subdesigns.values()) for item in subdesign_li...
# -*- coding: utf-8 -*- """Create an application instan
ce.""" from flask.helpers import get_debug_flag from myflaskapp.app import create_app from myflaskapp.settings import DevConfig, ProdConfig CONFIG = DevConfig if get_de
bug_flag() else ProdConfig app = create_app(CONFIG)
df_monthl
y = df.resample('M').sum() df_monthly.plo
t()
import copy from fmiapi.fmixmlparser import FMIxmlParser from tests.testUtils import * from tests.fmiapi.testdata.expected_data import * def describe_fmi_xml_parser(): parser = FMIxmlParser() def describe_daily_data(): test_data1 = load_xml('./tests/fmiapi/testdata/daily_12_days.xml') test_da...
def should_parse_multipart_request_correctly(): result = parser.parse([test_data1, test_data2, test_data3]) assert_equal(30, len(result['time'])) # concat three different dicts to one df
expected_df = copy.deepcopy(EXPECTED_DAILY_12_DAYS) for key in EXPECTED_DAILY_4_DAYS: expected_df[key] = expected_df[key] + EXPECTED_DAILY_4_DAYS[key] for key in EXPECTED_DAILY_14_DAYS: expected_df[key] = expected_df[key] + EXPECTED_DAILY_14_DAYS[key] ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.18 on 2019
-02-06 21:49 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('zerver', '0206_stream_rendered_description'), ] operations = [ migrations.AddField( model_name='multiuseinvite', ...
d(default=1), ), ]
# -*- coding: utf-8 -*- # Config file handling module # Copyright (C) 2014 Yury Gavrilov <yuriy@igavrilov.ru> # This file is part of VKBuddy. # VKBuddy 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...
at your option) any later version. # VKBuddy 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 PA
RTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with VKBuddy. If not, see <http://www.gnu.org/licenses/>. import yaml class IncorrectConfig(Exception): pass class BareConfig: def __init__(self): sel...
# -*- coding: utf-8 -*- """ werkzeug ~~~~~~~~ Werkzeug is the Swiss Army knife of Python web development. It provides useful classes and functions for any WSGI application to make the life of a python web developer much easier. All of the provided classes are independent from each other so yo...
loaded at # once, even if unused. # # The implementation of a lazy-loading module in this file replaces the # werkzeug package when imported from within. Attribute access to the werkzeug # module will then lazily import from the modules that implement the objects. # import mapping to objects in other modules all_by_...
dApplication'], 'werkzeug.local': ['Local', 'LocalManager', 'LocalProxy', 'LocalStack', 'release_local'], 'werkzeug.templates': ['Template'], 'werkzeug.serving': ['run_simple'], 'werkzeug.test': ['Client', 'EnvironBuilder', 'create_environ', ...
nit__() self.host_name = host_name class RomanaAnyAddressRequest(ipam_req.AnyAddressRequest): """Used to request any available address from the pool.""" def __init__(self, host_name, tenant_id, segment_name): """Initialize RomanaAnyAddressRequest.""" super(ipam_req.AnyAddressReques...
constants.IPv6: '::'} def __init__(self, tenant_id, subnet_id, version, prefixlen, gateway_ip=None, allocation_pools=None):
"""Initialize RomanaAnySubnetRequest. :param version: Either constants.IPv4 or constants.IPv6 :param prefixlen: The prefix len requested. Must be within the min and max allowed. :type prefixlen: int """ super(RomanaAnySubnetRequest, self).__init__( ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings # noqa from django.utils.translation import uget
text_lazy as _
# noqa from appconf import AppConf class BlogConf(AppConf): DISQUS_SHORTNAME = 'django-staticgen' POST_IDENTIFIER = 'current_post' class Meta: prefix = 'blog'
"""Functional
ity for
determining logic satisfiasbility."""
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agr
eements. 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 file exc
ept 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, ei...
import os import argparse import datetime import yaml import api.src.common.initial_environment_config from ..models.dense import create_model from ..data_processing.data_generator import DataGenerator from ..common.config import TrainingConfig, DataConfig, Config from ..common.utils import print_info, ensure_dir from...
.join(TrainingConfig.PATHS['MODELS'], RUNNING_TIME, 'weights.h5'), save_best_only=True, monitor=TrainingConfig.callbacks_monitor), CSVLogger(os.path.join(Training
Config.PATHS['MODELS'], RUNNING_TIME, 'history.csv')), LearningRateScheduler(TrainingConfig.schedule), EarlyStopping(patience=5) ]if not Config.NO_SAVE else [] if not Config.NO_SAVE: introduced_change = input("What new was introduced?: ") with open(os.path.join(TrainingConfig.PA...
# Copyright (c) 2014 - 2016 townhallpinball.org # # 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, copy, modify, merge, p...
center = ui.Text(bottom=0, font="bm3") self.display.add((self.player, self.players[0], self.players[1], self.players[2], self.players[3], self.ball, self.credits_right, self.credits_center)) self.handler.on("data_credits", self.update) self
.handler.on("add_player", self.update) self.handler.on("next_player", self.next_player) self.handler.on("player_score", self.score) self.update() def next_player(self): self.initial = True self.update() def score(self): self.initial = False self.update()...
import numpy as np import scipy.optimize from scipy.signal import lombscargle import batman import ctools import matplotlib.pyplot as plt def periodogram(time, data, periods): freq = 1/periods nfactor = 2/(data.size * np.var(data)) power = nfactor * lombscargle(time, data-np.mean(data), freq*2*np.pi) ...
avg_spacing stop = time_range periods = np.arange(start, stop, avg_spacing) phase_dispersion = ctools.phase_dispersion(time, flux, periods) power = periodogram(time, flux, periods) period = 25.0 time %= period inds =
np.argsort(time, kind='mergesort') time = time[inds] flux = flux[inds] flux /= np.median(flux) # Data must be normalized to use the rp parameter in_transit = flux < 1-(1-flux.min())/2 # Estimate planet radius fro mthe transit depth planet_radius = np.sqrt(1-np.median(flux[in_transit])) ...
import numpy as np import pandas as pd import pytest ROWID_ZERO_INDEXED_BACKENDS = ('omniscidb',) @pytest.mark.parametrize( 'column', [ 'string_col', 'double_col', 'date_string_col', pytest.param('timestamp_col', marks=pytest.mark.skip(reason='hangs')), ], ) @pytest.mark.x...
name='number', ) pd.testing.assert_series_equal(result.iloc[:, 0], expec
ted)
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # @Author: Adrien Chardon # @Date: 2014-11-16 14:29:10 # @Last Modified by: Adrien Chardon # @Last Modified time: 2014-11-16 16:31:32 import time as t ################################################################################ # Usefull functions ###################...
id-1] # Return all childs nodes that can be directly accessed from the node def getChildOfNode(data, node): ret = [] for dic in data: if dic['start'] == node: ret.append(dic['end']) re
turn ret # return the time for traveling directly from node1 to node 2 def getDist(data, node1, node2): for dic in data: if (dic['start'] == node1) and (dic['end'] == node2): return dic['time'] return infinity ##############################################################################...
: (c) 2014 by the FlaskBB Team. :license: BSD, see LICENSE for more details. """ import sys from flask import (Blueprint, current_app, request, redirect, url_for, flash, jsonify, __version__ as flask_version) from flask_login import current_user, login_fresh from flask_plugins import get_all_plu...
oup from flaskbb.management.forms import (AddUserForm, EditUserForm, AddGroupForm,
EditGroupForm, EditForumForm, AddForumForm, CategoryForm) management = Blueprint("management", __name__) @management.before_request def check_fresh_login(): """Checks if the login is fresh for the current user, otherwise the user has to reauthenticate.""...
from classytags.helpers import InclusionTag from django import template from django.conf import settings from django.template.loader import render_to_string register = template.Library() class Banner(InclusionTag): """ Displays
a checkout mode banner. """ template = 'sagepay/checkout_mode_banner.html' def render_tag(self, context, **kwargs): template = self.get_template(context, **kwargs) if settings.SAGEPAY_MODE == "Live": return '' data = self.get_context(context, **kwargs) return re...
er.tag(Banner)
= dict(required=False, type='bool'), alias_hosted_zone_id = dict(required=False), alias_evaluate_target_health = dict(required=False, type='bool', default=False), value
= dict(required=False),
overwrite = dict(required=False, type='bool'), retry_interval = dict(required=False, default=500), private_zone = dict(required=False, type='bool', default=False), identifier = dict(required=False, defaul...
def load_config(default_values, user_values): if user_values is None: return default_values config = {} for k, v in user_values.items(): if k in default_values: if isinstance(v, dict): cloned = user_values[k].copy()
for key, value in default_values[k].items(): if key is not None and key no
t in user_values[k] \ or user_values[k][key] == '': cloned[key] = value config[k] = cloned else: config[k] = v else: config[k] = v for k, v in default_values.items(): if k not in config: c...
from django.conf import settings from django.conf.urls import static from django.urls import include, path, re_path from django.contrib import admin urlpatterns = [ path(r"admin/", admin.site.urls), path(r"flickr/", include("ditto.flickr.urls")), path(r"lastfm/", include("ditto.lastfm.urls")), path(r"...
ls")), ] if settings.DEBUG: import debug_toolbar urlpatterns += [ re_path(r"^__debug__/", include(debug_toolbar.urls)), ] urlpatterns += static.sta
tic(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static.static( settings.STATIC_URL, document_root=settings.STATIC_ROOT )
, {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_join...
c': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'name': ('django.db.models.fields.CharF
ield', [], {'default': "u''", 'max_length': '255', 'blank': 'True'}), 'original_filename': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'owned_fil...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Stub functions that are used by the Amazon Pinpoint unit tests. When tests are run against an actual AWS account, the stubber class does not set up stubs and passes all calls through to the Boto 3 client. ""...
'OriginationNumber': origination_number}}}} response = {'MessageResponse': { 'ApplicationId': app_id, 'Result': { destination_number: { 'DeliveryStatus': 'SUCCESSFUL', 'StatusCode': 200, 'Messag...
ge( self, app_id, origination_number, destination_number, message_type, template_name, template_version, message_id, error_code=None): expected_params = { 'ApplicationId': app_id, 'MessageRequest': { 'Addresses': {destination_number: {'ChannelType'...
# -*- coding: utf-8 -*- from django.test import Client from django.urls import reverse from nmkapp impor
t views from .n
mk_unit_test_case import NmkUnitTestCase class ResultsTests(NmkUnitTestCase): def test_anon_user(self): """ Test result view with anonymous user """ self.client = Client() response = self.client.get(reverse(views.results)) self.assertEqual(response.status_code, 302)...
# -*- coding: utf-8 -*- # Copyright 2016 Acsone SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': 'Account Invoice Check Total', 'summary': """ Check if the verification total is equal to the bill's total""", 'version': '10.0.1.0.0', 'license': 'AGPL-3', 'author': 'Acsone SA/NV,Odoo Community Association (OCA)', ...
rity.xml', 'views/account_invoice.xml', ], }
# -*- coding: utf-8 -*- """forms""" import floppyforms.__future__ as floppyforms class HidableM
ultipleChoiceField(floppyforms.MultipleChoiceField): """ The MultipleChoiceField doesn't return an <input type="hidden"> when hidden but an empty string Overload this field to restore an <input type="hidden"> """ hidden_widget = floppyforms.HiddenInput
#!/usr/bin/env python
from pylab import * fig = figure() subplot(221) imshow(rand(100,100)) subplot(222) imshow(rand(100,100)) subplot(223
) imshow(rand(100,100)) subplot(224) imshow(rand(100,100)) subplot_tool() show()
#!/usr/bin/env python import unittest import os.path import sys import time sys.path.insert(0, os.path.join(os.path.abspath(os.path.dirname(__file__)), "..")) import base from PyQt4.QtTest import QTest from enki.core.core import core class Test(base.TestCase): def _verifyText(self, fileName, text): w...
File('file2.rb', 'fdsa') self.keyClick('Ctrl+Enter') self.keyClicks('new text') self.openDialog(lambda: self.keyClick('Ctrl+Shift+W'), lambda dialog: self.keyClick('w')) self.assertIsNone(core.workspace().currentDocument()) self._verifyText('file2.rb', ...
f.keyClick('Ctrl+Enter') self.keyClicks('new text') self.openDialog(lambda: self.keyClick('Ctrl+Shift+W'), lambda dialog: self.keyClick('c')) self.assertIsNotNone(core.workspace().currentDocument()) @base.inMainLoop def test_4(self): # Close all, save ...
# encoding: utf8 from django.db import models, migrations class Migration(migrations.Migration): dependencies = [("podcasts", "0005_auto_20140610_1854")] operations = [ migrations.AlterField(
model_name="episode", name="outdated", field=models.BooleanField(default=False, db_index=True), ), migrations.AlterField(
model_name="podcast", name="outdated", field=models.BooleanField(default=False, db_index=True), ), migrations.AlterField( model_name="episode", name="guid", field=models.CharField(max_length=100, null=True), ), ]
''' Generic message-based protocol used by Bitcoin and P2Pool for P2P communication ''' import hashlib import struct from twisted.internet import protocol from twisted.python import log import p2pool from p2pool.bitcoin import data as bitcoin_data from p2pool.util import datachunker, variable class TooLong(Exceptio...
necting', False): handler(**payload2) def disconnect(self): if hasattr(self.transport, 'abortConnection'): # Available since Twisted 11.1 self.transport.abortConnection
() else: # This doesn't always close timed out connections! warned about in main self.transport.loseConnection() def badPeerHappened(self): self.disconnect() def sendPacket(self, command, payload2): if len(command) >= 12: raise ValueError('co...
from django.db.models import Q from import_export.admin import ImportExportModelAdmin from models import Vote, Law, PrivateProposal, KnessetProposal, GovProposal, Bill, GovLegislationCommitteeDecision from laws.management.commands.scrape_votes import Command as ScrapeVotesCommand from django.utils.translation import u...
e__', 'short_summary', 'full_text_link', 'votes_count', 'for_votes_count', 'against_votes_count', 'abstain_votes_count') search_fields = ('title', 'summary', 'full_text', 'id', 'src_id') list_filter = (MissingDataVotesFilter, ) def update_vote(self, request, queryset): vote_count = queryse...
te_vote.short_description = 'update vote properties and calculations' def recreate_vote(self, request, queryset): recreated_votes = ScrapeVotesCommand().recreate_objects(queryset.values_list('pk', flat=True)) recreated_vote_ids_string = ', '.join([str(v.pk) for v in recreated_votes]) self.m...
"""MNE software for MEG and EEG data analysis.""" # PEP0440 compatible formatted version, see: # https://www.python.org/dev/peps/pep-0440/ # # Generic release markers: # X.Y # X.Y.Z # For bugfix releases # # Admissible pre-release markers: # X.YaN # Alpha release # X.YbN # Beta release # X.YrcN # Rele...
grade_to_tris, spatial_src_adjacency, spatial_tris_adjacency,
spatial_dist_adjacency, spatial_inter_hemi_adjacency, spatio_temporal_src_adjacency, spatio_temporal_tris_adjacency, spatio_temporal_dist_adjacency, extract_label_time...
# subsystemBonusGallentePropulsion2Agility # # Used by: # Su
bsystem: Proteus Propulsion - Hyperspatial Optimization type = "passive" def handler(fit, src, context): fit.ship.boostItemAttr("agility", src.getModifiedItemAttr("subsystemBonusGallentePropulsion2"), skill="Gallente Propu
lsion Systems")
import numpy as np vec_bitstring_3 = np.vectorize(lambda x: np.binary_repr(x,widt
h=3) ) def board_to_int(v): t = vec_bitstring_3(v) return int(''.join(np.apply_along_axis(lambda x: ''.join(x), 1,t)),2) def int_to_board(i): #i = '154444257952488798331863040' s = bin(int(i))[2:].zfill(108) v = np.array([int(s[i:i+3],2) for i in range(0,len(s),3)],dtype=int) return v.reshape...
6))
# -*- coding: ut
f-8 -*- # Generated by Django 1.10.3 on 2017-03-07 02:03 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [
('medgointranet', '0012_motivoanulacion'), ] operations = [ migrations.AddField( model_name='atencion', name='formulario', field=models.BooleanField(default=False, verbose_name='¿Doctor completo formulario?'), ), ]
import logging from datetime import timedelta from core import Feed from core.errors import ObservableValidationError from core.observables import Ip class AlienVaultIPReputation(Feed): default_values = { "frequency": timedelta(hours=4), "name": "AlienVaultIPReputation", "source": "http:/...
header=None, names=[ "IP", "number_1
", "number_2", "Tag", "Country", "City", "Coord", "number_3", ], ): self.analyze(line) def analyze(self, item): try: context = dict(source=self.name) ip_...
lf.ctrl.ItemCount(), 37) def testGetItem(self): "Test the ItemCount method" self.assertRaises(RuntimeError, self.ctrl.GetItem, "test\here\please") self.assertRaises(IndexError, self.ctrl.GetItem, r"\test\here\please") self.assertEquals( self.ctrl.GetItem((0, 1, 2)).T...
rops: self.assertEquals(getattr(self.ctrl, prop_name)(), props[prop_name]) def testItemCount(self): self.assertEquals(3, self.ctrl.ItemCount()) def testGetColumnRectangle(self): for i in range(0, 3): self.assertEquals( self.item_rects[i], ...
s = self.item_rects test_rects.insert(0, self.ctrl.ClientRect()) self.assertEquals( test_rects, self.ctrl.ClientRects()) def testGetColumnText(self): for i in range(0, 3): self.assertEquals( self.texts[i], self.ctrl.GetCol...
from rest_framework import status from test_utils import serialized_time def test_get_profile_topics( api_client, enable_premium_requirement, profile_topic_factory, user_factory ): """ Premium users should be able to list their own profile topics. """ password = "password" user = user_factory...
rialized_time(topic.created_at), "updated_at": serialized_time(topic.updated_at),
"is_detailed": topic.is_detailed, "items_url": api_client.build_full_url( f"/know-me/profile/profile-topics/{topic.pk}/items/" ), "name": topic.name, "permissions": {"read": True, "write": True}, "profile_id": topic.profile.pk, ...
# Copyright (c) Facebook, Inc. and its affiliates. # # 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 ...
col.TSimpleJSONProtocol(trans) obj.write(proto) r
eturn trans.getvalue() def readStructFromJSON(jstr, struct_type): stuff = struct_type() trans = TMemoryBuffer(jstr) proto = TSimpleJSONProtocol.TSimpleJSONProtocol(trans, struct_type.thrift_spec) stuff.read(proto) return stuff class TestSortKeys(unittest.TestCase): def testSorted(self): ...
0. self.z = math_ops.multiply(self.x, self.y, name="z") # Should be -4.0. self.sess = session.Session() self.sess.run(variables.global_variables_initializer()) self.sess = session.Session() self.sess.run(variables.global_variables_initializer()) def tearDown(self): ops.reset_default_graph...
andle. self.assertEqual(["c:0"], stepper.handle_names()) self.assertSetEqual({"c"}, stepper.handle_node_names()) # Override c:0. stepper.override_tensor("c:0", 7.0) # The overriding should have invalidated the tensor handle. self.assertEqual([], stepper.handle_names()) self.assertSetEqual(...
) self.assertAllClose(28.0, result) # Should reflect the overriding value. self.assertEqual({ "c:0": NodeStepper.FEED_TYPE_OVERRIDE }, stepper.last_feed_types()) # The handle to tensor e:0 should have been cached, even though its # transitive closure contains an override. self.assertIn...
pinds[0], epinds[-1] + 1)) return inds def linear_interp_basis(toas, dt=30 * 86400): """Provides a basis for linear interpolation. :param toas: Pulsar TOAs in seconds :param dt: Linear interpolation step size in seconds. :returns: Linear interpolation basis and nodes """ # evenly spaced...
n.""" if np.all(pos1 == pos2): return 1 + 1e-5 else: return np.dot(pos1, pos2) @function def monopole_orf(pos1, pos2): """Monopole spatial correlation function.""" if np.all(pos1 == pos2): return 1.0 + 1e-5 else:
return 1.0 @function def anis_orf(pos1, pos2, params, **kwargs): """Anisotropic GWB spatial correlation function.""" anis_basis = kwargs["anis_basis"] psrs_pos = kwargs["psrs_pos"] lmax = kwargs["lmax"] psr1_index = [ii for ii in range(len(psrs_pos)) if np.all(psrs_pos[ii] == pos1)][0] psr2...
one) # If there are no unique fields on the model, return false if not django_opts.unique_together and not any(x.unique for x in django_opts.fields): return False opts = getattr(model_or_instance, "Djangae", None) if opts: if hasat
tr(opts, "disable_constraint_checks"): if opts.disable_constraint_checks: return False else: return True return not getattr(settings, "DJANGAE_DISABLE_CONSTRA
INT_CHECKS", False) class KeyProperty(db.Property): """A property that stores a datastore.Key reference to another object. Think of this as a Django GenericForeignKey which returns only the PK value, not the whole object, or a db.ReferenceProperty which can point to any model kind, and only return...
# 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 ...
romote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ boTAB ===== This solver uses the popular TAB model to simulate the atomization of droplets Author: Adam O'Brien """ from input import * from math import exp, cos, sin, sqrt from fluid import * from evaporation import * from TAB import * from output import * impor...
the break-up of a drop in a uniform cross-flow", "\n" # Open up a configuration file userInput = readInputFile() freestream = Freestream() initialDroplet = Droplet() dropletInlet = DropletInlet() # Set object parameters from the input file setObjectParametersFromInput(userInput, freest...
nitialize a droplet list, with one copy of the initial droplet droplets = [cp.deepcopy(initialDroplet)] # Initialize misc parameters dt = maxTime/nTimeSteps t = [0.] nChildDroplets = 0 # Begin the simulation print "\nBeginning time-stepping..." #####################################...
#!/usr/bin/env python # -*- coding: utf-8 -*- ##################################################################### # Author: Cristian Segura L. # # Email: cristian+dot+segura+dot+lepe+arroba+dot+gmail+dot+com # # Creation Date: Sat nov 8 20:11:38 CLST 2014 ...
nt "* *" print "* Downloading LIBPRI *" print "*
*" print "*****************************************************" print "[+]downloading file: %s using wget" % ( lPriTgzFile ) print "" subprocess.call( ["wget", lPriDownPath] ) print "" print "*****************************************************" print "* ...
import factory from questionnaire.models impor
t Theme class ThemeFactory(factory.DjangoModelFactory): class Meta: model = Theme
name = "A title" description = 'Description'
#!/usr/bin/env python from server import Serve from utils import get_authenticated_user import
os import sys authenticated_user = None try: authenticated_user = get_authenticated_user('server.cfg') except IOError: print ("File 'server.cfg' doesn't exist on disk. Please ensure that it" " does and try again.") sys.exit(1) except ValueError: print ("'server.cfg' is empty. Please run 'p...
_, authenticated_user)
#! /usr/bin/p
ython class Indexer: def __getitem__(self, index): return index ** 2 x = Indexer() for i in range(5):
print x[i], class Stepper: def __getitem__(self, index): return self.data[index] s = Stepper() s.data = "spam" for x in s: print x, print s.data[0]
DEBUG = True USE_TZ = True DATABASES = { 'default':
{ 'ENGINE': 'django.db.backends.sqlite3', } } INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'custom_user', 'test_custom_user_s
ubclass', ] SECRET_KEY = 'not_random' AUTH_USER_MODEL = 'test_custom_user_subclass.MyCustomEmailUser'
#----------------------------------------------------- # # Find the next prime number as the user
keeps asking # #----------------------------------------------------- import sys #------------------------ # is the number a prime? #------------------------ def is_prime( num ): for i in range( 2, num ): if num % i == 0: retu
rn False if num != 1: return True else: return False #-------------------- # main #-------------------- if __name__ == "__main__": curr_prime = 1 #initialize the prime number while True: response = raw_input( "Print the next prime? [Y]es " ) if response.upper().startswith('Y'): while True: cur...
"""Views for the monitoring app.""" from django.contrib.auth.decorators import login_required from django.db.models import Count from django.http import Http404 from django.utils.decorators impor
t method_decorator from django.views.generic import ListView, TemplateView from .register import monitor class MonitoringViewMixin(object): """Helper methods that all monitoring base views need.""" view_name = None monitor_titl
e = None @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): # pragma: no cover if not request.user.is_staff: raise Http404 self.request = request self.monitor_name = request.GET.get('monitor') return super(MonitoringViewMixin, self).disp...
""" Page classes to test either the Course Team page or the Library Team page. """ from bok_choy.promise import EmptyPromise from bok_choy.page_object import PageObject from ...tests.helpers import disable_animations from . import BASE_URL def wait_for_ajax_or_reload(browser): """ Wait for all ajax requests t...
l.get_attribute('data-email')) ).results @property def has_add_button(self): """ Is the "New Team Member" button present? """ return self.q(css='.create-user-button').present def click_add_butto
n(self): """ Click on the "New Team Member" button """ self.q(css='.create-user-button').click() @property def new_user_form_visible(self): """ Is the new user form visible? """ return self.q(css='.form-create.create-user .user-email-input').visible def set_...