repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
brouberol/pynlg
pynlg/lexicon/lang.py
Python
mit
118
0
# encoding:
utf-8 """
Definition of supported languages""" ENGLISH = 'english' FRENCH = 'french' DEFAULT = 'english'
olivetree123/memory_profiler
test/test_import.py
Python
bsd-3-clause
179
0.005587
from memory_profiler import profile @profile def my_func(): a = [1] * (10 ** 6) b = [2] * (2 * 10 ** 7) del b return a if __name
__ == '__main__': my_func()
Eric89GXL/vispy
vispy/app/backends/_osmesa.py
Python
bsd-3-clause
7,645
0
# -*- coding: utf-8 -*- # vispy: testskip # Copyright (c) Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. """ OSMesa backend for offscreen rendering on Linux/Unix """ from __future__ import division from ...util.ptime import time from ..base import ...
gl.glFinish() def _vispy_set_title(self, title): pass def _vispy_set_size(self, w, h): self._pixels = osmesa.allocate_pixels_buffer(w, h) self._size = (w, h) self._vispy_canvas.events.resize(size=(w, h)) self._vispy_set_current() self._vispy_update() de...
set_visible(self, visible): if visible: self._vispy_set_current() self._vispy_update() def _vispy_set_fullscreen(self, fullscreen): pass def _vispy_update(self): # This is checked by osmesa ApplicationBackend in process_events self._needs_draw = True ...
gvnn3/PCS
pcs/packets/igmp.py
Python
bsd-3-clause
3,526
0.011344
import pcs from socket import AF_INET, inet_ntop import struct import time import pcs.packets.ipv4 import pcs.packets.igmpv2 as igmpv2 import pcs.packets.igmpv3 as igmpv3 #import pcs.packets.dvmrp #import pcs.packets.mtrace IGMP_HOST_MEMBERSHIP_QUERY = 0x11 IGMP_v1_HOST_MEMBERSHIP_REPORT = 0x12 IGMP_DVMRP = 0x13 IGM...
gmpv2, IGMP_v1_HOST_MEMBERSHIP_REPORT: igmpv2.igmpv2, #IGMP_DVMRP: dvmrp.dvmrp, IGMP_v2_HOST_MEMBERSHIP_REPORT: igmpv2.igmpv2, IGMP_HOST_LEAVE_MESSAGE: igmpv2.igmpv2, #IGMP_MTRACE_REPLY: mtrace.reply, #IGMP_MTRACE_QUERY: mtrace.query, IGMP_v3_HOST_MEMBERSHIP_REPORT: igmpv3.report } descr = { IGMP_HOST_MEMB...
T_MEMBERSHIP_REPORT: "IGMPv1 Report", IGMP_DVMRP: "DVMRP", IGMP_v2_HOST_MEMBERSHIP_REPORT: "IGMPv2 Report", IGMP_HOST_LEAVE_MESSAGE: "IGMPv2 Leave", IGMP_MTRACE_REPLY: "MTRACE Reply", IGMP_MTRACE_QUERY: "MTRACE Query", IGMP_v3_HOST_MEMBERSHIP_REPORT: "IGMPv3 Report" } class igmp(pcs.Packet): """IGMP""" ...
dingmingliu/quanttrade
quanttrade/core/data.py
Python
apache-2.0
350
0.025714
__author__ = 'bett' import MySQLdb as db import pandas.io.sql as psql from config import db_config def getData(symbols,start,
end): databa
se = db.connect(**db_config) data=psql.frame_query("SELECT * FROM tbl_historical where start", database) return data; if(__name__=='__main__'): getData('000009.sz','2013-1-1','2015-4-8')
calamityman/ansible-modules-extras
network/openvswitch_bridge.py
Python
gpl-3.0
8,748
0.000572
#!/usr/bin/python #coding: utf-8 -*- # (c) 2013, David Stygstra <david.stygstra@gmail.com> # # Portions copyright @ 2015 VMware, Inc. # # This file is part of Ansible # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Fre...
e.exit_json(changed=changed) def run(self): '''Make the necessary changes''' changed = False # pylint: disable=W0703 try: if self.state == 'abse
nt': if self.exists(): self.delete() changed = True elif self.state == 'present': if not self.exists(): self.add() changed = True current_fail_mode = self.get_fail_mode() ...
delicb/SublimeConfig
tailf.py
Python
mit
3,015
0
import os import io import stat import time import threading import sublime import sublime_plugin # Set of IDs of view that are being monitored. TAILF_VIEWS = set() STATUS_KEY = 'tailf' class TailF(sublime_plugin.TextCommand): ''' Start monitoring file in `tail -f` line style. ''' def __init__(self...
new_mod_time > self.prev_mod_time or new_size != self.prev_file_size): self.view.run_command('update_file') self.view.run_command('move_to', args={'to': 'eof', 'extend': False})
self.prev_file_size = new_size self.prev_mod_time = new_mod_time time.sleep(self.view.settings().get('tailf_pull_rate')) else: return def description(self): return 'Starts monitoring file on disk' class StopTailF(sublime_plugin.TextComman...
chris-martin/chain-bitcoin-python
chain_bitcoin/tests/test_get_block_op_returns_by_height.py
Python
mit
1,761
0
from __future__ import absolute_import import sure from .. import Chain, NoApiKeyId, OpReturn, get_block_op_returns_by_height from .mock_http_adapter import * def test_get_block_op_returns_by_height(): get_block_op_returns_by_height(block_height, api_key_id=api_key_id, http_ada...
.should.equal(op_returns) def test_get_block_op_returns_by_height_using_class(): Chain(api_key_id=api_key_id, http_adapter=http_adapter) \ .get_block_op_returns_by_height(block_height).should.equal(op_returns) def test_get_block_op_returns_by_height_without_api_key_id(): (lambda: get_block_op_r...
http_adapter=no_http())) \ .should.throw(NoApiKeyId) block_height = 308920 api_key_id = 'DEMO-4a5e1e4' url = 'https://api.chain.com/v1/bitcoin/blocks/308920/op-returns' \ '?api-key-id=DEMO-4a5e1e4' response_body = """ [ { "transaction_hash":"ac88...", "hex":"4067...", "text":"Yo A...
mlds-lab/egk
demo.py
Python
mit
1,643
0
import numpy as np import cPickle as pickle from sklearn.svm import LinearSVC import gp from full_marginal import compute_means_covs from fastfood import FastfoodEGK def main(): np.random.seed(111) with open('data/ECG200-50.pkl', 'rb') as f: ts_train, ts_test, l_train, l_test = pickle.load(f) # E...
normalize=True) clf = LinearSVC(C=100) X_train = rp.fit_transform(train_means, train_covs) clf.fit(X_train, l_train) X_test = rp.transform(test_means, test_covs) l_predict = clf.predict(X_test) accuracy = np
.mean(l_predict == l_test) print accuracy if __name__ == '__main__': main()
LegNeato/bztools
bugzilla/models.py
Python
bsd-3-clause
6,168
0.000811
from remoteobjects import RemoteObject as RemoteObject_, fields from .fields import StringBoolean, Datetime # The datetime format is inconsistent. DATETIME_FORMAT_WITH_SECONDS = '%Y-%m-%d %H:%M:%S %z' DATETIME_FORMAT = '%Y-%m-%d %H:%M %Z' class RemoteObject(RemoteObject_): def post_to(self, url): self...
set_location) class Bug(RemoteObject): id = fields.Field() summary = fields.Field() assigned_to = fields.Object('User') reporter = fields.Object('User') target_milestone = fields.Field() attachments = fields.List(fields.Object('Attachment')) comments = fields.List(fields.Object('Comment'))...
lds.Field() # TODO: These are Mozilla specific and should be generalized cf_blocking_20 = fields.Field() cf_blocking_fennec = fields.Field() cf_crash_signature = fields.Field() creation_time = Datetime(DATETIME_FORMAT_WITH_SECONDS) flags = fields.List(fields.Object('Flag')) blocks = fields...
keisuke-umezawa/chainer
chainer/link_hooks/spectral_normalization.py
Python
mit
11,583
0
import numpy import chainer from chainer import backend from chainer import configuration import chainer.functions as F from chainer import link_hook import chainer.links as L from chainer import variable import chainerx from chainerx import _fallback_workarounds as fallback def l2normalize(xp, v, eps): """Norma...
f self.use_gamma: del link.gamma def forward_preprocess(self, cb_args): # This method normalizes target link's weight spectrally # using power iteration method link = c
b_args.link input_variable = cb_args.args[0] if not self._initialized: self._prepare_parameters(link, input_variable) weight = getattr(link, self.weight_name) # For link.W or equivalents to be chainer.Parameter # consistently to users, this hook maintains a reference ...
ruibarreira/linuxtrail
usr/lib/python2.7/unittest/loader.py
Python
gpl-3.0
13,465
0.002005
"""Loading unittests.""" import os import re import sys import traceback import types from functools import cmp_to_key as _CmpToKey from fnmatch import fnmatch from . import case, suite __unittest = True # what about .pyc or .pyo (etc) # we would need to avoid loading the same tests multiple times # from '.py', '....
bspath(start_dir)
): start_dir = os.path.abspath(start_dir) if start_dir != top_level_dir: is_not_importable = not os.path.isfile(os.path.join(start_dir, '__init__.py')) else: # support for discovery from dotted module names try: __import__(start_dir...
opennode/nodeconductor-assembly-waldur
src/waldur_jira/migrations/0003_project_template.py
Python
mit
1,946
0.001028
# Generated by Django 1.11.7 on 2017-12-13 09:18 import django.db.models.deletion from django.db import migrations, models import waldur_core.core.fields import waldur_core.core.models import waldur_core.core.validators class Migration(migrations.Migration): dependencies = [ ('waldur_jira', '0002_resour...
': Fal
se,}, bases=(waldur_core.core.models.BackendModelMixin, models.Model), ), migrations.AddField( model_name='project', name='template', field=models.ForeignKey( default=None, on_delete=django.db.models.deletion.CASCADE, ...
Shopify/shopify_python_api
shopify/resources/gift_card_adjustment.py
Python
mit
193
0
from ..base import ShopifyResource class GiftC
ardAdjustment(ShopifyResource): _prefix_source = "/admin/gift_cards/$gift_card_id/" _plural = "adjustments" _singular = "adjustment"
danakj/chromium
third_party/WebKit/Tools/Scripts/webkitpy/performance_tests/perftest.py
Python
bsd-3-clause
12,942
0.002859
# Copyright (C) 2012 Google Inc. All rights reserved. # Copyright (C) 2012 Zoltan Horvath, Adobe Systems Incorporated. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of ...
return re.sub(r'\.\w+$', '', self.test_name()) def test_path(self): return self._test_path def description(self): return self._description def _create_driver(self): return self._port.create_driver(worker_number=0, no_timeout=True) def run(self, time_out_ms): f...
driver = self._create_driver() try: if not self._run_with_driver(driver, time_out_ms): return None finally: driver.stop() should_log = not self._port.get_option('profile') if should_log and self._description: ...
sacharya/nova
nova/tests/api/openstack/compute/contrib/test_server_start_stop.py
Python
apache-2.0
4,710
0.001274
# Copyright (c) 2012 Midokura Japan K.K. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with th
e 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 expre...
import server_start_stop from nova.compute import api as compute_api from nova import db from nova import exception from nova import test from nova.tests.api.openstack import fakes def fake_instance_get(context, instance_id, columns_to_join=None, use_slave=False): result = fakes.stub_instan...
idaholab/raven
framework/SupervisedLearning/ScikitLearn/LinearModel/LassoLarsIC.py
Python
apache-2.0
6,386
0.008926
# Copyright 2017 Battelle Energy Alliance, LLC # # 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...
---------------- #Internal Modules (Lazy Importer) End-------------------------------------------------------
--------- #External Modules------------------------------------------------------------------------------------ from numpy import finfo #External Modules End-------------------------------------------------------------------------------- #Internal Modules---------------------------------------------------------------...
khushboo9293/postorius
src/postorius/views/settings.py
Python
gpl-3.0
4,486
0
# -*- coding: utf-8 -*- # Copyright (C) 1998-2015 by the Free Software Foundation, Inc. # # This file is part of Postorius. # # Postorius is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the...
new.html', {'form': form, 'message': message}, context_instance=RequestContext(request)) def domain_delete(request, domain): """Deletes a domain but asks for confirmation first. """ if request.method == 'POST': try: client = u...
nt.delete_domain(domain) messages.success(request, _('The domain %s has been deleted.' % domain)) return redirect("domain_index") except HTTPError as e: print e.__dict__ messages.error(request, _('The domain could not be deleted:' ...
iniweb/deployCD
manage.py
Python
mit
266
0.003759
#!env/bin/python from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from app import app, db migrate = Migrate(app, db) manager
= Manager(app) manager.add_command('db', MigrateCommand) if __name__ == '__m
ain__': manager.run()
napalm-automation/napalm-yang
napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/isis/global_/lsp_bit/overload_bit/__init__.py
Python
apache-2.0
25,678
0.001675
# -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListTy...
efining_module='openconfig-network-instance', yang_type='container', is_config=True)""", } ) self.__config = t if hasattr(self, "_set"): self._set() def _unset_config(self): self.__confi
g = YANGDynClass( base=config.config, is_container="container", yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace="http:/...
Aravinthu/odoo
addons/account/tests/account_test_classes.py
Python
agpl-3.0
2,749
0.003638
# -*- coding: utf-8 -*- from odoo.tests.common import HttpCase from odoo.exceptions import ValidationError class AccountingTestCase(HttpCase): """ This class extends the base TransactionCase, in order to test the accounting with localization setups. It is configured to run the tests after the installation ...
le) :param property_name: The name of the property. ''' company_id = self.env.user.company_id field_id = self.env['ir.model.fields'].search( [('model', '=', 'product.template'), ('name', '=', property_name)], limit=1) property_id = self.env['ir.property'].search([ ...
d), ('name', '=', property_name), ('res_id', '=', None), ('fields_id', '=', field_id.id)], limit=1) account_id = self.env['account.account'].search([('company_id', '=', company_id.id)], limit=1) value_reference = 'account.account,%d' % account_id.id if propert...
torshid/foodnow
server.py
Python
gpl-3.0
2,035
0.009337
import datetime import json import os import psycopg2 as dbapi2 import re
from werkzeug.exceptions import NotFound, Forbidden from flask import Flask, app, render_template from common import * from config import * import jinja app = Flask(__name__) # jinja-python functions @app.context_processor def processor(): functions = {} for function in jinja.__dict__.values(): if c...
"): if name.endswith(".py"): module = name[:-3] globals()[module] = __import__('entities.' + module, fromlist = ['page']) app.register_blueprint(getattr(globals()[module], 'page')) @app.errorhandler(NotFound) def error(e): return render_template('errors/' + str(e.code) + '.html'), e.cod...
ellert/doxygen
src/scan_states.py
Python
gpl-2.0
1,591
0.0044
#!/usr/bin/python # python script to generate an overview of the staes based on the input lex file. # # Copyright (C) 1997-2019 by Dimitri van Heesch. # # Permission to use, copy, modify, and distribute this software and its # documentation under the terms of the GNU General Public License is hereby # granted. No repre...
ys.argv[1] if (os.path.exists(lex_file)): #write preamble print("static const char *stateToString(int state)") print("{") print(" switch(state)") print(" {") print(" case INITIAL: return \"INITIAL\";") with open(lex_file) as f: for line in f:...
te)) elif re.search(r'^%%', line): break else: pass f.close() #write post print(" }") print(" return \"Unknown\";") print("}") if __name__ == '__main__': main()
qtux/instmatcher
tests/test_parser.py
Python
apache-2.0
21,291
0.039547
# Copyright 2016 Matthias Gazzari # # 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 writ...
ype="institution">institD</orgName> <address> <country key="AQ">Irrelevant</country> <settlement>settlement</settlement> </address> </affiliation>''' ) actual = list(parser.parseAll(__name__, self.url)) expected = [{ 'ins
titution': 'institD', 'institutionSource': 'grobid', 'alpha2': 'AQ', 'country': 'Antarctica', 'countrySource': 'grobid', 'settlement': ['settlement',], },] self.assertEqual(actual, expected) def test_parse_every_tags(self): self.server.setResponse( __name__, '''<affiliation> <orgName t...
gnulinooks/sympy
sympy/utilities/runtests.py
Python
bsd-3-clause
21,885
0.002467
""" This is our testing framework. Goals: * it should be compatible with py.test and operate very similarly (or identically) * doesn't require any external dependencies * preferably all the functionality should be in this file only * no magic, just import the test file and execute the test functions, that's it * port...
try: execfile(filename, gl) except (ImportError, SyntaxError): self._reporter.import_error(filename, sys.exc_info()) return pytestfile = "" if gl.has_key("XFAIL"): pytest
file = inspect.getsourcefile(gl["XFAIL"]) disabled = gl.get("disabled", False) if disabled: funcs = [] else: # we need to filter only those functions that begin with 'test_' # that are defined in the testing file or in the file where # is defined t...
alex-ip/geophys2netcdf
utils/set_attribute.py
Python
apache-2.0
1,500
0.003333
''' Created on Apr 7, 2016 @author: Alex Ip, Geoscience Australia ''' import sys import netCDF4 import subprocess import re from geophys2netc
df import ERS2NetCDF de
f main(): assert len( sys.argv) == 5, 'Usage: %s <root_dir> <file_template> <attribute_name> <attribute_value>' % sys.argv[0] root_dir = sys.argv[1] file_template = sys.argv[2] attribute_name = sys.argv[3] attribute_value = sys.argv[4] nc_path_list = [filename for filename in subprocess...
rfhk/awo-custom
sale_line_quant_extended/wizard/__init__.py
Python
lgpl-3.0
60
0
# -*-
co
ding: utf-8 -*- from . import stock_return_picking
DJArmstrong/autovet
FPPcalc/priorutils.py
Python
gpl-3.0
16,928
0.021148
#significant input and copied functions from T. Morton's VESPA code (all mistakes are my own) #coords -- RA and DEC of target in degrees. Needed for GAIA querying. # Degrees, 0-360 and -90 to +90. List format [RA,DEC]. import numpy as np import pandas as pd from scipy.integrate import quad from scipy import...
e to be average over all types? f_close = 1.0 implies all triples have a close binary. May be over-generous eclipse prob ''' return centroid_val * f_triple * f_close * eclipse_probability(r1, r2, P, m1, m2) def planet_prior(centro
id_val, P, r1=1.0, rp=1.0, m1=1.0, mp=0.0, f_planet=0.2957): ''' centroid pdf at source location planet occurrence (fressin, any planet<29d) eclipse prob works for defined source planets too, just use appropriate centroid pdf value. possibly needs a more general f_planet - as classifier will be ...
ThinkmanWang/NotesServer
models/Alarm.py
Python
apache-2.0
151
0.02649
class Alarm(object):
id = '' uid = 0 note_id = '' date = 0 update_date = 0 is_delet
ed = 0 #note = None()
kfwang/Glance-OVA-OVF
glance/async/taskflow_executor.py
Python
apache-2.0
5,199
0.000385
# Copyright 2015 OpenStack Foundation # 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 requ...
_) _deprecated_opt = cfg.DeprecatedOpt('eventlet_executor_pool_size', group='task') taskflow_executor_opts = [ cfg.StrOpt('engine_mode', default='parallel', choices=('serial', 'parallel'), help=_("The mode in which the engine will ru...
l'.")), cfg.IntOpt('max_workers', default=10, help=_("The number of parallel activities executed at the " "same time by the engine. The value can be greater " "than one when the engine mode is 'parallel'."), deprecated_opts=[_d...
mahandra/recipes_video_conv
rec_hls_server/check_rec_stream.py
Python
gpl-2.0
4,889
0.004909
#!/usr/bin/env python #-*- coding: utf-8 -*- import time __author__ = 'mah' __email__ = 'andrew.makhotin@gmail.com' import MySQLdb as mdb import sys import ConfigParser import logging import logging.handlers import re import os from ffprobe import FFProbe #### LOG ### logger = logging.getLogger('Logging for check_s...
1: try: main() except KeyboardInterrupt: sys.exit(0) #logger.inf
o('waiting...') time.sleep(30)
tyb0807/angr
angr/analyses/decompiler/clinic.py
Python
bsd-2-clause
5,861
0.002901
import logging import networkx from .. import Analysis, register_analysis from ...codenode import BlockNode from ..calling_convention import CallingConventionAnalysis import ailment import ailment.analyses l = logging.getLogger('angr.analyses.clinic') class Clinic(Analysis): """ A Clinic deals with AILm...
vr = self.project.analyses.VariableRecoveryFast(self.function, clinic=self, kb=self.kb) # pylint:disable=unused-variable # TODO: The current m
apping implementation is kinda hackish... for block in self._blocks.itervalues(): self._link_variables_on_block(block) def _link_variables_on_block(self, block): """ :param block: :return: """ var_man = self.kb.variables[self.function.addr] fo...
AstroMatt/esa-time-perception
backend/api_v2/migrations/0007_auto_20170101_0101.py
Python
mit
3,986
0.003512
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-01 01:01 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api_v2', '0006_remove_event_is_valid'), ] operations = [ migrations.AlterFi...
name='regularity', field=models.PositiveSmallIntegerField(help_
text='Click every X seconds', verbose_name='Regularity'), ), migrations.AlterField( model_name='trial', name='time_mean_all', field=models.DecimalField(blank=True, decimal_places=2, help_text='Time Coefficient Mean - all', max_digits=3, null=True, verbose_name='TM'), ...
donbright/piliko
examples/example05.py
Python
bsd-3-clause
1,688
0.034953
from piliko import * print print 'example 5' v1,v2 = vector(3,0),vector(0,4) print 'vectors v1, v2:', v1, v2 print ' v1 + v2, v1 - v2: ', v1 + v2, v1 - v2 print ' v1 * 5/4:', v1 * Fraction(5,4) print ' v1 perpendicular v1? ', v1.perpendicular( v1 ) print ' v1 perpendicular v2? ', v1.perpendicular( v2 ) print ' v2 perp...
v1.dot(v2) + v1.dot(v3) print ' pythagoras: Q(v1)+Q(v2)=Q(v3)?: lhs:', lhs, 'rhs:',rhs v4 = vector( -5, 0 ) v5 = 3 * v4 v6 = v5 - v4 print 'vector v4, v5, and v6=v5-v4:', v4, v5, v6 lhs = sqr( quadrance( v4 ) + quadrance( v5 ) + quadrance( v6 ) ) rhs = 2*(sqr(quadrance(v4))+sqr(quadrance(v5))+sqr(quad
rance(v6))) print ' triplequad for v4,v5,v6 : lhs:', lhs, 'rhs:',rhs print 'spread( v1, v1 ):', spread( v1, v1 ) print 'spread( v2, v1 ):', spread( v2, v1 ) print 'spread( v2, 5*v1 ):', spread( v2, 5*v1 ) print 'spread( v1, v2 ):', spread( v1, v2 ) print 'spread( v1, v3 ):', spread( v1, v3 ) print 'spread( v1, 5*v3 ):...
ofek/hatch
backend/src/hatchling/builders/plugin/hooks.py
Python
mit
229
0
from ...plugin imp
ort hookimpl from ..custom import CustomBuilder from ..sdist import SdistBuilder from ..wheel import WheelBuilder @hookimpl def hatch_register_builder(): return [CustomBuilder, SdistBuilder, Wh
eelBuilder]
miyucy/oppia
core/domain/dependency_registry_test.py
Python
apache-2.0
4,450
0
# coding: utf-8 # # Copyright 2014 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
ids() all_dependency_ids = ( widget_registry.Registry.get_deduplicated_dependency_ids( interactive_widget_ids)) self.assertNotIn('jsrepl', all_dependency_ids) # Thus, jsrepl is not loaded in the exploration reader. response = self.testapp.get('/explore/%s' % ...
ual(response.status_int, 200) response.mustcontain(no=['jsrepl']) def test_dependency_loads_in_exploration_containing_it(self): EXP_ID = '1' exp_services.load_demo(EXP_ID) # Verify that exploration 1 has a jsrepl dependency. exploration = exp_services.get_exploration_by_id...
EducationalTestingService/rsmtool
rsmtool/test_utils.py
Python
apache-2.0
66,934
0.001404
import os import re import sys import warnings from ast import literal_eval as eval from filecmp import clear_cache, dircmp from glob import glob from importlib.machinery import SourceFileLoader from inspect import getmembers, getsourcelines, isfunction from os import remove from os.path import basename, exists, join f...
should be true if the second human score column is specified. Defaults to ``False``. skll : bool, optional Whether the model being used in the experiment is a SKLL model in which case
the coefficients, predictions, etc. will not be checked since they can vary across machines, due to parameter tuning. Defaults to ``False``. file_format : str, optional Which file format is being used for the output files of the experiment. Defaults to "csv". given_test_dir : str...
dan1/horizon-proto
openstack_dashboard/api/rest/keystone.py
Python
apache-2.0
18,340
0
# Copyright 2014, Rackspace, US, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
rameters for project_id, domain_id and group_id to change that listing's context. The listing result is an object with property "items". """ domain_context = request.session.get('domain_context') filters = rest_utils.parse_filters_kwargs(request, ...
= None result = api.keystone.user_list( request, project=request.GET.get('project_id'), domain=request.GET.get('domain_id', domain_context), group=request.GET.get('group_id'), filters=filters ) return {'items': [u.to_dict() for u in re...
blckshrk/Weboob
modules/grooveshark/test.py
Python
agpl-3.0
1,879
0.001597
# -*- coding: utf-8 -*- # Copyright(C) 2013 Bezleputh # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opt...
see <http://www.gnu.org/licenses/>. from weboob.tools.test import BackendTest from weboob.capabilities.video import BaseVideo class GroovesharkTest(BackendTest): BACKEND = 'grooveshark' def test_grooveshark_video_search(self): result = list(self.backend.search_videos("Loic Lantoine")) self...
grooveshark_user_playlist(self): l1 = list(self.backend.iter_resources([BaseVideo], [u'playlists'])) assert len(l1) c = l1[0] l2 = list(self.backend.iter_resources([BaseVideo], c.split_path)) assert len(l2) v = l2[0] self.backend.fillobj(v, ('url',)) self....
pynamodb/PynamoDB
pynamodb/exceptions.py
Python
mit
4,009
0.001746
""" PynamoDB exceptions """ from typing import Any, Optional import botocore.exceptions class PynamoDBException(Exception): """ A common exception class """ def __init__(self, msg: Optional[str] = None, cause: Optional[Exception] = None) -> None: self.msg = msg self.cause = cause ...
ror(PynamoDBConnectionError): """ An error involving a dynamodb table operation """ msg = "Error performing a table operation" class DoesNotExist(PynamoDBException): """ Raised when an item queried does not exist """ msg = "Item does not exist" class TableDoesNotExist(PynamoDBExcepti...
_init__(self, table_name: str) -> None: msg = "Table does not exist: `{}`".format(table_name) super(TableDoesNotExist, self).__init__(msg) class TransactWriteError(PynamoDBException): """ Raised when a TransactWrite operation fails """ pass class TransactGetError(PynamoDBException): ...
insta-code1/ecommerce
src/products/views.py
Python
mit
3,661
0.029227
from django.contrib import messages from django.db.models import Q from django.http import Http404 from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.shortcuts import render, get_object_or_404, redirect from django.utils import timezone # Create your views he...
uctListView(ListView): model = Product queryset = Product.objects.all() def get_context_data(self, *args, **kwargs): context = super(ProductListView, self).get_context_data(*args, **kwargs) context["now"] = timezone.now() context["query"] = self.request.GET.get("q") #None return context def get_queryset(s...
(*args, **kwargs) query = self.request.GET.get("q") if query: qs = self.model.objects.filter( Q(title__icontains=query) | Q(description__icontains=query) ) try: qs2 = self.model.objects.filter( Q(price=query) ) qs = (qs | qs2).distinct() except: pass return qs import ra...
lovelylinus35/Cinnamon
files/usr/lib/cinnamon-settings/bin/XletSettings.py
Python
gpl-2.0
14,098
0.003263
#!/usr/bin/env python2 import sys try: import os import glob import gettext import json import collections import XletSettingsWidgets import dbus from SettingsWidgets import SectionBg from gi.repository import Gio, Gtk, GObject, GdkPixbuf except Exception, detail: print detail ...
n("Failed to parse settings JSON d
ata for %s %s" % (self.type, self.uuid)) instance_id = instance.split(".json")[0] self.applet_settings[instance_id] = js self.setting_factories[instance_id] = XletSettingsWidgets.Factory("%s/%s" % (path, instance), instance_id, self.multi_instance, self.uuid) ...
google/ctfscoreboard
scoreboard/config_defaults.py
Python
apache-2.0
1,499
0
# Copyright 2016 Google LLC. 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 ag...
local' MAIL_FROM = None MAIL_FROM_NAME = None MAIL_HOST = 'localhost' NE
WS_POLL_INTERVAL = 60000 PROOF_OF_WORK_BITS = 0 RULES = '/rules' SCOREBOARD_ZEROS = True SCORING = 'plain' SECRET_KEY = None TEAM_SECRET_KEY = None SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = True SQLALCHEMY_TRACK_MODIFICATIONS = True SESSION_EXPIRATION_SECONDS = 60 * ...
vinegret/youtube-dl
youtube_dl/extractor/foxnews.py
Python
unlicense
5,156
0.002715
from __future__ import unicode_literals import re from .amp import AMPIE from .common import InfoExtractor class FoxNewsIE(AMPIE): IE_NAME = 'foxnews' IE_DESC = 'Fox News and Fox Business Video' _VALID_URL = r'https?://(?P<host>video\.(?:insider\.)?fox(?:news|business)\.com)/v/(?:video-embed\.html\?vide...
er-school-shooting.amp.html?__twitter_impression=true', 'info_dict': { 'id': '5748266721001', 'ext': 'flv', 'title': 'Kyle Kashuv has a positive message for the Trump White House', 'description': 'Marjory Stoneman Douglas student disagrees with classmates.', ...
params': { 'skip_download': True, }, }, { 'url': 'http://insider.foxnews.com/2016/08/25/univ-wisconsin-student-group-pushing-silence-certain-words', 'only_matching': True, }] def _real_extract(self, url): display_id = self._match_id(url) webpage = self._d...
max00xam/service.maxxam.teamwatch
lib/socketio/asyncio_server.py
Python
gpl-3.0
24,559
0
import asyncio import engineio import six from . import asyncio_manager from . import exceptions from . import packet from . import server class AsyncServer(server.Server): """A Socket.IO server for asyncio. This class implements a fully compliant Socket.IO web server with support for websocket and lon...
``True``, event handlers are executed in separate threads. To run handlers synchronously, set to ``False``. The default is ``Tru
e``. :param kwargs: Connection parameters for the underlying Engine.IO server. The Engine.IO configuration supports the following settings: :param async_mode: The asynchronous model to use. See the Deployment section in the documentation for a description of the ...
ufo-kit/concert
concert/tests/integration/test_scan.py
Python
lgpl-3.0
4,356
0.002296
from itertools import product import numpy as np from concert.quantities import q from concert.tests import assert_almost_equal, TestCase from concert.devices.motors.dummy import LinearMotor from concert.processes.common import scan, ascan, dscan def compare_sequences(first_sequence, second_sequence, assertion): ...
stScan(TestCase): def setUp(self): super(TestScan, self).setUp() self.motor = LinearMotor() async def feedback(self): return 1 * q.dimensionless async def test_ascan(self): async def run(include_last=True): scanned = [] async for pair in ascan(self...
r) return scanned expected = [(0 * q.mm, 1 * q.dimensionless), (5 * q.mm, 1 * q.dimensionless), (10 * q.mm, 1 * q.dimensionless)] scanned = await run() compare_sequences(expected, scanned, assert_almost_equal) # Second scan, values must be same ...
sandeva/appspot
astro/birth/urls.py
Python
apache-2.0
1,038
0.003854
# Copyright 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
rt re urlpatterns = patterns(re.sub(r'[^.]*$', "views", __name__), (r'^$', 'index'), (r'^(?P<admin>admin)/(?P<user>.*?)/$', 'index'), (r'^((?P<event_key>.*?)/)?edit/$', 'edit'), (r'^(?P<ref_key>.*?)/((?P<event_key>.*?)/)?edit/event/$', 'editPureEvent'
), #(r'^(?P<location_key>\w+)/update/$', 'update'), # Uncomment this for admin: # (r'^admin/', include('django.contrib.admin.urls')), )
ga4gh/CGT
tests/populate.py
Python
apache-2.0
1,290
0.00155
import uuid import json import requests import argparse parser = argparse.ArgumentParser( description="Upload a series of test submissions with randomized ids") parser.add_argument('host', nargs='?', default="http://localhost:5000", help="URL of server to upload to") args = parser.parse_args() ...
submissions.iteritems(): print("Submitting {}".format(name)) # Change raw_data_accession so each run adds new records fields["raw_data_accession"] = str(uuid.uuid4()) print(fields["raw_data_accession"]) r = requests.post("{}/v0/submissions?publish=false".for
mat(args.host), files=[ ("files[]", (fields["vcf_filename"], open("tests/ALL/{}".format(fields["vcf_filename"]), "rb")))], data=fields) assert(r.status_code == requests.codes.ok) submitted.append(json.lo...
xplv/qtile
libqtile/widget/currentlayout.py
Python
mit
2,371
0
# -*- coding: utf-8 -*- # # Copyright (c) 2011 Florian Mounier # Copyright (c) 2011 Kenji_Takahashi # Copyright (c) 2012 roger # Copyright (c) 2012, 2014 Tycho Andersen # Copyright (c) 2012 Maximilian Köhl # Copyright (c) 2013 Craig Barnes # Copyright (c) 2014 Sean Vig # Copyrig
ht (c) 2014 Adi Sieker # # 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 Soft
ware without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permiss...
alex-dow/psistatsrd
psistatsrd/config.py
Python
mit
920
0.004348
import sys import os import pygame class Config(object): def __init__(self, config_file): self.config_file = config_file self.params = {} def parse(self): with open(self.config_file) as f: for line in f: if line[0] == ";": continue; ...
\n") val = self.params[parts[0]] if val[0] == "#": self.params[parts[0]] = pygame.Color(val) if val == "false": self.params[parts[0]] = False elif val == "true": sel...
al == "none": self.params[parts[0]] = None
D-K-E/cltk
src/cltk/prosody/lat/verse_scanner.py
Python
mit
18,030
0.002609
"""Parent class and utility class for producing a scansion pattern for a line of Latin verse. Some useful methods * Perform a conservative i to j transformation * Performs elisions * Accents vowels by position * Breaks the line into a list of syllables by calling a Syllabifier class which may be injected into this cl...
ils as string_utils from cltk.prosody.lat.metrical_validator import MetricalValidator from cltk.prosody.lat.scansion_constants import ScansionConstants from cltk.prosody.lat.scansion_formatter import ScansionFormatter from cltk.prosody.lat.syllabifier import Syllabifier from cltk.prosody.lat.verse import Vers
e LOG = logging.getLogger(__name__) LOG.addHandler(logging.NullHandler()) __author__ = ["Todd Cook <todd.g.cook@gmail.com>"] __license__ = "MIT License" class VerseScanner: """ The scansion symbols used can be configured by passing a suitable constants class to the constructor. """ def __init__...
david58/gradertools
gradertools/isolation/isolate_simple.py
Python
mit
1,622
0.006165
import subprocess import shutil import os import time from .interface import IsolateInterface class IsolateSimple(IsolateInterface): def isolate(self, files, command, parameters, envvariables, directories, allowmultiprocess, stdinfile, stdoutfile): if os.path.isdir("/tmp/gradert
ools/isolation/"): shutil.rmtree("/tmp/gradertools/isolation/") os.makedirs("/tmp/gradertools/isolation/") box = "/tmp/gradertools/isolation/" for file in files: shutil.copy(file, os.path.join(box, os.path.basename(file))) isolateio=" " if stdinfile is not...
teio+="> "+stdoutfile t0 = time.perf_counter() out = subprocess.run(" ".join(["cd "+ box+ ";"]+[command]+parameters+[isolateio]), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) t1 = time.perf_counter() self._boxdir = box self._status =...
openstack/horizon
openstack_dashboard/contrib/developer/profiler/api.py
Python
apache-2.0
3,772
0
# Copyright 2016 Mirantis 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...
riting, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import contextlib
import json from osprofiler import _utils as utils from osprofiler.drivers.base import get_driver as profiler_get_driver from osprofiler import notifier from osprofiler import profiler from osprofiler import web from horizon.utils import settings as horizon_settings ROOT_HEADER = 'PARENT_VIEW_TRACE_ID' def init_...
murat1985/bagpipe-bgp
bagpipe/exabgp/message/update/__init__.py
Python
apache-2.0
2,921
0.030127
# encoding: utf-8 """ update/__init__.py Created by Thomas Mangin on 2009-11-05. Copyright (c) 2009-2012 Exa Networks. All rights reserved. Modified by Orange - 2014 """ from copy import deepcopy from bagpipe.exabgp.structure.address import AFI,SAFI from bagpipe.exabgp.message import Message,prefix from bagpipe.exa...
afi sel
f.safi = routes[0].nlri.safi # The routes MUST have the same attributes ... def announce (self,asn4,local_asn,remote_asn): if self.afi == AFI.ipv4 and self.safi in [SAFI.unicast, SAFI.multicast]: nlri = ''.join([route.nlri.pack() for route in self.routes]) mp = '' else: nlri = '' mp = MPRNLRI(self.ro...
Karosuo/Linux_tools
xls_handlers/xls_sum_venv/lib/python3.6/site-packages/pip/_internal/commands/list.py
Python
gpl-3.0
10,150
0
from __future__ import absolute_import import json import logging from pip._vendor import six from pip._vendor.six.moves import zip_longest from pip._internal.cli import cmdoptions from pip._internal.cli.base_command import Command from pip._internal.exceptions import CommandError from pip._internal.index import Pac...
='include_editable', help='Exclude editable package from output.', ) cmd_opts.add_option( '--include-editable', action='store_true', dest='include_editable', help='Include editable package from output.', default=True, ) ...
index_opts = cmdoptions.make_option_group( cmdoptions.index_group, self.parser ) self.parser.insert_option_group(0, index_opts) self.parser.insert_option_group(0, cmd_opts) def _build_package_finder(self, options, index_urls, session): """ Create a package fi...
pcdummy/socketrpc
examples/gevent_srpc.py
Python
bsd-3-clause
5,981
0.00535
#!/usr/bin/python -OO # -*- coding: utf-8 -*- # vim: set et sts=4 sw=4 encoding=utf-8: # ############################################################################### # # This file is part of socketrpc. # # Copyright (C) 2011 Rene Jochum <rene@jrit.at> # ##############################################################...
'e': 'fast', 'n': 'and', 't': 'sexy!'} class ClientProtocol(SocketRPCProtocol): def docall_log(self, args): self.logger.log(args[0], '"%s" logged from the server' % args[1]) return '%s: logged on the client, fac...
((options['host'], options['port']), ClientProtocol) for i in xrange(options['requests']): client.call('bounce', ['log', (logging.WARN, 'test')]).get() elif mode == 'clientlarge': client = SocketRPCClient((options['host'], options['port']), ClientProtocol) ...
dogukantufekci/workplace_saas
workplace_saas/_apps/places/models.py
Python
mit
1,622
0.000617
from django.db import models class PlaceType(models.Model): name = models.CharField( max_length=100, unique=True, ) class Place(models.Model): type = models.ForeignField( PlaceType, related_name='places', ) name = models.CharField( max_length=100, ) ...
a3 = models.CharField( max_length=3, ) ccn3 = models.CharField( max_length=3, ) world_region = models.ForeignField( Place, relate
d_name='countries_world_region', ) world_sub_region = models.ForeignField( Place, related_name='countries_world_sub_region' ) class CountryCallingCode(models.Model): country = models.ForeignField( Country, related_name='country_calling_codes' ) calling_code = mo...
rajashreer7/autotest-client-tests
linux-tools/sblim_sfcb/sblim_sfcb.py
Python
gpl-2.0
1,610
0.004969
#!/bin/python import os, subprocess import logging from autotest.client import test from autotest.client.shared import error, software_manager sm = software_manager.SoftwareManager() class sblim_sfcb(test.test): """ Autotest module for testing basic functionality
of sblim_sfcb @author Wang Tao <wangttao@cn.ibm.com> """ version = 1 nfail = 0 path = '' def initialize(self, test_path=''): """ Sets the overall failure counter for the test. """ self.nfail = 0 if not sm.check_installed('gcc'): logging....
) ret_val = subprocess.Popen(['make', 'all'], cwd="%s/sblim_sfcb" %(test_path)) ret_val.communicate() if ret_val.returncode != 0: self.nfail += 1 logging.info('\n Test initialize successfully') def run_once(self, test_path=''): """ Trigger test run ...
lfairchild/PmagPy
programs/conversion_scripts/irm_magic.py
Python
bsd-3-clause
3,055
0.008838
#!/usr/bin/env python """ NAME irm_magic.py DESCRIPTION Creates MagIC file from an IRM excel file. If you have multiple Excel files you will have to run the program for each Excel file and combine each type of file (locations.txt, sites.txt, etc.) manually using "combine_magic.py" The program cre...
ind=sys.argv.index('-WD') kwargs['output_dir_path'] = sys.argv[ind+1] else: kwargs['output_dir_path'] = './' if '-f' in sys.argv: ind=sys.argv.index('-f') kwargs['mag_file'] = sys.argv[ind+1] elif len(sys.argv) == 2: kwargs['mag_file'] = sys.argv[1] else: ...
=sys.argv.index('-cit') kwargs['citation'] = sys.argv[ind+1] else: kwargs['citation'] = 'This study' if '-M' in sys.argv: ind=sys.argv.index('-M') kwargs['MPMSdc_type'] = sys.argv[ind+1] else: kwargs['MPMSdc_type'] = '0' convert.irm(**kwargs) if __name__...
jeremiahyan/odoo
addons/mail/models/ir_model.py
Python
gpl-3.0
4,660
0.003219
# -*- coding: utf-8 -*- # Part of Odoo. See LICENS
E file for full copyright and licensing details. from odoo import _, api, fields, models from odoo.exceptions import UserError class IrModel(models.Model): _inherit = 'ir.model' _order = 'is_mail_thread DESC, name ASC' is_mail_thread = fields.Boolean( string="Mail Thread", default=False, ...
_mail_activity = fields.Boolean( string="Mail Activity", default=False, help="Whether this model supports activities.", ) is_mail_blacklist = fields.Boolean( string="Mail Blacklist", default=False, help="Whether this model supports blacklist.", ) def unlink(self): ...
divio/django-shop
shop/admin/product.py
Python
bsd-3-clause
6,026
0.004315
# -*- coding: utf-8 -*- from __future__ import unicode_literals import warnings from django import forms from django.core.cache import cache from django.core.exceptions import ImproperlyConfigured from django.contrib import admin from django.contrib.sites.models import Site from django.utils.translation import ugette...
Add this mixin class to the ModelAdmin class for products wishing to be assigned to djangoCMS pages when used as categories. """ def __init__(self, *args, **kwargs): super(CMSPag
eAsCategoryMixin, self).__init__(*args, **kwargs) if not hasattr(self.model, 'cms_pages'): raise ImproperlyConfigured("Product model requires a field named `cms_pages`") def get_fieldsets(self, request, obj=None): fieldsets = list(super(CMSPageAsCategoryMixin, self).get_fieldsets(reques...
rogerthat-platform/rogerthat-backend
src-test/rogerthat_tests/mobicage/capi/test_feature_version.py
Python
apache-2.0
1,999
0.001501
# -*- coding: utf-8 -*- # Copyright 2017 GIG Technology NV # # 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...
License for the specific language governing permissions and # limitations under the License. # # @@license_version:1.3@@ import mc_unittest from rogerthat.bizz.profile import create_user_profile from rogerthat.bizz.system import update_app_asset_response from rogerthat.capi.system import updateAppAsset from rogerthat....
ies.profiles import MobileDetails from rogerthat.rpc import users from rogerthat.rpc.models import Mobile from rogerthat.rpc.rpc import logError from rogerthat.to.app import UpdateAppAssetRequestTO class Test(mc_unittest.TestCase): def testSendNews(self): self.set_datastore_hr_probability(1) sca...
spektom/incubator-airflow
airflow/ti_deps/deps/exec_date_after_start_date_dep.py
Python
apache-2.0
1,807
0.001107
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding co
pyright ownership. The ASF licenses this file # to you 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...
for the # specific language governing permissions and limitations # under the License. from airflow.ti_deps.deps.base_ti_dep import BaseTIDep from airflow.utils.session import provide_session class ExecDateAfterStartDateDep(BaseTIDep): NAME = "Execution Date" IGNOREABLE = True @provide_session def ...
dsoprea/protobufp
protobufp/read_buffer.py
Python
gpl-2.0
4,934
0.004459
import logging from threading import RLock from struct import unpack class ReadBuffer(object): """This class receives incoming data, and stores it in a list of extents (also referred to as buffers). It allows us to leisurely pop off sequences of bytes, which we build from the unconsumed extents. As the...
then go back to remove the span from the front of the buffers. """ with self.__class__.__locker: result
= self.__passive_read(4) if result is None: return None (four_bytes, last_buffer_index, updates1) = result (length,) = unpack('>I', four_bytes) result = self.__passive_read(length, last_buffer_index) if result is None: return...
rangadi/beam
sdks/python/apache_beam/runners/direct/direct_runner_test.py
Python
apache-2.0
4,539
0.003084
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
cells import DistributionData from apache_beam.metrics.cells import DistributionResult from apache_beam.metrics.execution import MetricKey from apache_beam.metrics.execution import MetricResult from apache_beam.metrics.metric import Metrics from apache_beam.metrics.metricbase import MetricName from apache
_beam.pipeline import Pipeline from apache_beam.runners import DirectRunner from apache_beam.runners import TestDirectRunner from apache_beam.runners import create_runner from apache_beam.testing import test_pipeline from apache_beam.testing.util import assert_that from apache_beam.testing.util import equal_to class ...
smmribeiro/intellij-community
python/testData/completion/superMethodWithAnnotation.after.py
Python
apache-2.0
202
0.009901
from typing import Dict class Pare
nt: def overridable_method(self, param: str)
-> Dict[str, str]: pass class Child(Parent): def overridable_method(self, param: str) -> Dict[str, str]:
ThinkmanWang/NotesServer
3rd-lib/DBUtils-1.1/setup.py
Python
apache-2.0
2,421
0.003717
"""Setup Script for DBUtils""" __version__ = '1.1' __revision__ = "$Rev: 8220 $" __date__ = "$Date: 2011-08-14 14:01:04 +0200 (So, 14. Aug 2011) $" from sys import version_info py_version = version_info[:2] if not (2, 3) <= py_version < (3, 0): raise ImportError('Python %d.%d is not supported by DBUtils.' % py_v...
DistributionMetadata.download_url = None try: DistributionMetadata.package_data except AttributeError: DistributionMetadata.package_data = None try: DistributionMetadata.zip_safe except AttributeError: Distribution
Metadata.zip_safe = None setup( name='DBUtils', version=__version__, description='Database connections for multi-threaded environments.', long_description='''\ DBUtils is a suite of tools providing solid, persistent and pooled connections to a database that can be used in all kinds of multi-threaded en...
abantos/bolt
test/test_btoptions.py
Python
mit
3,939
0.007616
""" """ import logging import unittest import bolt._btoptions as btoptions class TestOptions(unittest.TestCase): def setUp(self): # If we don't initialize it from an empty options list, it parses # the arguments to nosetests and the test fail. The actual code using # it doesn't need t...
lt_command_is_properly_initialized(self): self.assertEqual(self.default_options.command, btoptions.Default.COMMAND) def test_command_is_version_if_switch_specified(self): self.given(btoptions.OptionSwitch.VERSION_LONG) self.assertEqual(self.options.command, btoptions.Commands.VERSION) ...
): self.assertEqual(self.default_options.task, btoptions.Default.TASK) def test_returns_correct_task_if_specified(self): task = 'a_task' self.given(task) self.assertEqual(self.options.task, task) def test_default_boltfile_is_properly_initialized(self): self.assertEqua...
brokendata/bigmler
bigmler/command.py
Python
apache-2.0
6,139
0
# -*- coding: utf-8 -*- # # Copyright 2014-2015 BigML # # 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 ...
rom bigmler.defaults import get_user_defaults from bigmler.prediction import MAX_MODELS from bigmler.parser import create_parser COMMAND_LOG = u".bigmler" DIRS_LOG = u".bigmler_dir_stack" SESSIONS_LOG = u"bigmler_sessions" def tail(file_handler, window=1): """Returns the last n lines of a file. """ buf...
0 and file_bytes > 0: if (file_bytes - bufsiz) > 0: # Seek back one whole bufsiz file_handler.seek(block * bufsiz, 2) # read BUFFER new_data = [file_handler.read(bufsiz)] new_data.extend(data) data = new_data else: # fi...
antoinecarme/pyaf
tests/artificial/transf_Quantization/trend_PolyTrend/cycle_30/ar_/test_artificial_1024_Quantization_PolyTrend_30__0.py
Python
bsd-3-clause
268
0.085821
import pyaf.Bench.TS_datasets as tsds import
tests.artificial.process_artificial_dataset as art art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 30, transform = "Quantization", sigma = 0.0, exog_count = 0, ar_ord
er = 0);
Osmose/monews
monews/wsgi.py
Python
mit
387
0.002584
""" WSGI config for monews project. It exposes the WSGI callable as a module-level variable named ``application``. For more infor
mation on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "monews.setti
ngs") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
thkim107/sim
KAKAO_DATA_PREPARE_eval_multithread.py
Python
mit
1,759
0.030131
import h5py from scipy.spatial import distance import scipy.misc import numpy as np from joblib import Parallel, delayed # installation by 'conda install joblib' #path = '/home/sungkyun/Dropbox/kakao coversong git/sim/data/training/CP_1000ms_training_s2113_d2113_170106223452.h5' path = '/home/sungkyun/Dropbox/kakao ...
sum(cover2,axis=0)/np.max(np.sum(cover2,axis=0)) dist_store = np.zeros(chroma_dim) for i in range(0,chroma_dim): cover2_mean_shifted = np.roll(cover2_mean, i) dist = np.dot(cover1_mean,cover2_mean_shifted) dist_store[i] = dist oti = np.argmax(dist_store) cover2_shifted = np.ro...
i(X,Y,12)[0] YY = oti(X,Y,12)[1] M = [[0 for col in range(180)] for row in range(180)] for i in range(180): for j in range(180): M[i][j] = distance.euclidean(XX[i,:],YY[j,:]) return np.asarray(M) #%% Preprocess & Save Eval data def my_func(idx_start): for i in range(idx_start, idx_start+1): p...
AutorestCI/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_08_01/models/effective_network_security_group_list_result.py
Python
mit
1,400
0
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
NetworkSecurityGroupListResult(Model): """Response for list effective network security groups API service call. Variables are only populated by the server, and will be ignored when sending a request. :param value: A list of effective network security groups. :type value: list[~azure.mgmt.netw...
:ivar next_link: The URL to get the next set of results. :vartype next_link: str """ _validation = { 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[EffectiveNetworkSecurityGroup]'}, 'next_link': {'key': 'nextLink', 'type': 'st...
yuanxu/django-scaffold
scaffold_toolkit/zui/forms.py
Python
gpl-2.0
5,477
0.000183
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.admin.widgets import AdminFileWidget from django.forms import ( HiddenInput, FileInput, CheckboxSelectMultiple, Textarea, TextInput, PasswordInput ) from django.forms.widgets import CheckboxInput from .zui import ( ge
t_zui_setting, get_form_renderer, get_field_renderer, get_formset_renderer ) from .text import text_concat, t
ext_value from .exceptions import BootstrapError from .utils import add_css_class, render_tag, split_css_classes from .components import render_icon FORM_GROUP_CLASS = 'form-group' def render_formset(formset, **kwargs): """ Render a formset to a Bootstrap layout """ renderer_cls = get_formset_render...
oesteban/tract_querier
tract_querier/setup.py
Python
bsd-3-clause
766
0.001305
#!/usr/bin/env python def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('tract_querier', parent_package, top_path) config.add_subpackage('tractography') config.add_subpackage('tract_math') config.add_subpackage('code_uti...
.qry', 'data/mori_queries.qry', ])) return config if __name__ == '__main__': from distutils.core import setup setup(**configuration(top_path='').todic
t())
maruohon/Minecraft-Overviewer
overviewer_core/files.py
Python
gpl-3.0
6,437
0.005127
# This file is part of the Minecraft Overviewer. # # Minecraft Overviewer is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or (at # your option) any later version...
shutil.copy(os.path.join(src, entry), os.path.jo
in(dst, entry)) else: shutil.copyfile(os.path.join(src, entry), os.path.join(dst, entry)) # Define a context manager to handle atomic renaming or "just forget it write # straight to the file" depending on whether os.rename provides atomic # overwrites. # Detect whether os.rename wil...
tbttfox/TwistyTools
ttUI/QtFiles/combo.py
Python
gpl-3.0
899
0.002225
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'combotest.ui' # # Created: Wed Feb 29 11:35:04 2012 # by: PyQt4 UI code generator 4.7.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_Form(object): def setupUi
(self, Form): Form.setObjectName("Form") self.comboMode = QtGui.QComboBox(Form) self.comboMode.setMaxCount(2) self.comboMode.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContents) self.comboMode.setObjectName("comboMode") self.comboMode.addItem("Puzzle Mode") self....
QtGui.QApplication(sys.argv) Form = QtGui.QWidget() ui = Ui_Form() ui.setupUi(Form) Form.show() sys.exit(app.exec_())
petewarden/tensorflow
tensorflow/python/lib/core/bfloat16_test.py
Python
apache-2.0
17,940
0.005128
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
.5) + float(2.25))) self.assertEqual(np.float64, type(float(3.5) + bfloat16(2.25))) self.assertEqual(np.float32,
type(bfloat16(3.5) + np.array(2.25, np.float32))) self.assertEqual(np.float32, type(np.array(3.5, np.float32) + bfloat16(2.25))) def testSub(self): np.testing.assert_equal(0, float(bfloat16(0) - bfloat16(0))) np.testing.assert_equal(1, float(bfloat16(1) - bfloat16(0))...
agfor/chipy.org
chipy_org/apps/profiles/models.py
Python
mit
772
0
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile') display_name = models.CharField( max_length=200, verbo...
k In') show = models
.BooleanField( default=False, verbose_name="Show my information in the member list") @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): """Create a matching profile whenever a user object is created.""" if created: profile, new = UserProfile.objects.get_...
endlessm/chromium-browser
third_party/catapult/third_party/gsutil/third_party/apitools/samples/fusiontables_sample/fusiontables_v1/fusiontables_v1_client.py
Python
bsd-3-clause
34,754
0.004892
"""Generated client library for fusiontables version v1.""" # NOTE: This file is autogenerated and should not be edited by hand. from apitools.base.py import base_api from samples.fusiontables_sample.fusiontables_v1 import fusiontables_v1_messages as messages class FusiontablesV1(base_api.BaseApiClient): """Generat...
lative_path=u'tables/{tableId}/columns/{columnId}', request_field='', request_type_name=u'FusiontablesColum
nDeleteRequest', response_type_name=u'FusiontablesColumnDeleteResponse', supports_download=False, ) def Get(self, request, global_params=None): r"""Retrieves a specific column by its id. Args: request: (FusiontablesColumnGetRequest) input message global_params: (Sta...
z411/weabot
tenjin.py
Python
agpl-3.0
81,524
0.006526
## ## $Release: 1.1.1 $ ## $Copyright: copyright(c) 2007-2012 kuwata-lab.com all rights reserved. $ ## $License: MIT License $ ## ## 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 wit...
'odd' print(c
ycle()) #=> 'even' print(cycle()) #=> 'odd' print(cycle()) #=> 'even' """ def gen(values): i, n = 0, len(values) while True: yield values[i] i = (i + 1) % n return gen(values).next class Captu...
kencochrane/django-intercom
django_intercom/settings.py
Python
bsd-3-clause
925
0.005405
from django.conf import settings INTERCOM_APPID = getattr(settings, 'INTERCOM_APPID', None) INTERCOM_SECURE_KEY = getattr(settings, 'INTERCOM_SECURE_KEY', None) INTERCOM_ENABLE_INBOX = getattr(settings, 'INTERCOM_ENABLE_INBOX', True) INTERCOM_ENABLE_INBOX_COUNTER = getattr(settings, 'INTERCOM_EN
ABLE_INBOX_COUNTER', True) INTERCOM_INBOX_CSS_SELECTOR = getattr(settings, 'INTERCOM_INBOX_CSS_SELECTOR', '#Intercom') INTERCOM_USER_DATA_CLASS = getattr(settings, 'I
NTERCOM_USER_DATA_CLASS', None) INTERCOM_CUSTOM_DATA_CLASSES = getattr(settings, 'INTERCOM_CUSTOM_DATA_CLASSES', None) INTERCOM_COMPANY_DATA_CLASS = getattr(settings, 'INTERCOM_COMPANY_DATA_CLASS', None) INTERCOM_DISABLED = getattr(settings, 'INTERCOM_DISABLED', False) INTERCOM_INCLUDE_USERID = getattr(settings, 'INTER...
enthought/etsproxy
enthought/kiva/pdfmetrics.py
Python
bsd-3-clause
45
0
# proxy module from k
iva.pdfmetrics import *
GuLinux/PySpectrum
qtcommons.py
Python
gpl-3.0
3,204
0.009363
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QFileDialog, QToolBar, QToolButton, QMenu, QAction, QLabel, QApplication from PyQt5.QtGui import QIcon from PyQt5.QtCore import Qt, QStandardPaths, QTimer import os class QtCommons: def nestWidget(parent, child): l = QVBoxLayout() l.setContentsMargi...
dialog): dialog.setFileMode(QFileDialog.ExistingFiles) dialog.setAcceptMode(QFileDialog.AcceptOpen) dialog.filesSelected.connect(on_ok) QtCommons.__open_dialog__(title, file_types, dir, setup_dialog
, parent) def open_file(title, file_types, on_ok, dir='', parent=None): def setup_dialog(dialog): dialog.setFileMode(QFileDialog.ExistingFile) dialog.setAcceptMode(QFileDialog.AcceptOpen) dialog.fileSelected.connect(lambda file:on_ok((file,dialog.selectedNameFilt...
Astutech/Pushwoosh-Python-library
setup.py
Python
mit
2,681
0
"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.absp...
g description from the relevant file with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='pushwoosh', # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https...
push notification service.', long_description=long_description, # The project's main homepage. url='https://github.com/Astutech/Pushwoosh-Python-library', # Author details author='Astutech', author_email='matthew@astutech.com', # Choose your license license='MIT', # See https://p...
GrognardsFromHell/TemplePlus
tpdatasrc/tpgamefiles/scr/Spell600 - Frog Tongue.py
Python
mit
1,771
0.040655
from toee import * def OnBeginSpellCast( spell ): print "Frog Ton
gue OnBeginSpellCast" print "spell.target_list=", spell.target_list print "spell.caster=", spell.caster, " caster.level= ", spell.caster_level def OnSpellEffect( spell ): print "Frog Tongue OnSpellEffect" # it takes 1 round to pull the target to the frog (normally) spell.duration = 0 target_item = spell.target...
ell.caster.get_size: spell.duration = 1 has_freedom = 0 if target_item.obj.d20_query(Q_Critter_Has_Freedom_of_Movement): has_freedom = 1 ranged_touch_res = spell.caster.perform_touch_attack( target_item.obj ) if (ranged_touch_res & D20CAF_HIT) and not has_freedom: target_item.obj.float_mesfile_line( 'mes\\s...
antoinecarme/pyaf
tests/artificial/transf_Fisher/trend_ConstantTrend/cycle_30/ar_12/test_artificial_128_Fisher_ConstantTrend_30_12_20.py
Python
bsd-3-clause
267
0.086142
import p
yaf.Bench.TS_datasets as tsds import tests.artificial.pr
ocess_artificial_dataset as art art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "ConstantTrend", cycle_length = 30, transform = "Fisher", sigma = 0.0, exog_count = 20, ar_order = 12);
healthchecks/healthchecks
hc/front/tests/test_add_msteams.py
Python
bsd-3-clause
1,478
0
from django.test.utils import override_settings from hc.api.models import Channel from hc.test import BaseTestCase class AddMsTeamsTestCase(BaseTestCase): def setUp(self): super().setUp() self.url = "/projects/%s/add_msteams/" % self.project.code def test_instructions_work(self): self...
requires_rw_access(self): self.bobs_membership.role = "r" self.bobs_membership.save() self.client.login(username="bob@example.org", password="password") r = self.client.get(self.url) self.assertEqual(r.status_code, 403) @override_settings(MSTEAMS_ENABLED=False) def test...
f.client.login(username="alice@example.org", password="password") r = self.client.get(self.url) self.assertEqual(r.status_code, 404)
jvdm/AutobahnPython
examples/asyncio/wamp/session/series/backend.py
Python
mit
1,661
0
############################################################################### # # The MIT License (MIT) # # Copyright (c) Tavendo GmbH # # 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 with...
###### import datetime from autobahn.asyncio.wamp import ApplicationSession class Component(Applicati
onSession): """ A simple time service application component. """ def onJoin(self, details): def utcnow(): now = datetime.datetime.utcnow() return now.strftime("%Y-%m-%dT%H:%M:%SZ") self.register(utcnow, u'com.timeservice.now')
savoirfairelinux/sous-chef
src/notification/urls.py
Python
agpl-3.0
77
0
from django.conf.urls import url app_na
me = "not
ification" urlpatterns = []
DIRACGrid/DIRACWeb
dirac/lib/helpers.py
Python
gpl-3.0
1,413
0.035386
"""Helper functions Consists of functions to typically be used within templates, but also available to Controllers. This module is available to both as 'h'. """ from webhelpers import * from webhelpers.html import tags from routes import url_for from pylons import request def javascript_link( *urls, **attrs ): retu...
( fn ): def wrap( self = None ): return "<html><body><img src='/images/logos/logo.png'/><br><br><br><br><p class='lrg'>\ The <a href='http://diracgrid.org'>DIRAC</a> project is a complete \ Grid solution for a community of users needing access to \ distributed computing resourc...
ommunity? Get <a href='https://github.com/DIRACGrid'>\ involved</a>!</p><br>\ <p class='footer'>" + fn( self ) + "</p></body></html>" return wrap
Smiter/voodoo
voodoo/wsgi.py
Python
gpl-2.0
1,522
0.000657
""" WSGI con
fig for voodoo project. This module contains the WSGI a
pplication used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application ...
Sciprios/EvolutionaryPartyProblemSimulator
PartyProblemSimulator/Experiments/Experiment.py
Python
mit
3,577
0.00615
from PartyProblemSimulator.BooleanEquation.Equation import Equation from threading import Thread class Experiment(Thread): """ An experiment to be run on the Party Problem Simulator. """ def run(self): """ Should be implemented to execute the experiment and save results. """ results = self._do...
0
while trial_count < no_trials: trial_res = self._do_trial(method(), Equation(test_case['Equation']), test_case['NumVars']) # Do the trial if trial_res['Success']: # Only add information if it was successful test_case_sr = test_case_sr + 1 ...
indiofish/lov-o-meter
src/analysis/analyser.py
Python
gpl-3.0
2,602
0
from collections import namedtuple, Counter from datetime import timedelta from analysis import sentiment from analysis import qa_analysis ChatData = namedtuple('ChatData', ['interval', 'avg_chats', 'sentiments', 'qa_ratio']) c...
e += chat[i].time - chat[i-1].time avg_interval = tmp_time.total_seconds() // len(chat) return avg_interval # TODO: should we use n of chats, or length? def __chat_per_day__(self, chat): c
nt = Counter() for c in chat: cnt[c.time.date()] += 1 return sum(cnt.values()) // len(cnt) def __questions__(self, chat): total_q = 0 ans = 0 # self, other questions = [[], []] for c in chat: if qa_analysis.is_question(c.contents): ...
ecreall/lagendacommun
lac/views/user_management/deactivate.py
Python
agpl-3.0
857
0.003501
# Copyright (c) 2014 by Ecreall under licence AGPL terms # available on http://www.gnu.org/licenses/agpl.html # licence: AGPL # author: Amen Souissi from pyramid.view import view_config from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS from pontus.view import BasicView from lac.content.processes....
Person, renderer='pontus:templates/views_templates/grid.pt', ) class DeactivateView(Basi
cView): title = _('Deactivate the member') name = 'deactivate' behaviors = [Deactivate] viewid = 'deactivateview' def update(self): results = self.execute(None) return results[0] DEFAULTMAPPING_ACTIONS_VIEWS.update({Deactivate: DeactivateView})
blckshrk/Weboob
weboob/tools/capabilities/paste.py
Python
agpl-3.0
2,825
0.004248
# -*- coding: utf-8 -*- # Copyright(C) 2011 Laurent Bachelier # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your ...
t MockPasteBackend({1337: '', 42: '', False: ''}).get_closest_e
xpiration(84) is 42 assert MockPasteBackend({1337: '', 42: '', False: ''}).get_closest_expiration(False) is False assert MockPasteBackend({1337: '', 42: ''}).get_closest_expiration(False) is 1337 assert MockPasteBackend({1337: '', 42: '', False: ''}).get_closest_expiration(1336) is 42 assert MockPasteBa...
StackStorm/st2
contrib/examples/actions/pythonactions/yaml_string_to_object.py
Python
apache-2.0
795
0
# C
opyright 2020 The StackStorm Authors. # Copyright 2019 Extreme Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless req...
agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import yaml from st2common.runners.base_a...
alfasin/st2
st2common/tests/unit/test_rbac_resolvers.py
Python
apache-2.0
7,834
0.002553
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
Method which verifies that user
has all the provided permissions. """ self.assertTrue(isinstance(permission_types, (list, tuple))) self.assertTrue(len(permission_types) > 1) for permission_type in permission_types: result = resolver.user_has_resource_db_permission( user_db=user_db, ...
jeanpimentel/contents
tests/functional/test_file_with_long_levels.py
Python
gpl-3.0
3,294
0.003947
import sure import tempfile from contents import contents def test_file_with_long_levels(): content = '''/** * Project X * Author: Jean Pimentel * Date: August, 2013 */ /* > Intro */ Toc toc! Penny! Toc toc! Penny! Toc toc! Penny! /* >> The Big Bang Theory << */ The Big Bang Theory is an American sitcom cr...
============================================================= */ /** * Project X * Author: Jean Pimentel * Date: August, 2013 */ /* > Intro */ Toc toc! Penny! Toc toc! Penny! Toc toc! Penny! /* >> The Big Bang Theory << */ The Big Bang Theory is an American sitcom created by Chuck Lorre and Bill
Prady. /* ==>>> Characters ========================================================= */ Leonard Hofstadter, Sheldon Cooper, Howard Wolowitz, Rajesh Koothrappali, Penny /* >>>> Production ============================================================================= */ Executive producer(s): Chuck Lorre, Bill Prady, S...
mindriot101/bokeh
bokeh/io/tests/test_showing.py
Python
bsd-3-clause
7,140
0.004762
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2017, Anaconda, Inc. All rights reserved. # # Powered by the Bokeh Development Team. # # The full license is in the file LICENSE.txt, distributed with this software. #---------------------------------------------------...
= {'notebook_handle': True} assert curdoc().roots == [] @patch('bokeh.io.showing.run_notebook_hook') def test_show_with_app(mock_run_notebook_hook): curstate().reset() app = Application() output_notebook() bis.show(app, notebook_url="baz") assert curstate().notebook_type == "jupyter" assert...
_args[0][1:] == ("app", app, curstate(), "baz") assert mock_run_notebook_hook.call_args[1] == {} @patch('bokeh.io.showing._show_with_state') def test_show_doesn_not_adds_obj_to_curdoc(m): curstate().reset() assert curstate().document.roots == [] p = Plot() bis.show(p) assert curstate().document...