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
bahmanh/word-rnn-tensorflow
utils.py
Python
mit
4,469
0.003359
# -*- coding: utf-8 -*- import os import collections from six.moves import cPickle import numpy as np import re import itertools class TextLoader(): def __init__(self, data_dir, batch_size, seq_length): self.data_dir = data_dir self.batch_size = batch_size self.seq_length = seq_length ...
# Mapping from word to index vocabulary = {x: i for i, x in enumerate(vocabulary_inv)} return [vocabulary, vocabulary_inv] def preprocess(self, input_file, vocab_file, tensor_file): with open(input_file, "r"
) as f: data = f.read() # Optional text cleaning or make them lower case, etc. #data = self.clean_str(data) x_text = data.split() self.vocab, self.words = self.build_vocab(x_text) self.vocab_size = len(self.words) with open(vocab_file, 'wb') as f: ...
Teddy-Schmitz/temperature_admin
models/__init__.py
Python
mit
58
0
""" Cont
ains the dat
abase models for the application. """
schleichdi2/OPENNFR-6.3-CORE
bitbake/lib/layerindexlib/cooker.py
Python
gpl-2.0
14,139
0.00488
# Copyright (C) 2016-2018 Wind River Systems, Inc. # # SPDX-License-Identifier: GPL-2.0-only # import logging import json from collections import OrderedDict, defaultdict from urllib.parse import unquote, urlparse import layerindexlib import layerindexlib.plugin logger = logging.getLogger('BitBake.layerindexlib.c...
(layerpath) else: remote = remotes.split("\t")[1].split(" ")[0] if "(fetch)" == remotes.split("\t")[1].split(" ")[1]: layerurl = self.
_handle_git_remote(remote) break layerItemId += 1 index.layerItems[layerItemId] = layerindexlib.LayerItem(index, None) index.layerItems[layerItemId].define_data(layerItemId, layername, description=layerpath, vcs_url=layerurl) for branchId in ...
christianurich/VIBe2UrbanSim
3rdparty/opus/src/opus_matsim/sustain_city/tests/matsim_coupeling/matrix_test.py
Python
gpl-2.0
3,343
0.012564
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington and Kai Nagel # See opus_core/LICENSE import os import opus_matsim.sustain_city.tests as test_dir from opus_core.tests import opus_unittest from opus_core.store.csv_storage import csv_storage from urbansim.datasets.travel_dat...
cation to travel data table self.input_directory = os.path.join( self.test_dir_path, 'data', 'travel_cost') logger.log_status("input_directory: %s" % self.input_directory)
# check source file if not os.path.exists( self.input_directory ): raise('File not found! %s' % self.input_directory) print "Leaving setup" def test_run(self): print "Entering test run" # This test loads an exising travel data as a TravelDataSet...
stonescar/multi-user-blog
blogmods/handlers/new_post.py
Python
mit
772
0
from main_handler import Handler from ..models import Posts from .. import utils class NewPost(Handler):
"""Handler for new post page""" @utils.login_required def get(self): self.render("newpost.html") @utils.login_required def post(self
): subject = self.request.get("subject") content = self.request.get("content") if subject and content: p = Posts(subject=subject, content=content, author=self.user) p.put() self.redirect("/post/"+str(p.key().id())) else: error = "Subject ...
larsmans/numpy
numpy/lib/tests/test_io.py
Python
bsd-3-clause
66,065
0.000802
from __future__ import division, absolute_import, print_function import sys import gzip import os import threading from tempfile import mkstemp, NamedTemporaryFile import time import warnings import gc from io import BytesIO from datetime import datetime import numpy as np import numpy.ma as ma from numpy.lib._iotool...
ray([[1 + 2j, 2 + 7j], [3 - 6j, 4 + 12j]], complex) c = BytesIO() np.savez(c, file_a=a, file_b=b) c.seek(0) l = np.load(c) assert_equal(a, l['file_a']) assert_equal(b, l['file_b']) def test_BagObj(self): a = np.array([[1, 2], [3, 4]], float) b = n...
c = BytesIO() np.savez(c, file_a=a, file_b=b) c.seek(0) l = np.load(c) assert_equal(sorted(dir(l.f)), ['file_a','file_b']) assert_equal(a, l.f.file_a) assert_equal(b, l.f.file_b) def test_savez_filename_clashes(self): # Test that issue #852 is fixed ...
sthirugn/robottelo
tests/foreman/api/test_template_combination.py
Python
gpl-3.0
3,545
0
# -*- coding: utf-8 -*- """Tests for template combination @Requirement: TemplateCombination @CaseAutomation: Automated @CaseLevel: Acceptance @CaseComponent: API @TestType: Functional @CaseImportance: Medium @Upstream: No """ from nailgun import entities from requests.exceptions import HTTPError from robottelo.d...
"""Delete ConfigTemplate used on tests""" super(TemplateCombinationTestCase, self).tearDown() # Clean combination if it is not already deleted try: self.template_combination.delete() except HTTPError: pass self.template.delete() @tier1
@skip_if_bug_open('bugzilla', 1369737) def test_positive_get_combination(self): """Assert API template combination get method works. @id: 2447674e-c37e-11e6-93cb-68f72889dc7f @Setup: save a template combination @Assert: TemplateCombination can be retrieved through API """ ...
ubunteroz/foreman
foreman/utils/population.py
Python
gpl-3.0
30,432
0.006145
# foreman imports import hashlib from foreman.model import User, ForemanOptions, UserRoles, Case, UserCaseRoles, CaseType, CaseClassification, CaseStatus from foreman.model import TaskType, Task, TaskStatus, UserTaskRoles, EvidenceType, Evidence, TaskUpload, EvidenceStatus from foreman.model import EvidencePhotoUpload...
dd(u9) sessio
n.add(u10) session.flush() u1.add_change(admin) u2.add_change(admin) u3.add_change(admin) u4.add_change(admin) u5.add_change(admin) u6.add_change(admin) u7.add_change(admin) u8.add_change(admin) u9.add_change(admin) u10.add_change(admin) session.flush() session.commit...
chop-dbhi/varify-data-warehouse
vdw/variants/migrations/0012_auto__add_field_varianteffect_segment.py
Python
bsd-2-clause
17,850
0.008179
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'VariantEffect.segment' db.add_column('variant_effect', 'segment', self...
[], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.TextField', [
], {'blank': 'True'}), 'phenotypes': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['phenotypes.Phenotype']", 'through': "orm['genes.GenePhenotype']", 'symmetrical': 'False'}), 'symbol': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), ...
jeroanan/GameCollection
UI/Handlers/Exceptions/UnrecognisedHandlerException.py
Python
gpl-3.0
56
0
class
UnrecognisedHandlerException(Exception):
pass
mikel-egana-aranguren/SADI-Galaxy-Docker
galaxy-dist/eggs/mercurial-2.2.3-py2.7-linux-x86_64-ucs4.egg/hgext/extdiff.py
Python
gpl-3.0
12,584
0.001271
# extdiff.py - external diff program support for mercurial # # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. '''command to allow external programs to compare revisions The ex...
evs and change: msg = _('cannot specify --rev and --change at the same time') raise util.Abort(msg) elif change: node2 = scmutil.revsingle(repo, change, None).node() node1a, node1b = repo.changelog.parents(node2) else: node1a, node2 = scmutil.revpair(repo, revs) i...
ot revs: node1b = repo.dirstate.p2() else: node1b = nullid # Disable 3-way merge if there is only one parent if do3way: if node1b == nullid: do3way = False matcher = scmutil.match(repo[node2], pats, opts) mod_a, add_a, rem_a = map(set, repo.status(no...
unibet/unbound-ec2
tests/unit/test_config.py
Python
isc
8,032
0.003984
import os import ast from tests import unittest from unbound_ec2 import config class TestConfig(unittest.TestCase): def setUp(self): self.config = config.UnboundEc2Conf() def tearDown(self): os.environ['UNBOUND_ZONE'] = config.DEFAULT_ZONE os.environ['UNBOUND_REVERSE_ZONE'] = config....
os.environ['UNBOUND_EC2_CONF'] = fixture_conf_file self.config = config.UnboundEc2Conf() self.assertEqual(self.config.conf_file, fixture_conf_file) def test_set_defaults(self): self.config.set_defaults() self.assertIn('aws_region', self.confi
g.ec2) self.assertIn('zone', self.config.main) self.assertIn('reverse_zone', self.config.main) self.assertIn('ttl', self.config.main) self.assertIn('cache_ttl', self.config.main) self.assertIn('type', self.config.server) self.assertIn('type', self.config.lookup) s...
agoose77/hivesystem
bee/types.py
Python
bsd-2-clause
16,351
0.003241
from __future__ import print_function import functools _modes = ["push", "pull"] _types = set(( "event", "exception", "int", "float", "bool", "str", "mstr", "id", "object", "block", "blockcontrol", "blockmodel", "expression", "bee", )) _objecttypes = "object", "mstr", "id", "block", "bloc...
l = pclass(a) ret2[pname] = pval unmatched = {} for pname in kargs: if pname in ret2: raise TypeError("Duplicate definition of parameter %s" % pname) ppar = [v[1] for v in namedparameters if v[0] == pname] if len(ppar) == 0: unmatched[pname] = kargs[pname...
nmatched[pname] = a else: if pclass is object: pval = a elif a is None: pval = None else: pval = pclass(a) ret2[pname] = pval for pname, pclass, default in namedparameters: if pname not in ret2: r...
DavisPoGo/Monocle
migrations/versions/f19fc04ba856_added_existing_tables.py
Python
mit
10,836
0.01495
"""Added existing tables Revision ID: f19fc04ba856 Revises: Create Date: 2017-09-24 03:10:27.208231 """ from alembic import op import sqlalchemy as sa import sys from pathlib import Path monocle_dir = str(Path(__file__).resolve().parents[2]) if monocle_dir not in sys.path: sys.path.append(monocle_dir) from monoc...
ble=True), sa.Column('move_2', sa.SmallInteger(), nullable=True), sa.Column('gender', sa.SmallInteger(), nullable=True), sa.Column('form', sa.SmallInteger(), nullable=True), sa.Column('cp', sa.SmallInteger(), nullable=True), sa.Column('level', sa.SmallInteger(), nullable=True), sa.PrimaryKeyCons...
.f('ix_sightings_encounter_id'), 'sightings', ['encounter_id'], unique=False) op.create_index(op.f('ix_sightings_expire_timestamp'), 'sightings', ['expire_timestamp'], unique=False) op.create_table('spawnpoints', sa.Column('id', sa.Integer(), nullable=False), sa.Column('spawn_id', sa.BigInteger(), nulla...
agaffney/ansible
lib/ansible/modules/stat.py
Python
gpl-3.0
19,140
0.001776
#!/usr/bin/python # Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r''' --- module: stat version_added: "1.3" short_description: Re...
socket returned: success, path exists and user can read stats type: bool sample: False uid: description: N
umeric id representing the file owner returned: success, path exists and user can read stats type: int sample: 1003 gid: description: Numeric id representing the group of the owner returned: success, path exists and user can read stats type...
bhattmansi/Implementation-of-CARED-in-ns3
src/stats/bindings/modulegen__gcc_LP64.py
Python
gpl-2.0
256,748
0.014244
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) ...
='ns.core') ## simulator.h (module 'core'): ns3::Simulator [enumeration] module.add_enum('', ['NO_CONTEXT'], outer_class=root_module['ns3::Simulator'], import_from_module='ns.core') ## data-calculator.h (module 'stats'): ns3::StatisticalSummary [class] module.add_class('StatisticalSummary', allow_subcla...
value.h (module 'core'): ns3::TracedValue<bool> [class] module.add_class('TracedValue', import_from_module='ns.core', template_parameters=['bool']) ## traced-value.h (module 'core'): ns3::TracedValue<double> [class] module.add_class('TracedValue', import_from_module='ns.core', template_parameters=['double']...
NeuroTechX/eeg-101
python_tools/utilities.py
Python
isc
5,241
0.011067
""" Utilities for plotting various figures and animations in EEG101. """ # Author: Hubert Banville <hubert@neurotechx.com> # # License: TBD import numpy as np import matplotlib.pylab as plt import collections from scipy import signal def dot_plot(x, labels, step=1, figsize=(12,8)): """ Make a 1D dot plot. ...
s = np.vstack((sines, np.sum(sines, axis=0))) + offsets # Update figure for p, x in zip(points, sines): p.set_ydata(x) # Wait before starting another cycle plt.pause(1./refresh_rate) if __name__ == '__main__': # 1) DISTRIBUTION OF TRAINING...
fake data nb_points = 10*10 relax_data = np.random.normal(0.01, 0.01, size=(nb_points,)) focus_data = np.random.normal(0.03, 0.01, size=(nb_points,)) dot_plot(x=np.concatenate((relax_data, focus_data)), labels=np.concatenate((np.zeros((nb_points,)), np.ones((nb_points,)))), ...
jwilk/anorack
lib/articles.py
Python
mit
1,632
0.001232
# Copyright © 2016 Jakub Wilk <jwilk@jwilk.net> # # 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...
es or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO E
VENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. ''' English articles ''' from lib import phonetics accent...
Azure/azure-sdk-for-python
sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_09_01/models/_models.py
Python
mit
38,322
0.00321
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
e: str :param name: The name of the action. :type name: str :param status: The status of the action. :type status: str :p
aram sub_state: The substatus of the action. :type sub_state: str :param send_time: The send time. :type send_time: str :param detail: The detail of the friendly error message. :type detail: str """ _attribute_map = { 'mechanism_type': {'key': 'MechanismType', 'type': 'str'}, ...
cmgrote/tapiriik
tapiriik/urls.py
Python
apache-2.0
7,197
0.007781
from django.conf.urls import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic import TemplateView # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', ur...
ollback_dashboard', {}, name='rollback_dashboard', ), url(r'^configure/sav
e/(?P<service>.+)?$', 'tapiriik.web.views.config.config_save', {}, name='config_save', ), url(r'^configure/dropbox$', 'tapiriik.web.views.config.dropbox', {}, name='dropbox_config', ), url(r'^configure/flow/save/(?P<service>.+)?$', 'tapiriik.web.views.config.config_flow_save', {}, name='config_flow_save', ), ...
uclaros/QGIS
python/PyQt/PyQt5/uic/pyuic.py
Python
gpl-2.0
1,079
0
# -*- coding: utf-8 -*- """ *************************************************************************** pyuic.py --------------------- Date : March 2016 Copyright : (C) 2016 by Juergen E. Fischer Email : jef at norbit dot de ********************************...
ther version 2 of the License, or * * (at your option) any later version. * *
* *************************************************************************** """ __author__ = 'Juergen E. Fischer' __date__ = 'March 2016' __copyright__ = '(C) 2016, Juergen E. Fischer' from PyQt5.uic import pyuic if (callable(pyuic.main)): pyuic.main()
lisawei/api_automate_test
base.py
Python
apache-2.0
1,990
0.00603
#coding=utf-8 import httplib import urllib, urllib2 import json import base64 import functools import logging import time class RequestApi(object): TimeOut = 3 DEBUG_LEVEL = 1 HOST = "api.douban.com" @classmethod def request(cls, method, path, params, headers={}, host=''): """test --- ...
%s?%s" % (path, params) params = '' else: path = "%s" % path logging.debug("*[Requst]* %s %s %s" % (method, host + path, params)) conn.request(method, path, params, _headers) #conn.set
_debuglevel(cls.DEBUG_LEVEL) try: r = conn.getresponse() data = r.read() return data except Exception,e: logging.error("*[Requst]* %s %s %s request error:%s" % (method, host + path, params,e)) raise e finally: conn.close() ...
nkgilley/home-assistant
homeassistant/components/pvpc_hourly_pricing/sensor.py
Python
apache-2.0
5,339
0.001499
"""Sensor to collect the reference daily prices of electricity ('PVPC') in Spain.""" import logging from random import randint from typing import Optional from aiopvpc import PVPCData from homeassistant import config_entries from homeassistant.const import CONF_NAME, ENERGY_KILO_WATT_HOUR from homeassistant.core impo...
dd_entities ): """Set up the elect
ricity price sensor from config_entry.""" name = config_entry.data[CONF_NAME] pvpc_data_handler = PVPCData( tariff=config_entry.data[ATTR_TARIFF], local_timezone=hass.config.time_zone, websession=async_get_clientsession(hass), logger=_LOGGER, timeout=_DEFAULT_TIMEOUT, ...
aricaldeira/pyxmlsec
examples/sign1.py
Python
gpl-2.0
3,625
0.006345
#!/usr/bin/env python # # $Id: sign1.py 363 2006-01-01 18:03:07Z valos $ # # PyXMLSec example: Signing a template file. # # Signs a template file using a key from PEM file # # Usage: # ./sign1.py <xml-tmpl> <pem-key> # # Example: # ./sign1.py sign1-tmpl.xml rsakey.pem > sign1-res.xml # # The result signature could be ...
le) assert(key_file) # Load template doc = libxml2.parseFile(tmpl_file) if doc is None or doc.getRootElement() is None: print "Error:
unable to parse file \"%s\"" % tmpl_file return -1 # Find start node node = xmlsec.findNode(doc.getRootElement(), xmlsec.NodeSignature, xmlsec.DSigNs) if node is None: print "Error: start node not found in \"%s\"" % tmpl_file return cleanup(doc) ...
JuliaLang/pyjulia
src/julia/tests/test_juliaoptions.py
Python
mit
1,232
0
import pytest from julia.core import JuliaOptions # fmt: off @pytest.mark.parametrize("kwargs, args", [ ({}, []), (dict(compiled_modules=None), []), (dict(compiled_modules=False), ["--compiled-modules", "no"]), (di
ct(compiled_modules="no"), ["--compiled-modules", "no"]), (dict(depwarn="error"), ["--depwarn", "error"]), (dict(sysimage="PATH"), ["--sysimage", "PATH"]), (dict(bindir="PATH"), ["--home", "PATH"]), ]) # fmt: on def test_as_args(
kwargs, args): assert JuliaOptions(**kwargs).as_args() == args @pytest.mark.parametrize("kwargs", [ dict(compiled_modules="invalid value"), dict(bindir=123456789), ]) def test_valueerror(kwargs): with pytest.raises(ValueError) as excinfo: JuliaOptions(**kwargs) assert "Option" in str(excin...
lubao/UjU_Windows
src/GammuSender.py
Python
mit
1,013
0.008885
''' Created on Jan 18, 2010 @author: Paul ''' from SQLEng import SQLEng class PduSender(object): ''' classdocs This class is designed for Gammu-smsd Inserting a record into MySQL Gammu-smsd will send the record Using command line will cause smsd stop for a while '''
def get_mesg(self,byte_array): mesg = "" for byte in byte_array: if by
te < 16 : val = hex(byte) if val == "0x0" : val = "00" else : val = val.lstrip("0x") val = "{0}{1}".format('0', val) else : val = hex(byte) val = val.lstrip("...
i3visio/osrframework
osrframework/wrappers/pending/streakgaming.py
Python
agpl-3.0
4,315
0.009042
# !/usr/bin/python # -*- coding: cp1252 -*- # ################################################################################## # # Copyright 2016 Félix Brezo and Yaiza Rubio (i3visio, contacto@i3visio.com) # # This program is part of OSRFramework. You can redistribute it and/or modify # it under the terms of...
ved a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ################################################################################## __author__ = "Yaiza Rubio and Félix Brezo <contacto@i3visio.com>" __version__ = "1.1" import argparse import json...
(Platform): """ A <Platform> object for Streakgaming. """ def __init__(self): """ Constructor... """ self.platformName = "Streakgaming" self.tags = ["social", "news", "gaming"] ######################## # Defining valid modes # #...
RedhawkSDR/integration-gnuhawk
components/sig_source_i/tests/test_sig_source_i.py
Python
gpl-3.0
4,531
0.006621
#!/usr/bin/env python # # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is part of GNUHAWK. # # GNUHAWK is free software: you can redistribute it and/or modify is 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. # # GNUHAWK 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 received a copy of the GNU General Public License along with # this program. If not, see http://www.gnu.org/licenses/. # import unittest import ossie.utils.testing import os from omniORB...
wavefrontHQ/wavefront-collector
wavefront/awsbilling.py
Python
apache-2.0
17,443
0.001433
""" This module handles parsing the AWS Billing Reports (stored on S3 in .zip or just plain .csv format) and creating metrics to be sent to the WF proxy. """ import ConfigParser import datetime import io import os import sys import time import traceback import zipfile import logging.config import dateutil from wave...
space', None) self.enabled = self.
config.getboolean(section_name, 'enabled', False) self.region = self.config.get(section_name, 's3_region', None) self.bucket = self.config.get(section_name, 's3_bucket', None) self.prefix = self.config.get(section_name, 's3_prefix', None) self.header_row_index = int( self.con...
dbrattli/RxPY
tests/test_observable/test_withlatestfrom.py
Python
apache-2.0
14,723
0.001019
import unittest from rx import Observable from rx.testing import TestScheduler, ReactiveTest, is_prime, MockDisposable from rx.disposables import Disposable, SerialDisposable on_next = ReactiveTest.on_next on_completed = ReactiveTest.on_completed on_error = ReactiveTest.on_error subscribe = ReactiveTest.subscribe sub...
(self): ex1 = 'ex1' ex2 = 'ex2' scheduler = TestScheduler() msgs1 = [on_next(150, 1), on_next(210, 2), on_error(220, ex1)] msgs2 = [on_next(150, 1), on_error(230, ex2)] e1 = scheduler.create_hot_observ
able(msgs1) e2 = scheduler.create_hot_observable(msgs2) def create(): return e2.with_latest_from(e1, lambda x, y: x + y) results = scheduler.start(create) results.messages.assert_equal(on_
xiandiancloud/edxplaltfom-xusong
lms/djangoapps/instructor/views/coupons.py
Python
agpl-3.0
6,252
0.003039
""" E-commerce Tab Instructor Dashboard Coupons Operations views """ from django.contrib.auth.decorators import login_required from django.core.exceptions import ObjectDoesNotExist from django.db.models import Q from django.views.decorators.http import require_POST from django.utils.translation import ugettext as _ fro...
istrationCode Table course_registration_code = CourseRegistrationCode.objects.filter(code=code) if course_registration_code: return HttpResponseNotFound(_( "The code ({code}) that you have tried to define is already in use as a registration code").format(code=code) ) description...
: return HttpResponseNotFound(_("Please Enter the Integer Value for Coupon Discount")) if discount > 100: return HttpResponseNotFound(_("Please Enter the Coupon Discount Value Less than or Equal to 100")) coupon.code = code coupon.description = description coupon.course_id = course_id ...
tiancj/emesene
emesene/e3/common/utils.py
Python
gpl-3.0
2,941
0.00306
# -*- coding: utf-8 -*- # This file is part of emesene. # # emesene 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. # #...
self.__current = 0 @property def current(self): return self.__current @property def total(s
elf): return self.__total @total.setter def total(self, total): self.__total = total def notify(self, q): aux = (int)((q/self.__total) * 100.0) if aux == self.__current: changed = False else: ...
dials/dials
tests/algorithms/indexing/test_symmetry.py
Python
bsd-3-clause
7,130
0.001823
from __future__ import annotations import pytest import scitbx.matrix from cctbx import crystal, sgtbx, uctbx from cctbx.sgtbx import bravais_types from dxtbx.model import Crystal from dials.algorithms.indexing import symmetry @pytest.mark.parametrize("space_group_symbol", bravais_types.acentric) def test_Symmetry...
cell().volume() ) assert handler.target_symmetry_primitive.space_group() == sgtbx.space_group("P-1") assert ( handler.target_symmetry_reference_setting.unit_cell().volume() == pytest.approx(cs_min_cell.unit_cell().volume()) ) assert handler.target_symmetry_reference_setting.space_gro...
e_group_info(symbol="P422") cs = sgi.any_compatible_crystal_symmetry(volume=10000) B = scitbx.matrix.sqr(cs.unit_cell().fractionalization_matrix()).transpose() crystal = Crystal(B, sgtbx.space_group()) handler = symmetry.SymmetryHandler( unit_cell=None, space_group=sgtbx.space_group_info("I23")...
tux-00/ansible
test/units/module_utils/facts/test_collectors.py
Python
gpl-3.0
12,595
0.001032
# unit tests for ansible fact collectors # -*- coding: utf-8 -*- # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansibl...
collector_class = PythonFactCollector class TestSelinuxFacts(BaseFactsTest): __test__ = True gather_subset = ['!all', 'selinux'] valid_subsets = ['selinux'] fact_namespace = 'ansible_selinux' collector_class = SelinuxFactCollector def test_no_selinux(self): with patch('ansible.modul...
fact_collector = self.collector_class() facts_dict = fact_collector.collect(module=module) self.assertIsInstance(facts_dict, dict) self.assertFalse(facts_dict['selinux']) return facts_dict class TestServiceMgrFacts(BaseFactsTest): __test__ = True gat...
ikben/troposphere
troposphere/fms.py
Python
bsd-2-clause
1,072
0
# Copyright (c) 2012-2020, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSProperty, AWSObject, Tags from .validators import json_checker, boolean class IEMap(AWSProperty): props = { 'ACCOUNT': ([basestring], False), } class Policy(AWSObject...
'ResourceType': (basestring, True), 'ResourceTypeList': ([basestring], True), 'SecurityServicePolicyData': (json_checke
r, True), 'Tags': (Tags, False), } class NotificationChannel(AWSObject): resource_type = "AWS::FMS::NotificationChannel" props = { 'SnsRoleName': (basestring, True), 'SnsTopicArn': (basestring, True), }
christianurich/VIBe2UrbanSim
3rdparty/opus/src/paris/household_x_neighborhood/age_lnprice.py
Python
gpl-2.0
1,876
0.032516
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE # This is a simple test variable for the interaction of gridcells and households. from opus_core.variables.variable import Variable from urbansim.functions import attribute_label class age_...
le for the interaction of neighborhoods and households. Computes household.lhhincpc * neighborhood.ln_price.""" def dependencies(self): return [attribute_label("neighborhood", "ln_price"), "paris.household.agetrans"] def compute(self, dataset_pool): ...
_=='__main__': #from opus_core.tests import opus_unittest #from urbansim.variable_test_toolbox import VariableTestToolbox #from numpy import array #from numpy import ma #class Tests(opus_unittest.OpusTestCase): #variable_name = "urbansim.household_x_neighborhood.hhrich_nbpoor" ...
rshk/ardomino-api
ardomino/tests/test_configuration.py
Python
bsd-3-clause
3,008
0
""" Tests for configuration file parsers, ... """ from ConfigParser import RawConfigParser import io import os import textwrap import pytest from ardomino.conf import (process_conf_files, find_configuration_files, create_conf_parser) @pytest.fixture def conf_di...
""")) with open(str(tm
pdir.join('not-a-conf-file.txt')), 'w') as f: f.write(textwrap.dedent(""" [this-is:not] what = a configuration file! """)) return tmpdir def test_create_conf_parser(conf_dir): conf_parser = create_conf_parser(str(conf_dir)) assert 'pet:Cat' in conf_parser.sections() ass...
xasos/crowdsource-platform
crowdsourcing/migrations/0041_auto_20150825_0240.py
Python
mit
1,146
0.001745
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('crowdsourcing', '0040_auto_20150824_2013'),
] operations = [ migrations.AlterModelOptions( name='comment', options={'ordering': ['created_timestamp']}, ), migrations.RenameField( model_name='taskcomment', old_name='module',
new_name='task', ), migrations.AlterField( model_name='module', name='feedback_permissions', field=models.IntegerField(default=1, choices=[(1, b'Others:Read+Write::Workers:Read+Write'), (2, b'Others:Read::Workers:Read+Write'), (3, b'Others:Read::Workers:Read'), (4, b'...
kcsry/django-form-designer
form_designer/apps.py
Python
bsd-3-clause
193
0
from d
jango.apps import AppConfig from django.utils.translation import gettext_lazy as _ class FormDesignerConfig(AppConfig): name = 'form_designer' verbose_nam
e = _("Form Designer")
OnFTA/scrapy-training
crawler_film/crawler_film/pipelines.py
Python
mit
1,062
0.002825
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import pymongo class CrawlerPipeline(object): def __ini
t__(self, mongo_uri, mongo_db): self.mongo_uri = mongo_uri self.mongo_db = mongo_db @classmethod def from_crawler(cls, crawler): return cls( mongo_uri=crawler.settings.get('MONGO_URI'), mongo_db=crawler.settings.get('MONGO_DATABASE', 'crawler_film') ) ...
# disable drop by default self.db.drop_collection(self.collection_name) def close_spider(self, spider): self.client.close() def process_item(self, item, spider): self.db[self.collection_name].update({'url': item['url']}, dict(item), upsert=True) return item
jetspace/jetlibs
docs/source/conf.py
Python
mit
10,239
0.006739
# -*- coding: utf-8 -*- # # Jetlibs documentation build configuration file, created by # sphinx-quickstart on Wed Dec 23 16:22:13 2015. # # 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 # autogenerated file. # # A...
show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True
# -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'jetlibs', u'Jetlibs Documentation', [u'Marius Messerschmidt'], 1) ] # If true, show URL addres...
seishei/multiprocess
py2.5/examples/ex_synchronize.py
Python
bsd-3-clause
6,159
0.004221
# # A test file for the `processing` package # import time, sys, random from Queue import Empty import processing # may get overwritten #### TEST_VALUE def value_func(running, mutex): random.seed() time.sleep(random.random()*4) mutex.acquire() print '\n\t\t\t' + ...
itive refcou
nts left' if __name__ == '__main__': processing.freezeSupport() assert len(sys.argv) in (1, 2) if len(sys.argv) == 1 or sys.argv[1] == 'processes': print ' Using processes '.center(79, '-') namespace = processing elif sys.argv[1] == 'manager': print ' Usin...
aacebedo/raspbian-docker-images
seafile/files/seafile-installer.py
Python
gpl-3.0
9,507
0.019565
#!/usr/bin/env python3 import pexpect import sys import argparse import logging from logging import StreamHandler import traceback import os import quik from quik import Template import fileinput import re import tarfile import fnmatch ROOTLOGGER = logging.getLogger("seafileinstaller") class SeafileInstaller: @stat...
') parser.add_argument( '--install-dir', required=True, help='Install directory', type=str) parser.add_argument( '--server-name', required=True, help='Serve
r name', type=str) parser.add_argument( '--server-host', required=True, help="Server's host ip or domain", type=str) parser.add_argument( '--data-dir', required=True, help="Directory where data will be stored", ...
dotsonlab/AWSC-Toilet
flow.py
Python
mit
2,391
0.013802
''' David Rodriguez Goal: Continuously looping while to perform valve actions at specified times, introduce substance at a specific ratio based on flow data, recording and saving flow data, and actuating a flush at a specified time. Inputs: A schedule of events based on entered times. Outputs: Sequence of e...
erStepper(self): time.sleep(0.5) PWM.start("P9_16", 25, 100, 1) time.sleep(2) PWM.set_frequency("P9_16", 250) time.sleep(90) PWM.stop("P9_16") PWM.cleanup() def toiletTrigger(self, flushType): if flushType == "Full": self.toil
etFull() else: self.toiletUrine() def toiletUrine(self): print "Toilet Urine Triggered" self.enableStepper() self.triggerStepper() GPIO.output("P8_17", GPIO.HIGH) #pwm on GPIO.output("P8_15", GPIO.LOW) #extend actuator time.sleep(.65) ...
bauhaus93/webcrawler
ui_infopanel.py
Python
gpl-2.0
1,369
0.045289
import wx import functions infoItems=[ ("active time", functions.FormatTime), ("active workers", None), ("active tasks", None), ("tasks done", None), ("pending urls", None), ("unique urls found", None), ("bytes read", functions.FormatByte), ("processing speed", func
tions.FormatByteSpeed), ("current processing speed", functions.FormatByteSpeed), ("work time", functions.FormatTime), ("errors
", None), ("invalid data", None), ("http 1xx", None), ("http 2xx", None), ("http 3xx", None), ("http 4xx", None), ("http 5xx",None)] class InfoPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) self.sizer=wx.GridSizer(rows=len(infoItems), cols=2) self.text={} ...
gillesdegottex/dfasma
test/synth_grid.py
Python
gpl-3.0
1,049
0.014299
import numpy as np #import scipy.io.wavfile #import scipy.signal import pysndfile import matplotlib.pyplot as plt plt.ion() def db2mag(d): return 10.0*
*(d/20.0) if __name__ == "__main__" : print('Synthesise clicks and sinusoids at regular time and frequencies') fs = 16000 syn = np.zeros(4*fs) ts = np.arange(len(syn))/float(fs) # Add some frequencies freqs = [0, fs/16.0, fs/2-fs/16.0, fs/2] amps = -32 for freq in freqs: ...
syn += amp*2.0*np.cos((2*np.pi*freq)*ts) # Add some clicks clicks = np.array([0.0, 1.0, 2.0, 3.0, (len(syn)-1)/float(fs)]) syn[(clicks*fs).astype(np.int)] = 0.5 #print(pysndfile.get_sndfile_encodings('wav')) pysndfile.sndio.write('synth_grid_fs'+str(fs)+'.wav', syn, rate=fs, format='wav', e...
theia-log/theia
theia/cli/tau.py
Python
apache-2.0
100
0
""" -------------
theia.cli.tau ------------- Tau is a Text User Inter
face frontend for Theia. """
frozenjava/RobotSimulator
examples/robotFunctionality.py
Python
gpl-2.0
704
0.002841
from jbot import simulator def diagonal_moving(robot
): robot.clear_messages() robot.send_message("moving diagonally") for m in range(0, 100): robot.move_left(1) robot.move_up(1) def directional_moving(robot): robot.send_message("moving down") robot.move_down(30) robot.send_message("moving up") robot.move_up(60) robot...
ot = simulator.get_robot() directional_moving(my_robot) diagonal_moving(my_robot) my_robot.send_message("All Done!") if __name__ == "__main__": simulator.simulate(main)
dede67/FillBD2
Database.py
Python
gpl-3.0
7,228
0.019676
#!/usr/bin/env python # -*- coding: utf-8 -*- import sqlite3 import os HOMEDIR=os.path.expanduser('~') DATABASENAME=os.path.join(HOMEDIR, ".fillBD.conf.sqlite") # ########################################################### # DB-Zugriff für die Profile class Database(): def __init__(self): self.dbname=DATABASEN...
sor.fetchall() fldrs=[] for r2 in rows2: fldrs.append(r2[0]) retlst.append((r1[1], r1[2], r1[3], fldrs)) return(retlst) # ########################################################### # Fügt einen Satz in "destProfile" ein. def insertOrUpdateDest(self, name, comment, size, blocksize, ...
'SELECT ID FROM destProfile WHERE name LIKE ?', (name, )) c=self.cursor.fetchone() # c[0]=ID if c!=None: # Satz exitiert schon self.cursor.execute('UPDATE destProfile' \ ' SET comment=?, size=?, blocksize=?, addblock=?, fldrname=?, final=?' \ ' WHE...
chadversary/deqp
scripts/caselist_diff.py
Python
apache-2.0
15,192
0.016522
# -*- coding: utf-8 -*- #------------------------------------------------------------------------- # drawElements Quality Program utilities # -------------------------------------- # # Copyright 2015 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use t...
"dEQP-GLES2.usecases.ui.no_blend_nearest_batched_4") ] RENAME_LIST_2011_3_2011_4 = [] RENAME_LIST_2011_4_2012_1 = [ ("dEQP-GLES2.functional.vertex_arrays.multiple_attributes.output_types.*", "dEQP-GLES2.functional.vertex_arrays.multiple_attributes.input_types."), ] RENAME_LIST_2012_2_2012_3 = [ ("d...
"dEQP-GLES2.functional.shaders.operator.geometric.refract.mediump_float_float_vertex"), ("dEQP-GLES2.functional.shaders.operator.geometric.refract.mediump_float_fragment", "dEQP-GLES2.functional.shaders.operator.geometric.refract.mediump_float_float_fragment"), ("dEQP-GLES2.functional.shaders.operator.geometric.refr...
h2oai/h2o-3
h2o-py/tests/testdir_utils/pyunit_typechecks.py
Python
apache-2.0
6,106
0.001965
#!/usr/bin/env python # -*- encoding: utf-8 -*- """Pyunit for h2o.utils.typechecks.""" from __future__ import absolute_import, division, print_function import math from h2o import H2OFrame from h2o.exceptions import H2OTypeError, H2OValueError from h2o.utils.typechecks import (U, I, NOT, Tuple, Dict, numeric, h2ofram...
(len(vi) == len(v[0]) for vi in v))) try: # Cannot use `assert_error` here because typechecks module cannot detect args in (*args, *kwargs) assert_is_type(10000000, I(int, lambda port: 1 <= port <= 65535)) assert False, "Failed to throw an exception" excep
t H2OTypeError as e: assert "integer & 1 <= port <= 65535" in str(e), "Bad error message: '%s'" % e url_regex = r"^(https?)://((?:[\w-]+\.)*[\w-]+):(\d+)/?$" assert_matches("Hello, world!", r"^(\w+), (\w*)!$") assert_matches("http://127.0.0.1:3233/", url_regex) m = assert_matches("https://local...
m4773rcl0ud/launchpaddings
launchpaddings.py
Python
gpl-3.0
4,694
0.003409
from mididings import * from launchpad_utils import * config( backend='jack-rt', client_name='launchpad', in_ports=[ 'Pad Keys', ], out_ports=[ 'To Pad', 'To PC', ] ) # FROM PAD TO PC # First the controls active = 0 muted = 127 UpperRow = (Filter(CTRL) >> CtrlValueF...
reen, 0, active), 1: (red, -16, muted), 2: (green, -16, active), 3: (red, -32, muted), 4: (green, -32, active), 5: (red, -48, muted), 6: (green, -48, active), 7: (red, -64, muted), } # The even rows activate (green), the odd rows mute (red) patterns 0-31 # Moreover, the Pad keys light up wi...
ty(fixed=v[0]) >> Port(1), # color to Pad ~OnlyRight >> Transpose(v[1]) >> Ctrl(EVENT_NOTE, v[2]) >> Port(2), # ctrl to PC ] for k, v in list(dMap.items())] # I would like the right keys to activate/mute entire groups (rows) of patterns: def EntireRow(row): "Sends all not...
pombredanne/django-narcissus
narcissus/garden/__init__.py
Python
bsd-3-clause
1,221
0.001638
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.datastructures import SortedDict from django.utils.importlib import import_module from narcissus.settings import FLOWERS # Cache of actual flower classes. _narcissus_flowers = None def _get_flowers(): glob...
raise ImproperlyConfigured('Error importing narcissus flower module %s: "%s"' % (module, e)) try: flower = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a "%s" flower class' % (module, attr)) ...
name(), flower)) _narcissus_flowers = SortedDict(flowers) return _narcissus_flowers flowers = _get_flowers()
GNS3/gns3-server
gns3server/compute/dynamips/nodes/device.py
Python
gpl-3.0
2,538
0
# -*- coding: utf-8 -*- # # Copyright (C) 2015 GNS3 Technologies Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. ...
project self._manager = manager self._hypervisor = hypervisor @property def hypervisor(self): """ Returns the current hypervisor. :returns: hypervisor instance """ return self._hypervisor @property def project(self): """ Returns...
def name(self): """ Returns the name for this device. :returns: name """ return self._name @name.setter def name(self, new_name): """ Sets the name of this device. :param new_name: name """ self._name = new_name @proper...
CiscoSystems/fabric_enabler
dfa/server/services/firewall/native/drivers/phy_asa.py
Python
apache-2.0
4,614
0
# Copyright 2015 Cisco Systems, Inc. # All Rights Reserved. # # Licensed under the Ap
ache 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
red by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # fro...
VictorRodriguez/personal
ec-ea/practices/pract2/sga.py
Python
apache-2.0
2,812
0.011024
#!/usr/bin/env python3 import argparse import random import time def bin(number): return "{0:5b}".format(number).replace(' ','0') def
initialize(population): return [bin(random.randint(0,31)) for x in range(0, population)] def evaluate(population): tuples = [] suma = 0 end = False for chaval in population: value = int(chaval, 2) y = value**2 tuples.append((value, y, 0)) suma += y if value...
chaval in population: probability = round(chaval[1] / suma,2) tuples.append((chaval[0], chaval[1], probability)) return tuples def ruleta(population): random.shuffle(population) random.shuffle(population) rand_num = random.randint(1,100) try: rand_inv = 1 / rand_num ex...
Rihorama/dia2code
src/dia2code/classd/cls_attribute.py
Python
gpl-3.0
1,404
0.019231
#!/usr/bin/python3 class ClsAttribute: visibility_dict = {0 : "public", 1 : "private", 2 : "protected", 3 : "public"} #3 stands for implementation which is not implemented #so public is default here ...
def __init__(self, cls, attr_dict): #attr_dict keys are equal to element names in the dia XML self.my_class = cls self.name = attr_dict["name"] self.d_type =
attr_dict["type"] self.visibility = self.visibility_dict[attr_dict["visibility"]] self.abstract_flag = attr_dict["abstract"] self.static_flag = attr_dict["class_scope"] #static is marked as "class_scope" in dia self.comment = attr_dict["comment"] self.value =...
ihmpdcc/cutlass
tests/test_sample.py
Python
mit
13,059
0.000689
#!/usr/bin/env python """ A unittest script for the Sample module. """ import unittest import json from cutlass import Sample from cutlass import MIXS, MixsException from CutlassTestConfig import CutlassTestConfig from CutlassTestUtil import CutlassTestUtil # pylint: disable=W0703, C1801 class SampleTest(unittest...
a.") parse_success = False try: sample_data = json.loads(sample_json) parse_success = True except Exception: pass self.assertTrue(parse_success, "to_json() did not throw an exception.") self.assertTrue(sample_data is ...
al(sample_data['meta']['fma_body_site'], fma_body_site, "'fma_body_site' in JSON had expected value." ) def testDataInJson(self): """ Test if the correct data is in the generated JSON. """ sample = self.session.create_sample...
debian-live/live-magic
tests/test_sources_list.py
Python
gpl-3.0
4,591
0.004356
#!/usr/bin/env python # -*- coding: utf-8 -*- # # live-magic - GUI frontend to create Debian LiveCDs, etc. # Copyright (C) 2007-2010 Chris Lamb <lamby@debian.org> # # 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 # t...
irror class TestSourcesList(unittest.TestCase): def setUp(self): import tempfile fd, self.filename = tempfile.mkstemp('live-magic') os.close(fd) def t
earDown(self): try: os.unlink(self.filename) except OSError: pass def f_w(self, contents, filename=None): if filename is None: f = open(self.filename, 'w+') else: f = open(filename, 'w+') f.write(contents) f.close() cl...
mcgill-cpslab/MonkeyHelper
examples/DroidReplayer.py
Python
apache-2.0
2,426
0.004534
# # Copyright 2014 Mingyuan Xia (http://mxia.me) and others # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Li
cense. # 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...
y a trace to a Android device. You need monkeyrunner to run scripts once including this module """ import os, sys, inspect def module_path(): ''' returns the module path without the use of __file__. from http://stackoverflow.com/questions/729583/getting-file-path-of-imported-module''' return os.path.absp...
sgerhart/ansible
lib/ansible/modules/monitoring/grafana_dashboard.py
Python
mit
14,915
0.002749
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, Thierry Sallé (@seuf) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function ANSIBLE_METADATA = { 'status': ['preview'], 'supported_by': 'com...
'yes' client_cert: description: - PEM formatted certificate chain file to be used for SSL client authentication. - This file can also include the key as well, and if the key is included, client_key is not required version_added: 2.7 client_key: description: - PEM formatted file that c...
version_added: 2.7 use_proxy: description: - Boolean of whether or not to use proxy. default: 'yes' type: bool version_added: 2.7 ''' EXAMPLES = ''' - hosts: localhost connection: local tasks: - name: Import Grafana dashboard foo grafana_dashboard: grafana_url: http://graf...
openstack/horizon
openstack_dashboard/dashboards/project/instances/tables.py
Python
apache-2.0
48,198
0
# Copyright 2012 Nebula, 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 agree...
me = "rescue" verbose_name = _("Rescue Instance") policy_rules = (("compute", "os_compute_api:os-rescue"),) classes = ("b
tn-rescue", "ajax-modal") url = "horizon:project:instances:rescue" def get_link_url(self, datum): instance_id = self.table.get_object_id(datum) return urls.reverse(self.url, args=[instance_id]) def allowed(self, request, instance): return instance.status in ACTIVE_STATES class Un...
alphagov/digitalmarketplace-supplier-frontend
tests/app/test_application.py
Python
mit
4,526
0.001994
# coding=utf-8 import mock from lxml import html from wtforms import ValidationError from dmapiclient.errors import HTTPError from app.main.helpers.frameworks import question_references from .helpers import BaseApplicationTest class TestApplication(BaseApplicationTest): def setup_method(self, method): s...
elf.client.get('/suppliers/create/start') assert res.status_code == 200 document = html.fromstring(res.get_data(as_text=True)) cookie_banner = document.xpath('//div[@id="dm-cookie-banner"]') assert cookie_banner[0].xpath('//h2//text()')[0].strip() == "Can we store analytics cookies on yo...
(self, data_api_client, validate_csrf): self.login() with self.app.test_client(): self.app.config['WTF_CSRF_ENABLED'] = True self.client.set_cookie( "localhost", self.app.config['DM_COOKIE_PROBE_COOKIE_NAME'], self.app.config['DM_CO...
toumorokoshi/sprinter
sprinter/core/featureconfig.py
Python
mit
4,648
0.000645
from __future__ import unicode_literals from six.moves import configparser import logging import copy import sys import sprinter.lib as lib EMPTY = object() logger = logging.getLogger(__name__) class ParamNotFoundException(Exception): """ Exception for a parameter not being found """ class FeatureConfig(obje...
""" sets the param to the value provided """ self.raw_dict[param] = value self.manifest.set(self.feature_name, param, value) def remove(self, param): """ Remove a parameter from the manifest """ if self.has(param): del(self.raw_dict[param]) self.manif...
return self.raw_dict.keys() def is_affirmative(self, param, default=None): return lib.is_affirmative(self.get(param, default=default)) def set_if_empty(self, param, default): """ Set the parameter to the default if it doesn't exist """ if not self.has(param): self.set(par...
UMTti/mauno
setup.py
Python
mit
160
0.00625
from setuptools import setup setup( name='flaskr', packages=['fl
askr'], include_package_data=True, install_requires=[ 'flask'
, ], )
fboender/jsonxs
jsonxs/jsonxs.py
Python
mit
5,644
0.000886
#!/usr/bin/env python """ jsonxs uses a path expression string to get and set values in JSON and Python datastructures. For example: >>> d = { ... 'feed': { ... 'id': 'my_feed', ... 'url': 'http://example.com/feed.rss', ... 'tags': ['devel', 'example', 'python'], ... 'short....
ssing from th
e data struture continue cur_path = cur_path[token] except Exception: if default is not None: return default else: raise # Perform action the user requested. if action == ACTION_GET: return cur_path elif action == ACTIO...
google/cog
cognitive/train_utils.py
Python
apache-2.0
9,504
0.00947
# Copyright 2018 Google 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless requi
red by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ================...
__future__ import absolute_import from __future__ import division from __future__ import print_function from six import string_types import random import re import json import numpy as np import traceback from cognitive import stim_generator as sg import cognitive.constants as const _R_MEAN = 123.68 _G_MEAN = 116.7...
jjerphan/semiotweet
semiotweet/urls.py
Python
gpl-3.0
857
0
"""semiotweet URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/
http/urls/ Examples: Function
views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the inc...
pschulam/lmbases
tests/test_bsplines.py
Python
mit
2,966
0.001349
import numpy as np import lmbases def test_against_r_splines_uniform(): '''Compare BSplines class against R's bsplines with uniform knots. Generate the ground truth with the following R commands: > library(splines) > x <- c(1.5, 3.3, 5.1, 7.2, 9.9) > k <- c(2.5, 5.0, 7.5) > b <- bs(x, knots...
h) def test_against_r_splines_quantiles(): '''Compare BSplines class against R's bsplines with quantile knots. Generate the ground truth with the following R commands: > library(splines) > x <- c(1.5, 3.3, 5.1, 7.2, 9.9) > b <- bs(x, degree=2, df=6, intercept=TRUE, Boundary.knots=c(0, 10)) >...
4 5 6 [1,] 0.2975207 0.5687895 0.1336898 0.000000000 0.0000000 0.0000000 [2,] 0.0000000 0.3529412 0.6470588 0.000000000 0.0000000 0.0000000 [3,] 0.0000000 0.0000000 0.5384615 0.461538462 0.0000000 0.0000000 [4,] 0.0000000 0.0000000 0.0000000 0.571428571 0.4285714 0.0000000 [5,] 0...
monikagrabowska/osf.io
api_tests/registrations/views/test_withdrawn_registrations.py
Python
apache-2.0
7,865
0.003687
from urlparse import urlparse from api_tests.nodes.views.test_node_contributors_list import NodeCRUDTestCase from nose.tools import * # flake8: noqa from api.base.settings.defaults import API_BASE from framework.auth.core import Auth from tests.base import fake from osf_tests.factories import ( ProjectFactory, ...
d) res = self.app.get(url, auth=self.user.auth, expect_errors=True) assert_equal(res.status_code, 403) def test_can_access_withdrawn_contributor_detail(self): url = '/{}registrations/{}/contributors/{}/'.format(API_BASE, self.registration._id, self.user._id) res = self.app.get(url, ...
return_a_withdrawn_registration_at_node_detail_endpoint(self): url = '/{}nodes/{}/'.format(API_BASE, self.registration._id) res = self.app.get(url, auth=self.user.auth, expect_errors=True) assert_equal(res.status_code, 404) def test_cannot_delete_a_withdrawn_registration(self): url ...
CartoDB/crankshaft
src/py/crankshaft/crankshaft/regression/gwr/base/gwr.py
Python
bsd-3-clause
39,275
0.004328
#Main GWR classes #Offset does not yet do anyhting and needs to be implemented __author__ = "Taylor Oshan Tayoshan@gmail.com" import numpy as np import numpy.linalg as la from scipy.stats import t from .kernels import * from .diagnostics import get_AIC, get_AICc, get_BIC import pysal.spreg.user_output as USER from c...
shaft.regression.glm.iwls import iwls from crankshaft.regression.glm.utils import cache_readonly fk = {'gaussian': fix_gauss, 'bisquare': fix_bisquare,
'exponential': fix_exp} ak = {'gaussian': adapt_gauss, 'bisquare': adapt_bisquare, 'exponential': adapt_exp} class GWR(GLM): """ Geographically weighted regression. Can currently estimate Gaussian, Poisson, and logistic models(built on a GLM framework). GWR object prepares model input. Fit method perf...
heyLu/pixie
pixie/vm/code.py
Python
gpl-3.0
25,247
0.002812
py_object = object import pixie.vm.object as object from pixie.vm.object import affirm from pixie.vm.primitives import nil, true, false from rpython.rlib.rarithmetic import r_uint from rpython.rlib.jit import elidable, elidable_promote, promote import rpython.rlib.jit as jit import pixie.vm.rt as rt BYTECODES = ["LOA...
art[self._required_arity] = array(rest) return self._code.invoke_with(start, self_fn) affirm(False, u"Got " + unicode(str(argc)) + u" arg(s) need at least " + unicode(str(self._required_arity))) class Closure(BaseCode): _type = object.Type(u"pixie.stdlib.Closure") __immutable_fields__ = ["_...
def __init__(self, code, closed_overs, meta=nil): BaseCode.__init__(self) affirm(isinstance(code, Code), u"Code argument to Closure must be an instance of Code") self._code = code self._closed_overs = closed_overs self._meta = meta def with_meta(self, meta): return...
missionpinball/mpf-mc
mpfmc/uix/transitions.py
Python
mit
5,152
0
import importlib from kivy.animation import AnimationTransition from kivy.properties import StringProperty from kivy.uix.screenmanager import TransitionBase from kivy.uix.screenmanager import (WipeTransition, SwapTransition, FadeTransition, FallOutTransition, ...
config['transition_out'] = dict(type=config['transition_out']) try: config['transition_out'] = ( self.mc.config_validator.validate_config( 'transitions:{}'.format( config['t
ransition_out']['type']), config['transition_out'])) except KeyError: raise ValueError('transition_out: section of config ' 'requires a "type:" setting') else: config['transition_out'] = None return config...
jbedorf/tensorflow
tensorflow/python/ops/init_ops_v2.py
Python
apache-2.0
26,725
0.004041
# 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...
flow.python.ops import linalg_ops_impl from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops import stateless_random_ops from tensorflow.python.util.tf_export import tf_export class Initializer(object): """Initializer base class: all initializers inherit ...
. dtype: Optional dtype of the tensor. If not provided will return tensor of `tf.float32`. """ raise NotImplementedError def get_config(self): """Returns the configuration of the initializer as a JSON-serializable dict. Returns: A JSON-serializable Python dict. """ return ...
codles/UpDownMethods
UpDownMethods/process.py
Python
mit
5,746
0
import numpy as np import pandas as pd import datetime as dt def initiate_procedure(): results = pd.DataFrame(columns=('Responses', 'Value', 'Reversal', 'Run', 'Trial', 'Direction', 'DateTime')) return results def append_result(res, resp, down, up, stepSize...
response given cntD += 1 # Increment the counter for down cntU = 0 # Reset the up counter if cntD == down: # The c
orrect number of down responses cntD = 0 # Reset the counter if direction != -1: # We found a reversal if direction != 0: # The first movement is not a reversal # Only edit values from most recent response ...
paulfanelli/planet_alignment
planet_alignment/data/system_data.py
Python
mit
1,159
0.000863
""" .. module:: system_data :platform: linux :synopsis: The module containing the system data. .. moduleauthor:: Paul Fanelli <paul.fanelli@gmail.com> .. modulecreated:: 6/26/15 """ import bunch import sys from yaml.parser import ParserError from zope.interface import implements from planet_alignment.data.inte...
super(SystemData, self).__init__(data) except ParserError as pe: print("ERROR: Error parsing data!") sys.exit("ERROR: {}".format(pe)) except Exception as e: print("ERROR: Unknown exceptio
n '{}'".format(e)) sys.exit("ERROR: {}".format(e)) def __iter__(self): return iter(self.system) def __len__(self): return len(self.system)
gw-sd-2016/Codir
codirSublime/SocketIO/websocket/_app.py
Python
gpl-2.0
10,235
0.002833
""" websocket - WebSocket client library for Python Copyright (C) 2010 Hiroki Ohtani(liris) This lib
rary 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. This library is distributed in the hope that it will be useful...
HOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software ...
RasaHQ/rasa_nlu
rasa/nlu/run.py
Python
apache-2.0
803
0.001245
import asyncio import logging from typing import Text from rasa.core.agent import Agent from rasa.shared.utils.cli import pr
int_info, print_success from
rasa.shared.utils.io import json_to_string logger = logging.getLogger(__name__) def run_cmdline(model_path: Text) -> None: """Loops over CLI input, passing each message to a loaded NLU model.""" agent = Agent.load(model_path) print_success("NLU model loaded. Type a message and press enter to parse it."...
NREL/bifacial_radiance
tests/test_gencumsky.py
Python
bsd-3-clause
4,169
0.010794
# -*- coding: utf-8 -*- """ Created on Fri Jul 27 10:08:25 2018 @author: cdeline Using pytest to create unit tests for gencumulativesky. Note that this can't be included in the repo until TravisCI has a Linux version of gencumsky set up in .travis.yml to run unit tests, run pytest from the command line in the bifaci...
rt term-missing --cov=bifacial_radiance """ #from bifacial_radiance import Rad
ianceObj, SceneObj, AnalysisObj import bifacial_radiance import numpy as np import pytest import os # try navigating to tests directory so tests run from here. try: os.chdir('tests') except: pass TESTDIR = os.path.dirname(__file__) # this folder # test the readepw on a dummy Boulder EPW file in the /tests/ ...
getsentry/obs
setup.py
Python
apache-2.0
1,534
0
#!/usr/bin/env python """ obs === :copyright: (c) 2015 Functional Software, Inc :license: Apache 2.0, see LICENSE for more details. """ from __future__ import absolute_import, unicode_literals import os.path from setuptools import setup, find_packages # Hack to prevent stupid "TypeError: 'NoneType' object is not c...
1,<1.1.0', 'pytest>=2.5.0,<2.6.0', 'pytest-cov>=1.6,<1.7', 'pytest-timeout>=0.3,<0.4', 'pytest-xdist>=1.9,<1.10', ] install_requires = [ ] setup( name='obs', version='0.0.0', author='David Cramer', author_email='dcramer@gmail
.com', url='https://github.com/getsentry/obs', description='', long_description=open('README.md').read(), packages=find_packages(exclude=['tests']), zip_safe=False, install_requires=install_requires, extras_require={ 'test': tests_require, }, license='Apache 2.0', include...
kobejean/tensorflow
tensorflow/python/profiler/model_analyzer_test.py
Python
apache-2.0
33,231
0.009088
# Copyright 2016 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...
.find(')')].split(',') # Make sure time is profiled. gap = 1 if test.is_gpu_available() else 2 for i in range(3, 6, gap): mat = re.search('(.*)(?:us|ms|sec)/(.*)(?:us|ms|sec)', metrics[i])
self.assertGreater(float(mat.group(1)), 0.0) self.assertGreater(float(mat.group(2)), 0.0) # Make sure device is profiled. if test.is_gpu_available(): self.assertTrue(metrics[6].find('gpu') > 0) self.assertFalse(metrics[6].find('cpu') > 0) ...
sunlightlabs/hanuman
data_collection/urls.py
Python
bsd-3-clause
730
0.00137
from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns import views urlpatterns = [ url(r'^firms/$', views.FirmList.as_view()), url(r'^firms/(?P<pk>[0-9]+)/$', views.FirmDetail.as_view()), url(r'^firms/next/$', views.NextFirmDetail.as_view()), url(r'^bio-pages/$...
w()), url(r'^flags/$', views.FlagCreate.as_view()), url(r'^token-auth/', 'rest_framework_jwt.views.obtain_jwt_token'), url(r'^token-auth-ns/', views.ObtainJSONWebTokenNS.as_view()), url(r'^token-refresh/', 'rest_framewo
rk_jwt.views.refresh_jwt_token'), ] urlpatterns = format_suffix_patterns(urlpatterns)
orione7/Italorione
servers/megadrive.py
Python
gpl-3.0
1,956
0.002559
# -*- coding: utf-8 -*- # ------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Conector para megadrive # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ # by DrZ3r0 # ------------------------------------------------------------ import re from core import logger from core...
%s')" % page_url) video_urls = [] data = scrapertools.cache_page(page_url) data_pack = scrapertools.find_single_match(data, "(eval.functi
on.p,a,c,k,e,.*?)\s*</script>") if data_pack != "": from core import unpackerjs3 data_unpack = unpackerjs3.unpackjs(data_pack) if data_unpack == "": from core import jsunpack data_unpack = jsunpack.unpack(data_pack) data = data_unpack video_url = scrapert...
Swiftea/Crawler
crawler/tests/test_data.py
Python
gpl-3.0
2,567
0.007803
#!/usr/bin/env python3 from shutil import rmtree from os import remove, path from crawler.swiftea_bot.data import BASE_LINKS URL = "http://aetfiws.ovh" SUGGESTIONS = ['http://suggestions.ovh/page1.html', 'http://suggestions.ovh/page2.html'] CODE1 = """<!DOCTYPE html> <html lang="en"> <head> <meta char...
icon"> </head> <body> <p>une <a href="demo">CSS Demo</a> ici!</p> <h1>Gros t
itre🤣 </h1> <h2>Moyen titre</h2> <h3>petit titre</h3> <p><strong>strong </strong><em>em</em></p> <a href="index"> <img src="public/themes/default/img/logo.png" alt="Swiftea"> </a> du texte au milieu <a href="about/ninf.php" rel="noindex, nofollow">Why...
sloria/device-inventory
inventory/settings/__init__.py
Python
bsd-3-clause
214
0
""" Settings for inventory """ from .base import * t
ry: from .local i
mport * except ImportError, exc: exc.args = tuple( ['%s (did you rename settings/local-dist.py?)' % exc.args[0]]) raise exc
cs-au-dk/Artemis
WebKit/Tools/Scripts/webkitpy/layout_tests/models/test_input.py
Python
gpl-3.0
2,580
0.001163
#!/usr/bin/env python # Copyright (C) 2010 Google Inc. All rights reserved. # Copyright (C) 2010 Gabor Rapcsanyi (rgabor@inf.u-szeged.hu), University of Szeged # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # *...
use they require us to figure out if the test is a reftest or not # and we want to be able to do that in parallel. self.should_run_pixel_tests = None self.reference_files = None def __repr__(self): return "TestInput('%s', %d, %s, %s)" % (self.test_name, self.timeout, self.
should_run_pixel_tests, self.reference_files)
tectronics/crossepg
src/enigma2/python/plugin.py
Python
lgpl-2.1
2,321
0.046963
from crossepglib import CrossEPG_Config from crossepg_main import crossepg_main from crossepg_locale import _ from Plugins.Plugin import PluginDescriptor def setup(menuid, **kwargs): if menuid == "setup": return [("CrossEPG", crossepg_main.setup, "crossepg", None)] else: return [] def call_downloader(session, *...
se: plugins.append(PluginDescriptor(name="CrossEPG", description=_("CrossEPG setup panel"),
where = PluginDescriptor.WHERE_MENU, fnc = setup)) plugins.append(PluginDescriptor(name="CrossEPG Auto", description = _("CrossEPG automatic actions"), where = PluginDescriptor.WHERE_SESSIONSTART, fnc = call_autostart)) if config.show_force_reload_as_plugin...
jianwei1216/my-scripts
mytest/python/MyInternet/myserver.py
Python
gpl-2.0
400
0.0025
#!/usr/bin/python
import socket def server_test(): s = socket.socket() host = socket.gethostname() port = 12345 s.bind((host, port)) s.listen(5) while True: c, addr = s.accept() print c print 'connect addr: ', addr c.send('Welcome to CaiNiao!') if cmp(c.recv(1024), "Goo...
break c.close() s.close()
rafaelbezerra-dev/PlantMonitoringSystem
monitoring_node/node.py
Python
gpl-3.0
1,138
0.011424
import sys, os, json physical_addess = '' node_info = None def getMacAdd
ress(): if sys.platform == 'win32': for line in os.popen("ipconfig /all"): if line.lstrip().startswith('Physical Address'): mac = line.split(':')[1].strip().replace('-',':') break else:
for line in os.popen("/sbin/ifconfig"): if line.find('Ether') > -1: mac = line.split()[4] break return mac def get(new_node = False, userId = None): global physical_addess global node_info if not physical_addess: physical_addess = getMacAddress() f = op...
wnavarre/email-dictator
script/template_test.py
Python
mit
1,955
0.008184
import template as t def test_template_once(inp, vals, funcs, output): actual = t.Template(inp).parse(vals, funcs) print (inp, vals, funcs, output, actual) assert(actual == output) print True def test_basic_vals_0(): test_template_once("", {}, {}, "") test_template_once("HI", {}, {}, "HI") de...
@." vals = {"name": "William", "age": 20} funcs = {} output = "My name is William and I am 20." test_template_once(inp, vals, funcs, output) def test_basic_func(): inp = "I am @@@age@@@ so I can @@@\\tooyoung@@@buy alcohol." vals1 = {"age": 20} vals
2 = {"age": 21} def f(vals, funcs): if vals["age"] < 21: return "not " else: return "" funcs = {"tooyoung": f} output1 = "I am 20 so I can not buy alcohol." output2 = "I am 21 so I can buy alcohol." test_template_once(inp, vals1, funcs, output1) test_tem...
wikkii/raspluonto
old/python_flask/old/main.py
Python
mit
388
0.064433
from dbconnect import connection from flask import Flask, render_template @app.route('/index/') def display_data(): try: c, conn = connection() query = "SELECT * from sensors" c
.execute(query) data = c.fetchall() conn.connection() #return data return r
ender_template("index.php", data=data) except Exception as e: return (str(e))
ray306/expy
test/show_picture.py
Python
gpl-3.0
882
0.004535
# coding:utf-8 ##### package test ##### import sys sys.path = ['../']+sys.path ################ from expy import * # Import the needed functions start() # Initiate the experiment environment '''General usage''' # Draw a picture on the canvas center drawPic('data/demo.jpg') show(3) # Display current canvas ''''''
# Draw a zoomed picture on the canvas center drawPic('data/demo.jpg', w=400, h=300)
show(3) # Display current canvas # Draw a zoomed picture on the canvas center drawPic('data/demo.jpg', w=300, h=400, rotate=90) show(3) # Display current canvas # Draw a zoomed picture on the canvas, and move it drawPic('data/demo.jpg', w=400, h=300, x=0.5, y=0.5) show(3) # Display current canvas # Draw a zoomed...
wevoice/wesub
apps/videos/rpc.py
Python
agpl-3.0
11,527
0.002429
# Amara, universalsubtitles.org # # Copyright (C) 2013 Participatory Culture Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your op...
return
cmp(lang2.get_language_code_display(), lang1.get_language_code_display()) #one should be original return cmp(lang1.is_original, lang2.is_original) first_languages.sort(cmp=_cmp_first_langs, reverse=True) #fill first languages to LANGS_COUNT if len(first_languages) < LA...
plone/plone.app.mosaic
src/plone/app/mosaic/browser/upload.py
Python
gpl-2.0
3,388
0
# -*- coding: utf-8 -*- from plone import api from plone.app.mosaic import _ from zope.publisher.browser import BrowserView import json class MosaicUploadView(BrowserView): """Handle file uploads""" def __call__(self): context = self.context request = self.request # Set header to js...
['status'] = 0 message['url'] = obj.absolute_url() message['title'] = title return json.dumps(
message) def cleanupFilename(self, name): """Generate a unique id which doesn't match the system generated ids""" context = self.context id = '' name = name.replace('\\', '/') # Fixup Windows filenames name = name.split('/')[-1] # Throw away any path part. for c i...
TheTimmy/spack
var/spack/repos/builtin/packages/namd/package.py
Python
lgpl-2.1
5,455
0.000183
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
g with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## import platform import shutil import sys import os from spack import * class Namd(MakefilePackage): """NA...
ge biomolecular systems.""" homepage = "http://www.ks.uiuc.edu/Research/namd/" url = "file://{0}/NAMD_2.12_Source.tar.gz".format(os.getcwd()) version('2.12', '2a1191909b1ab03bf0205971ad4d8ee9') variant('fftw', default='3', values=('none', '2', '3', 'mkl'), description='Enable the use...
JoshuaSkelly/TroubleInCloudLand
main.py
Python
mit
12,372
0.003476
#!/usr/bin/python import pygame import enemies from core import balloon, bullet, game, gem, particle, player, world from scenes import credits, scene, splashscreen from ui import menu, text from utils import prettyprint, utility, vector from utils.settings import * pygame.init() utility.read_settings() if settings...
set_volume(1) pygame.mixer.set_reserved(BAAKE_CHANNEL) pygame.mixer.Chan
nel(BAAKE_CHANNEL).set_volume(1) pygame.mixer.set_reserved(BOSS_CHANNEL) pygame.mixer.Channel(BOSS_CHANNEL).set_volume(1) pygame.mixer.set_reserved(PICKUP_CHANNEL) pygame.mixer.Channel(PICKUP_CHANNEL).set_volume(1) except: utility.sound_active = False print('WARNING! - Sound not initi...
mitmedialab/MediaCloud-Web-Tools
server/views/topics/topiclist.py
Python
apache-2.0
4,869
0.002875
import flask_login import logging from flask import jsonify, request from server import app, user_db from server.auth import user_mediacloud_client, user_name, user_admin_mediacloud_client,\ user_is_admin from server.util.request import form_fields_required, arguments_required, api_error_handler logger = logging....
rn jsonify({'topics': favorited_topics}) @app.route('/api/topics/queued-and-running', methods=['GET']) @flask_login.login_required @api_error_handler def does_user_have_a_running_topic(): # save a costly set of paging queries when the user is admin if user_is_admin(): return jsonify([]) # non-admi...
queued_and_running_topics = [] more_topics = True link_id = None while more_topics: results = user_mc.topicList(link_id=link_id, limit=100) topics = results['topics'] queued_and_running_topics += [t for t in topics if t['state'] in ['running', 'queued'] ...
jpzm/bw
__init__.py
Python
gpl-2.0
1,267
0
# vim: set fileencoding=utf-8 : # Copyright (C) 2008 Joao Paulo de Souza Medeiros # # Author(s): Joao Paulo de Souza Medeiros <ignotus21@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 Foundat...
indow from buttons import BWStockButton, BWToggleStockButton from comboboxes import BWChangeableComboBoxEntry from expanders import BWExpander from frames import BWFrame from notebooks import BWNotebook from labels import BWLabel, BWSectionLabel from textview import BWTextView, B
WTextEditor from windows import BWWindow, BWMainWindow, BWAlertDialog
wangjun/pyload
module/plugins/crypter/YoutubeBatch.py
Python
gpl-3.0
6,087
0.003286
# -*- coding: utf-8 -*- """ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in...
ageToken": token}) playlist = self.api_
response("playlistItems", req) for item in playlist["items"]: yield item["contentDetails"]["videoId"] if "nextPageToken" in playlist: for item in self._getVideosId(id, playlist["nextPageToken"]): yield item def getVideosId(self, p_id): return list(s...
valentin-krasontovitsch/ansible
lib/ansible/modules/cloud/openstack/_os_server_actions.py
Python
gpl-3.0
533
0.003752
#!/usr/bin/python # -*- coding: utf-8 -*-
# Copyright: (c) 2018, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_M
ETADATA = {'metadata_version': '1.1', 'status': ['removed'], 'supported_by': 'community'} from ansible.module_utils.common.removed import removed_module if __name__ == '__main__': removed_module(removed_in='2.8')