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
JHUISI/charm
charm/adapters/kpabenc_adapt_hybrid.py
Python
lgpl-3.0
2,476
0.007674
from charm.toolbox.pairinggroup import PairingGroup,GT,extract_key from charm.toolbox.symcrypto import AuthenticatedCryptoAbstraction from charm.toolbox.ABEnc import ABEnc from charm.schemes.abenc.abenc_lsw08 import KPabe debug = False class HybridABEnc(ABEnc): """ >>> from charm.schemes.abenc.abenc_lsw08 imp...
abenc = scheme self.group = groupObj def setup(self): return abenc.setup() def keygen(self, pk, mk, object): return abenc.keygen(pk, mk, object) def encrypt(self, pk, M, object): key = self.group.random(GT) c1 = abenc.encrypt(pk, key, object) ...
(key)) c2 = cipher.encrypt(M) return { 'c1':c1, 'c2':c2 } def decrypt(self, ct, sk): c1, c2 = ct['c1'], ct['c2'] key = abenc.decrypt(c1, sk) cipher = AuthenticatedCryptoAbstraction(extract_key(key)) return cipher.decrypt(c2) def main(): groupObj = Pairin...
pombredanne/func
func/minion/modules/func_module.py
Python
gpl-2.0
4,487
0.007577
## ## Copyright 2007, Red Hat, Inc ## see AUTHORS ## ## This software may be freely redistributed under the terms of the GNU ## general public license. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 675 Mass Ave...
_methods.keys() def __module_version(self): return self.version def __module_api_version(self): return self.api_version def __module_description(self): return self.description def __is_publ
ic_valid_method(self,attr): if inspect.ismethod(getattr(self, attr)) and attr[0] != '_' and\ attr != 'register_rpc' and attr!='register_method_args': return True return False def __get_method_args(self): """ Gets arguments with their formats accor...
bcamacho/diverscoin
qa/rpc-tests/test_framework/test_framework.py
Python
mit
8,261
0.002663
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # Base class for RPC testing import logging import optparse import os import sys import shutil import te...
cks(self.nodes[2:]) sync_mempools(self.nodes[:2]) sync_mempools(self.nodes[2:]) else:
sync_blocks(self.nodes) sync_mempools(self.nodes) def join_network(self): """ Join the (previously split) network halves together. """ assert self.is_network_split stop_nodes(self.nodes) self.setup_network(False) def main(self): parser = op...
googleapis/python-redis
samples/generated_samples/redis_v1beta1_generated_cloud_redis_reschedule_maintenance_sync.py
Python
apache-2.0
1,620
0.000617
# -*- coding: utf-8 -*- # Copyright 2022 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
.RescheduleMaintenanceRequest( name="name_value", reschedule_type="SPECIFIC_TIME", ) # Make the request operation = client.reschedule_maintenance(request=request) print("Waiting for operation to complete...")
response = operation.result() # Handle the response print(response) # [END redis_v1beta1_generated_CloudRedis_RescheduleMaintenance_sync]
tonysyu/matplotlib-style-gallery
mpl_style_gallery/__main__.py
Python
bsd-3-clause
2,157
0
#!/usr/bin/env python """ Create Matplotlib style gallery for all stylesheets and display in the browser. By default, all plots are rebuilt, but this can be avoided using the `--skip-build` (`-s`) flag. To build a static website, run suppress user input and set a static output directory:: python -m mpl_style_gal...
ve static files to static output directory.") args = parser.parse_args() if not args.skip_build: remove_directory(disk.build_dir) build.save_all_plots() gallery = app.GalleryApp(args.no_input) if args.static_output: output = gallery.render_static() save_static_ou
tput(output, args.static_output) elif args.serve: hostname, port = args.serve gallery.serve(hostname, port) else: gallery.open() if __name__ == '__main__': main()
GeographicaGS/moocng
moocng/badges/migrations/0011_badgesbycoursemultilang.py
Python
apache-2.0
26,422
0.007305
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 i
mport SchemaMigration from django.db import models class Migration(Sch
emaMigration): def forwards(self, orm): # Adding field 'BadgeByCourse.title_en' db.add_column('badges_badgebycourse', 'title_en', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True), keep_default=False) # Adding fi...
sburnett/seattle
nodemanager/tests/testnmthreadingerror.py
Python
mit
4,647
0.013557
import os import unittest import nmthreadingerror import nmrestrictionsprocessor class TestRestrictionsProcessor(unittest.TestCase): def setUp(self): self.contentStr = "resource cpu .10\nresource events 100\n" self.contentStr2 = "resource cpu .05\nresource events 50\n" self.contentArr = ["resource cpu ...
ilename, "w") fileo.write(self.contentStr) fileo.close() # Get the data using read_restrictions_file data = nmrestrictionsprocessor.read_restrictions_file(self.filename) # Check that it is equal to what is expected self.assertEqual(self.contentArr, data) def
testwrite(self): # Write the data using read_restrictions_file data = nmrestrictionsprocessor.write_restrictions_file(self.filename, self.contentArr); # Read in the file fileo = open(self.filename) contents = fileo.read() fileo.close() # Check that it is equal to what is expected ...
TheWeiTheTruthAndTheLight/senior-design
src/ml.py
Python
mit
4,197
0.006671
import pickle import warnings from copy import deepcopy from datetime import datetime from itertools import islice, tee from os import listdir from random import shuffle import numpy as np from json_io import tweet_iterate from nlp import * from sklearn.ensemble import VotingClassifier from sklearn.feature_extraction ...
t(np.arange(0,20,0.1)), 'binarize':list(np.arange(0.1,0.9,0.1))}), # (MultinomialNB(),{'alpha':list(np.arange(0,20,0.1))}) ] FILENAME_REGEX = r'[ :<>".*,|\/]+' PICKLED_FEATS_DIR = 'pickledfeatures/' JSON_DIR = '../json/' def trainTest(X, y, classifier
s=DEFAULT_CLASSIFIERS, reduce=0, splits=10, trainsize=0.8, testsize=0.2): sss = StratifiedShuffleSplit(n_splits=splits, test_size=testsize, train_size=trainsize) results = [] for i, (train_index, test_index) in enumerate(sss.split(X, y)): X_train = X[train_index] y_train = y[train_index] ...
rajegannathan/grasp-lift-eeg-cat-dog-solution-updated
python-packages/mne-python-0.10/mne/minimum_norm/tests/test_psf_ctf.py
Python
bsd-3-clause
2,926
0
import os.path as op import mne from mne.datasets import testing from mne import read_forward_solution from mne.minimum_norm import (read_inverse_operator, point_spread_function, cross_talk_function) from mne.utils import slow_test, run_tests_if_main from nose.tools import assert_true d...
inverse_operator = read_inverse_operator(fname_inv) # Test PSFs (then CTFs)
for mode in ('sum', 'svd'): stc_psf, psf_ev = point_spread_function( inverse_operator, forward, method=method, labels=labels, lambda2=lambda2, pick_ori='normal', mode=mode, n_svd_comp=n_svd_comp) n_vert, n_samples = stc_psf.shape ...
zielmicha/satori
satori.web/satori/web/views/contest/extends.py
Python
mit
4,539
0.018727
# vim:ts=4:sts=4:sw=4:expandtab from satori.client.common import want_import want_import(globals(), '*') from satori.web.utils.decorators import contest_view from django import forms from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse...
atus',value=(lambda table,i : table.results[i][1]),id=2)) self.fields.append(TableField(name='',value='Revoke',render=(lambda table,i : RenderObjectButton(name='revoke',buttonname='Revoke',id=table.results[i][0].id,css='button button_small')),id=3)) if request.method == "POST": if 'revo...
Privilege.revoke(role=c,entity=p,right='SUBMIT') return HttpResponseRedirect(reverse('extends',args=[page_info.contest.id])) form = ExtendForm(request.POST) if form.is_valid(): data = form.cleaned_data c = Contestant(int(data['contestant'])) start_on...
Morbotic/pronto-distro
externals/libbot-drc/bot2-lcm-utils/python/src/bot_log2mat/scan_for_lcmtypes.py
Python
lgpl-2.1
4,032
0.007688
#!/usr/bin/python import re import os import sys import pyclbr def find_lcmtypes(): alpha_chars = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") valid_chars = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") lcmtypes = [] regex = re.compile("_get_packed_fingerprint") ...
if mod_basename[0] not in alpha_chars: valid_modname =
False if not valid_modname: continue # quick regex test -- check if the file contains the # word "_get_packed_fingerprint" full_fname = os.path.join(root, fname) try: contents = open(full_fname, "r").read() e...
Collisio-Adolebitque/pfne-2017
py-junos-eznc/tests/unit/test_console.py
Python
gpl-3.0
10,886
0.001929
import unittest2 as unittest from jnpr.junos.utils.config import Config from nose.plugins.attrib import attr from mock import MagicMock, patch import re import sys import os from lxml import etree import six from jnpr.junos.console import Console from jnpr.junos.transport.tty_netconf import tty_netconf from jnpr.junos...
eturn_value = [facts_session] self.dev.gather_facts = True self.dev.op
en() self.assertEqual(self.dev.facts, {'2RE': False, 'RE_hw_mi': False, 'ifd_style': 'CLASSIC', 'serialnumber': 'UNKNOWN', 'model': 'UNKNOWN', ...
sarthakmeh03/django
tests/admin_views/tests.py
Python
bsd-3-clause
284,922
0.002788
# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime import json import os import re import unittest from django.contrib.admin import AdminSite, ModelAdmin from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.models import ADDITION, DELETION, LogEntry from...
.b2) cls.cx1 = ChapterXtra1.objects.create(chap=cls.chap1, xtra='ChapterXtra1 1') cls.cx2 = ChapterXtra1.objects.create(chap=cls.chap3, xtra='ChapterXtra1 2') # Post data for edit inline cls.inline_po
st_data = { "name": "Test section", # inline data "article_set-TOTAL_FORMS": "6", "article_set-INITIAL_FORMS": "3", "article_set-MAX_NUM_FORMS": "0", "article_set-0-id": cls.a1.pk, # there is no title in database, give one here or forms...
julianwang/cinder
cinder/volume/drivers/netapp/dataontap/client/api.py
Python
apache-2.0
21,951
0
# Copyright (c) 2012 NetApp, Inc. All rights reserved. # Copyright (c) 2014 Navneet Singh. All rights reserved. # Copyright (c) 2014 Glenn Gobeli. All rights reserved. # Copyright (c) 2014 Clinton Knight. All rights reserved. # # Licensed under the Apache License
, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distri...
press or implied. See the # License for the specific language governing permissions and limitations # under the License. """ NetApp API for Data ONTAP and OnCommand DFM. Contains classes required to issue API calls to Data ONTAP and OnCommand DFM. """ import copy import urllib2 from lxml import etree from oslo...
gitsimon/tq_website
payment/management/commands/parse_iso_20022_files.py
Python
gpl-2.0
967
0.001034
import logging from django.core.management.base import BaseCommand from payment.postfinance_connector import ISO2022Parser log = logging.getLogger('tq') class Command(BaseCommand): help = '(re)parse ISO 20022 files, ignoring duplicates' def add_arguments(self, parser): parser.add_argument( ...
default=False, help='parse file also if already processed', ) def handle(self, *args, **options): log.info('run management command: {}'.format(__file__)) parser = ISO2022Parser() count = parser.parse(reparse=options['reparse'], dry_run=options['dry_run']) lo...
new transactions'.format(count))
sandialabs/BioCompoundML
bcml/Chemoinformatics/experimental.py
Python
bsd-3-clause
5,477
0.002191
""" This module parses experimental/computed data from NCBI """ from __future__ import print_function import sys import re import os _path = os.path.abspath(__file__) _directory = os.path.dirname(_path) _features_list = _directory + '/feature_list.txt' def dictitems(dict): if sys.version_info[0]>=3: retu...
'' for id, compound in dictitems(self.compound.copy()): binhash = compound['experimentalhash'] for key, value in dictitems(binhash.copy()): if key not in self.variable: self.compound[id]['experimentalhash'].pop(ke
y, None) def _variable_features(self): '''Start by deciding which features to include, this is by default the 26 features stored in feature_list.txt''' features = _add_feature_list() self.total = {} self.variable = {} for _id, compound in dictitems(self.compound.copy...
nikste/tensorflow
tensorflow/python/summary/event_multiplexer.py
Python
apache-2.0
14,543
0.003232
# 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...
is not None: logging.info('Event Multplexer doing initialization load for %s', run_path_map) for (run, path) in six.iteritems(run_path_map): self.AddRun(path, run) logging.info('Event Multiplexer done initializing') def AddRun(self, path, name=None): """Add a run to th...
is not specified, it is the same as the path. If a run by that name exists, and we are already watching the right path, do nothing. If we are watching a different path, replace the event accumulator. If `Reload` has been called, it will `Reload` the newly created accumulators. Args: ...
locationtech/geowave
python/src/main/python/pygw/store/hbase/options.py
Python
apache-2.0
2,740
0.001825
# # Copyright (c) 2013-2020 Contributors to the Eclipse Foundation # # See the NOTICE file distributed with this work for additional information regarding copyright # ownership. All rights reserved. This program and the accompanying materials are made available # under the terms of the Apache License, Version 2.0 whic...
anCacheSize()
def set_verify_coprocessors(self, verify_coprocessors): """ Sets whether or not to verify coprocessors when performing operations. Args: verify_coprocessors (bool): Whether or not to verify coprocessors. """ self._base_options.setVerifyCoprocessors(verify_copro...
karthik-sethuraman/ONFOpenTransport
RI/flask_server/tapi_server/models/tapi_notification_name_and_value_change.py
Python
apache-2.0
3,735
0.000268
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from tapi_server.models.base_model_ import Model from tapi_server import util class TapiNotificationNameAndValueChange(Model): """NOTE: This class is auto generat...
tapi.notification.NameAndValueChange of this TapiNotificationNameAndValueChange. # noqa: E501 :rtype: TapiNotificationNameAndValueChange """ return util.deserialize_model(dikt, cls) @property def value_name(self): """Gets the value_name of this TapiNotificationNameAndValueChang...
n: The value_name of this TapiNotificationNameAndValueChange. :rtype: str """ return self._value_name @value_name.setter def value_name(self, value_name): """Sets the value_name of this TapiNotificationNameAndValueChange. The name of the value. The value need not have a...
hiorws/ulakbus
ulakbus/views/personel/yeni_ekle.py
Python
gpl-3.0
8,289
0.000605
# -*- coding: utf-8 -*- """ """ # Copyright (C) 2015 ZetaOps Inc. # # This file is licensed under the GNU General Public License v3 # (GPLv3). See LICENSE.txt for details. # # Yeni Personel Ekle WF adimlarini icerir. from pyoko.model import field from pyoko import form from zengine.lib.forms import JsonForm from ze...
900", "dogum_yeri": "Afyon", "dogum_tarihi": "10.10.1940"} current.task_data['mernis_tamam'] = True current.task_data['kimlik_bilgileri'] = response current.s
et_message(title='%s TC no için Hitap servisi başlatıldı' % tckn, msg='', typ=1, url="/wftoken/%s" % current.token) def mernis_adres_bilgileri_getir(tckn): # mernis servisi henuz hazir degil # from ulakbus.services.zato_wrapper import MernisAdresBilgileriGetir # mernis_bilgileri = ...
laijingtao/landlab
landlab/components/radiation/__init__.py
Python
mit
2,298
0
"""Landlab component that simulates relative incidence shortwave radiation on sloped surface. Landlab component that computes 1D and 2D total incident shortwave radiation. This code also computes relative incidence shortwave radiation compared to a flat surface. Ref: Bras, Rafael L. Hydrology: an introduction to hydro...
= Radiation(grid) Run the *update* method to update output variables with current time >>> current_time = 0.5 >>> rad.update(current_time) >>> rad.grid.at_cell['radiation__ratio_to_flat_surface'] array([ 0.38488566, 0.38488566, 0.33309785, 0.33309785, 0.37381705, 0.37381705]) >>> rad.grid.at_cell['radiat...
hortwave_flux'] array([ 398.33664988, 398.33664988, 344.73895668, 344.73895668, 386.88120966, 386.88120966]) """ from .radiation import Radiation __all__ = ['Radiation', ]
thomasquintana/freepy
tests/fsm_tests.py
Python
apache-2.0
5,402
0.019622
# 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 u...
e 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, # so
ftware 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. # # Thomas Quintana <quintana.thomas@gmail.com> from lib.fsm impo...
diogocs1/comps
web/addons/sale_journal/__openerp__.py
Python
apache-2.0
2,681
0.001492
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
ll be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU A
ffero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Invoicing Journals', ...
fei-chen/AmberAlert
deployment/cassandra/conf/ganglia/python_modules/simple_diskstats.py
Python
apache-2.0
2,551
0.02352
#!/usr/bin/python import sys, os, time, sched, re, getopt, fnmatch import types, resource, getpass, glob, linecache import copy name_prefix = 'simple_diskstats_' bytes_read = name_prefix + 'bytes_read' bytes_written = name_prefix + 'bytes_written' params = { 'filepath' : '/proc/diskstats' } curr_metrics = { byt...
n fd.readlines(): l = line.split() if len(l) < 13: continue if l[5] == '0' and l[9] == '0': continue if l[3:] == ['0',] * 11: continue curr_metrics[name]['value'] =
curr_metrics[name]['value'] + long(l[diskstat_indices[name]]) curr_metrics[name]['time'] = time.time() def get_delta(name): get_metrics(name) '''Translate number of sectors to number of bytes.''' delta = (curr_metrics[name]['value'] - last_metrics[name]['value']) * 512.0 / (curr_metrics[name]['time'] - last_m...
demisto/content
Packs/GraphQL/Integrations/GraphQL/GraphQL.py
Python
mit
4,011
0.002493
from itertools import zip_longest from typing import Callable, Dict import urllib3 import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * from gql import Client, gql from gql.transport.requests import RequestsHTTPTransport # Disable insecure warnings urllib3.disable_warni...
elif command == 'graphql-mutation': return_results(execute_query(client, demisto.args())) else: raise NotImplementedErr
or(f"Received an un-supported command: {command}") except Exception as e: demisto.error(traceback.format_exc()) return_error(f'Failed to execute {command} command. Error: {str(e)}') if __name__ in ('__main__', '__builtin__', 'builtins'): main()
cderici/pycket
pycket/option_helper.py
Python
mit
13,785
0.002466
#! /usr/bin/env python # -*- coding: utf-8 -*- # from rpython.rlib import jit def print_help(argv): print """Welcome to Pycket. %s [<option> ...] <argument> ... File and expression options: -e <exprs>, --eval <exprs> : Evaluate <exprs>, prints results -f <file>, --load <file> : Like -e '(loa...
add_name(names, 'loads', "load") add_name(names, 'load_arguments', argv[i]) if argv[i-1] in ["-r", "--script"]: add_name(names, 'set-run-file', argv[i]) retval = RETURN_OK elif argv[i] in ["-t", "--require", "-u", "--require-script"]: if ...
_name(names, 'loads', "file") add_name(names, 'load_arguments', argv[i]) if argv[i-1] in ["-u", "--require-script"]: add_name(names, 'set-run-file', argv[i]) config['no-lib'] = True retval = RETURN_OK elif argv[i] in ["-l", "--lib"]: ...
microsoft/O-CNN
tensorflow/script/network_cls.py
Python
mit
2,557
0.011341
import tensorflow as tf from ocnn import * # octree-based resnet55 def network_resnet(octree, flags, training=True, reuse=None): depth = flags.depth channels = [2048, 1024, 512, 256, 128, 64, 32, 16, 8] with tf.variable_scope("ocnn_resnet", reuse=reuse): data = octree_property(octree, property_name="feature...
g) data, _ = octree_max_pool(data, octree, d) with tf.variable_scope("full_voxel"): data = octree_full_voxel(data, depth=2) data = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc1"): data = fc_bn_relu(data, channels[2], training=training) dat
a = tf.layers.dropout(data, rate=0.5, training=training) with tf.variable_scope("fc2"): logit = dense(data, flags.nout, use_bias=True) return logit def cls_network(octree, flags, training, reuse=False): if flags.name.lower() == 'ocnn': return network_ocnn(octree, flags, training, reuse) elif fla...
theguardian/JIRA-APPy
lib/apscheduler/triggers/cron/fields.py
Python
gpl-2.0
3,047
0.002297
""" Fields represent CronTrigger options which map to :class:`~datetime.datetime` fields. """ from calendar import monthrange from lib.apscheduler.triggers.cron.expressions import ( AllExpression, RangeExpression, WeekdayPositionExpression, LastDayOfMonthExpression, WeekdayRangeExpression) __all__ = ('MIN_VALUE...
e in self.expressions) return ','.join(expr_strings) def __repr__(self): return "%s('%s', '%s')" % (self.__class__.__name__, self.name, self) class WeekField(BaseField): REAL = False def get_value(self, dateval): return dateval.isocalendar()[1] class DayOfMonthField(BaseField)...
Expression] def get_max(self, dateval): return monthrange(dateval.year, dateval.month)[1] class DayOfWeekField(BaseField): REAL = False COMPILERS = BaseField.COMPILERS + [WeekdayRangeExpression] def get_value(self, dateval): return dateval.weekday()
dbf256/py-ya-xml
setup.py
Python
mit
362
0
from setuptools import setup set
up(name='pyyaxml', version='0.6.7', description='Python API to Yandex.XML', url='https://github.com/dbf256/py-ya-xml', author='Alexey Moskvin', author_email='dbf256@gmail.com', license='MI
T', packages=['pyyaxml'], install_requires=[ 'six', ], zip_safe=False)
mcallaghan/tmv
BasicBrowser/scoping/migrations/0197_auto_20180528_1537.py
Python
gpl-3.0
3,055
0
# Generated by Django 2.0.5 on 2018-05-28 15:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('scoping', '0196_auto_20180528_0902'), ] operations = [ migrations.AddField( model_name='docpar', name='endColor', ...
ar', name='height', field=models.FloatField
(null=True), ), migrations.AddField( model_name='docpar', name='imputed_role', field=models.CharField(max_length=50, null=True), ), migrations.AddField( model_name='docpar', name='maxX', field=models.FloatField(null=...
jonatanolofsson/req
req/filesystem.py
Python
gpl-3.0
1,429
0.0014
""" Filesystem related methods """ import os import yaml from . import comm
and as subprocess from . import util GIT = ['git'] REQCONF_FILE = '.reqconfig' def read_file(path, ref=None): """ Read file from filesystem or git tree """ def _load_file_from_fs(): """ Read and parse file from filesystem """ with open(path) as file_:
return file_.read() def _load_file_from_git(): """ Load file from git tree """ blob_sha1 = subprocess.get_output( GIT + ['ls-tree', ref, path] ).split()[2] return subprocess.get_output( GIT + ['cat-file', 'blob', blob_sha1] )...
ereslibre/salt
salt/_modules/caasp_hosts.py
Python
apache-2.0
11,073
0.001716
from __future__ import absolute_import import difflib import os from salt.ext import six from salt.utils.odict import OrderedDict try: from salt.exceptions import InvalidConfigError except ImportError: from salt.exceptions import SaltException class InvalidConfigError(SaltException): ''' ...
pty strings res.sort() # sort the result (for determinism) return res def _load_lines(filename): __utils__['caasp_log.debug']('hosts: loading %s', filename) with open(filename, 'r') as f: lines = [x.strip().replace('\n', '') for x in f.readlines()] # remove any trailing empty lines w...
return lines def _write_lines(dst, contents): with open(dst, 'w+') as ofile: for line in contents: ofile.write(line + six.text_type(os.linesep)) # note: /etc/hosts needs to end with a newline so # that some utils that read it do not break ofile.write(six.text...
greenstatic/maas-reservation-system
maas_reservation_system/reservation_system/migrations/0021_auto_20170924_0855.py
Python
mit
717
0.002789
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-09-24 08:55 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Mig
ration): dependencies = [ ('reservation_system', '0020_auto_20170924_0838'), ] operations = [ migrations.CreateModel( name='PlatformSettings', fields=[ ('settingId', models.CharField(max_length=30, primary_key=True, serialize=False, verbose_name='Set...
servationDefaults', ), ]
Altoidnerd/cards
game.py
Python
mit
845
0.010651
#!/usr/bin/env python3 import itertools, random from pokerHands import * # create deck deck = getDeck() fred = OrderedCards() al = OrderedCards() burn = OrderedCards() community = OrderedCards() deck.deal(
2, al, fred) print("Fred's hand: " + str(fred)) print("Al's hand: " + str(al)) deck.deal(1,burn) deck.deal(3,commu
nity) print("Flop: " + str(community)) deck.deal(1,burn) deck.deal(1,community) print("Turn: " + str(community)) deck.deal(1,burn) deck.deal(1,community) print("River: " + str(community)) com2 = OrderedCards(community.cards_list[:]) community.deal(5,fred) com2.deal(5,al) fredHand = evalHand(fred) alHand = evalHand(al) ...
aaronsnig501/foreign-guides
apps/accounts/admin.py
Python
mit
113
0.00885
f
rom django.contrib import admin from .models import Use
r # Register your models here. admin.site.register(User)
codypiersall/mlab
src/mlab/releases.py
Python
mit
4,746
0.001896
''' MLAB calls MATLAB funcitons and looks like a normal python library. authors: Yauhen Yakimovich <eugeny.yakimovitch@gmail.com> Module wrapping borrowed from `sh` project by Andrew Moffat. ''' import os import sys from types import ModuleType from mlabwrap import (MlabWrap, choose_release, find_available_releas...
how about an return a function variable? # try: return os.environ[k] # except KeyError: pass # is it a "release version"? if k.startswith('R') and k in self._available_releases: self[k] = self.get_mlab_instance(k) return self[k
] if k == 'latest_release': matlab_release = self.pick_latest_release() instance = self.get_mlab_instance(matlab_release) self[k] = instance self[matlab_release] = instance return instance if self.__selected_instance is not None: ...
MadManRises/Madgine
shared/bullet3-2.89/examples/pybullet/gym/pybullet_envs/deep_mimic/env/env.py
Python
mit
348
0.014368
from abc import abstractmethod import sys, abc if sys.version_info >= (3, 4): ABC = abc.ABC else
: ABC = abc.ABCMeta('ABC', (), {}) import numpy as np from enum import Enum class Env(ABC): class Terminate(Enum): Null = 0 Fail = 1 Succ = 2 def __init__(self, args, enable_dra
w): self.enable_draw = enable_draw return
pescobar/easybuild-easyblocks
easybuild/easyblocks/m/mrtrix.py
Python
gpl-2.0
5,093
0.002749
## # Copyright 2009-2020 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (F...
pts'), self.installdir) # some scripts expect 'release/bin' to be there, so we put a symlink in place symlink(self.installdir, os.path.join(self.installdir, 'release')) def make_module_req_guess(self): """ Return list of subdirectories to consider to update envir
onment variables; also consider 'scripts' subdirectory for $PATH """ guesses = super(EB_MRtrix, self).make_module_req_guess() guesses['PATH'].append('scripts') if LooseVersion(self.version) >= LooseVersion('3.0'): guesses.setdefault('PYTHONPATH', []).append('lib') ...
EliotBryant/ShadDetector
shadDetector_testing/Colour Based Methods/ColorHistogram-master/color_histogram/core/hist_2d.py
Python
gpl-3.0
4,830
0.002277
# -*- coding: utf-8 -*- ## @package color_histogram.core.hist_2d # # Implementation of 2D color histograms. # @author tody # @date 2015/08/28 import numpy as np from color_histogram.core.color_pixels import ColorPixels from color_histogram.core.hist_common import colorCoordinates, colorDensities, rgbCo...
rget color channels.
[0, 1] with 'hsv' means (h, s) channels. def __init__(self, image, num_bins=16, alpha=0.1, color_space='hsv', channels=[0, 1]): self._computeTargetPixels(image, color_space, channels) self._num_bins = num_bins self._alpha = alpha self._color_space = color_space self._channel...
oubiwann/openpix
openpix/util.py
Python
lgpl-2.1
6,891
0.000726
import os import re import crypt import random import readline from datetime import datetime from pyparsing import oneOf import openpix from openpix import art from openpix import meta dividerSegment = "_" * 34 bannerDivider = "\n %s .:|:. %s\n" % (dividerSegment, dividerSegment) starterHelp = "Type help or '?' fo...
the code to change the password crypt checking, when we need to do that. """ return crypt.crypt(clearText, seed) def checkCryptPassword(clearText, check): """ A utility function for checking the authenticity of a password. """ seed = check[:2] crypted = generateCryptedPass(clearText, ...
intended to be used by the setup function for the admin SSH server, but there's no reason it can't be used elsewhere. """ import txlb limitedNamespace = namespace thisNamespace = globals() thisNamespace.update(locals()) for key in ('__builtins__', '__doc__', 'help', 'txlb'): if key ...
ktan2020/legacy-automation
win/Lib/site-packages/Crypto/Hash/hashalgo.py
Python
mit
3,984
0.00251
# -*- coding: utf-8 -*- # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to e...
es. It may contain non-ASCII characters, including null bytes. """ return self._hash.digest() def hexdigest(self): """Return the **printable** digest of the message that has been hashed so far. This method does n
ot change the state of the hash object. :Return: A string of 2* `digest_size` characters. It contains only hexadecimal ASCII digits. """ return self._hash.hexdigest() def copy(self): """Return a copy ("clone") of the hash object. The copy will have the sam...
memsharded/conan
conans/client/build/cmake.py
Python
mit
17,896
0.003632
import os import platform import subprocess from itertools import chain from six import StringIO # Python 2 and 3 compatible from conans.client import defs_to_string, join_arguments, tools from conans.client.build.cmake_flags import CMakeDefinitionsBuilder, \ get_generator, is_multi_configuration, verbose_defini...
f.definitions = builder.get_definitions() self.toolset = toolset or get_toolset(self._settings) self.build_dir = None self.msbuild_verbosity = os.getenv("CONAN_MSBUILD_VERBOSITY") or msbuild_verbosity @property def build_folder(self): return self.build_dir @build_folder.set...
self.build_dir = value @property def build_type(self): return self._build_type @build_type.setter def build_type(self, build_type): settings_build_type = self._settings.get_safe("build_type") if build_type != settings_build_type: self._conanfile.output.warn("Force...
matthiaskramm/corepy
corepy/arch/spu/isa/spu_isa.py
Python
bsd-3-clause
22,294
0.036153
# Copyright (c) 2006-2009 The Trustees of Indiana University. # All rights reserved. # # Redistribution and use in source and binary forms, with or without ...
cles = (0, 4, 0) class absdb(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':83} cycles = (0, 4, 0) class sumb(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':595} cycles = (0, 4, 0) class xsbh(Instruction): machine_inst = OPCD_A_T params = {'OPCD':694} cycles = (0, 2, 0) cla...
cles = (0, 2, 0) class xswd(Instruction): machine_inst = OPCD_A_T params = {'OPCD':678} cycles = (0, 2, 0) class and_(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':193} cycles = (0, 2, 0) class andc(Instruction): machine_inst = OPCD_B_A_T params = {'OPCD':705} cycles = (0, 2, 0) cla...
rismalrv/edx-platform
openedx/core/djangoapps/credit/api/provider.py
Python
agpl-3.0
15,435
0.002527
""" API for initiating and tracking requests for credit from a provider. """ import datetime import logging import pytz import uuid from django.db import transaction from lms.djangoapps.django_comment_client.utils import JsonResponse from openedx.core.djangoapps.credit.exceptions import ( UserIsNotEligible, ...
Hogwarts School of Witchcraft and Wizardry requires learners to:</p> <ul> <li>Sample instruction abc</li> <li>Sample instruction xyz</li> </ul>", "thumbnail_url": "https://credit.example.com/logo.png" } """ credit_provider = Cr...
"provider_id": credit_provider.provider_id, "display_name": credit_provider.display_name, "provider_url": credit_provider.provider_url, "provider_status_url": credit_provider.provider_status_url, "provider_description": credit_provider.provider_description, ...
nsi-iff/nsi_site
apps/news/migrations/0003_auto__del_new__add_news.py
Python
mit
7,906
0.00721
# encoding: 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): # Deleting model 'New' db.delete_table('news_new') # Removing M2M table for field projects_relate...
db.create_table('news_new_projects_relateds', ( ('id', models.AutoField(verbose_name='ID', primary_k
ey=True, auto_created=True)), ('new', models.ForeignKey(orm['news.new'], null=False)), ('project', models.ForeignKey(orm['projects.project'], null=False)) )) db.create_unique('news_new_projects_relateds', ['new_id', 'project_id']) # Deleting model 'News' db.delet...
Ictp/indico
bin/utils/getNameBadIndexed.py
Python
gpl-3.0
1,515
0.009901
# -*- coding: utf-8 -*- ## ## ## This file is part of Indico. ## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN). ## ## Indico is free software; you ca
n 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. ## ## Indico is distributed in the hope that it will be usefu
l, 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 Indico;if not, see <http://www.gnu.org/licenses/>. ...
pulinagrawal/nupic
examples/opf/experiments/multistep/simple_3/description.py
Python
agpl-3.0
1,645
0.004863
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
eters for a prediction experiment. import os from nupic.frameworks.opf.expdescriptionhelpers import importBaseDescription # the sub-experiment configuration config = \ { 'dataSource': 'file://' + os.path.join(os.path.dirname(__file__), '../datasets/simple_3.csv'), 'modelPa...
': { 'encoders': { }, 'verbosity': 0}, 'spParams': { }, 'tmParams': { }}, 'predictionSteps': [1, 3]} mod = importBaseDescription('../base/description.py', config) locals().update(mod.__dict__)
maartenq/ansible
test/units/modules/packaging/os/test_yum.py
Python
gpl-3.0
9,340
0.003222
# -*- coding: utf-8 -*- from ansible.compat.tests import unittest from ansible.modules.packaging.os.yum import YumModule yum_plugin_load_error = """ Plugin "product-id" can't be imported Plugin "search-disabled-repos" can't be imported Plugin "subscription-manager" can't be imported Plugin "product-id" can't be imp...
1:11.2.0-0.el7 ceph librbd1.x86_64 1:11.2.0-0.el7 ceph librgw2.x86_64 1:11.2.0-0.el7 ceph python-cephfs.x86_64 1:11.2.0-0.el7 ceph pyt
hon-rados.x86_64 1:11.2.0-0.el7 ceph python-rbd.x86_64 1:11.2.0-0.el7 ceph """ # from https://github.com/ansible/ansible-modules-core/issues/4318#issuecomment-251416661 wrapped_output_4 = """ ipxe-roms-qemu.noarch 20160...
simontakite/sysadmin
pythonscripts/programmingpython/System/Threads/queuetest3.py
Python
gpl-2.0
1,403
0.006415
"same as queuetest2.py, but uses threading, not _threads" numconsumers = 2 # how many consumers to start numproducers = 4 # how many producers to start nummessages = 4 # messages per producer to put import threading, queue, time, sys safeprint = threading.L...
ue)) thread.daemon = True # else cannot exit! thread.start() waitfor =
[] for i in range(numproducers): thread = threading.Thread(target=producer, args=(i, dataQueue)) waitfor.append(thread) thread.start() for thread in waitfor: thread.join() # or time.sleep() long enough here print('Main thread exit.')
LaurentClaessens/phystricks
testing/demonstration/phystricksQWEHooSRqSdw.py
Python
gpl-3.0
390
0.05641
from phys
tricks import * def QWEHooSRqSdw(): pspict,fig = SinglePicture("QWEHooSRqSd
w") pspict.dilatation(3) A=Point(0,0) O=Point(0,2) B=Point(3,0) s1=Segment(A,O) s2=Segment(O,B) angle=AngleAOB(A,O,B,r=0.7) angle.put_mark(text="\( c\)",pspict=pspict) pspict.DrawGraphs(angle,s1,s2) fig.no_figure() fig.conclude() fig.write_the_file()
braoru/check-windows-by-winrm
check_services_state_winrm.py
Python
agpl-3.0
10,350
0.003092
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2013: # Sébastien Pasche, sebastien.pasche@leshop.ch # Mikael Bugnon, mikael.bugnon@leshop.ch # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # ...
DE_LIST = frozenset( [ 'sppsvc', 'ShellHWDetection', 'BMR Boot Service', 'NetBackup SAN Client Fibre Transport Service', 'clr_optimization', 'Sophos Web Intelligence Update', 'Check_MK
_Agent', 'TeamViewer9', 'SysmonLog', 'gupdate', 'swi_update_64', 'swi_service', 'stisvc', 'vimPBSM', 'vimQueryService', 'Citrix Licensing', 'CitrixXenAppCommandsRemoting', 'RemoteRegistry', 'TrustedInstaller' ] ) MANUA...
Schevo/kiwi
tools/glade_conversor.py
Python
lgpl-2.1
1,442
0.002774
#!/usr/bin/env python import os import sys filters = [ ('<requires lib="Kiwi2.Widgets"/>', '<requires lib="kiwi"/>'), ("Kiwi2+Widgets+CheckButton", "kiwi+ui+widgets+checkbutton"), ("Kiwi2+Widgets+ComboBox", "kiwi+ui+widgets+combobox"), ("Kiwi2+Widgets+Entry", "kiwi+ui+widgets+entry"), ("Kiwi2+Widge...
lines(): for filter in filters: line = apply_filter(filter, line) out.write(line) os.unlink(filename) os.rename(tmp
, filename) if __name__ == '__main__': sys.exit(main(sys.argv))
grepme/CMPUT410Lab01
virt_env/virt1/lib/python2.7/site-packages/PasteScript-1.7.5-py2.7.egg/paste/script/util/logging_config.py
Python
apache-2.0
12,245
0.002858
# Copyright 2001-2005 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permissio...
ys.platform == "win32": RESET_ERROR = 10054 #WSAECONNRESET else: RESET_ERROR =
104 #ECONNRESET # # The following code implements a socket listener for on-the-fly # reconfiguration of logging. # # _listener holds the server object doing the listening _listener = None def fileConfig(fname, defaults=None): """ Read the logging configuration from a ConfigParser-format file. ...
littleDad/mesLucioles
app/__init__.py
Python
gpl-2.0
1,638
0.007326
# -*- coding: utf8 -*- # main from flask import Flask coreApp = Flask(__name__) coreApp.config.from_object('config') # db from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy(coreApp) # sessions, users and logins from flask_login import LoginManager # handle our users logged in state lm = LoginManager() lm.ini...
p.debug: # import logging # from logging.handlers import RotatingFileHandler # file_handler = RotatingFileHandler('data/coreApp.log', 'a', 1 * 1024 * 1024, 10) # log file size limited to 1Mb ; keep last 10 log files as backup # file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(me...
el(logging.INFO) # file_handler.setLevel(logging.INFO) # coreApp.logger.addHandler(file_handler) # coreApp.logger.info('coreApp startup')
antoinecarme/sklearn2sql_heroku
tests/regression/freidman2/ws_freidman2_Ridge_oracle_code_gen.py
Python
bsd-3-clause
122
0.016393
from sklearn2sql_her
oku.tests.regression import generic as reg_gen reg_gen.test_model("Ridge" , "freidman2" ,
"oracle")
plotly/plotly.py
packages/python/plotly/plotly/validators/scatter/marker/_cmax.py
Python
mit
467
0.002141
import _plotly_utils.basevalidators class CmaxValidator(_plotly_utils.basevalidators.NumberValidator): def __init__(self, plotly_name="cmax", parent_name="scatter.marker", **kwargs): su
per(CmaxValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), implied_edits=kwa
rgs.pop("implied_edits", {"cauto": False}), **kwargs )
steeleyuk/alaska
window.py
Python
gpl-3.0
7,483
0.001604
#!/usr/bin/env python3 from gi.repository import Gtk from gi.repository import GLib import dialogs import information import menu import sonos import toolbar class Window(Gtk.Window): def __init__(self): Gtk.Window.__init__(self) self.set_default_size(400, 250) self.set_title('Alaska - %s...
f.scalePosition = Gtk.Scale() self.scalePosition.set_hexpand(True) self.scalePosition.set_draw_value(False) grid1.attach(self.scalePosition, 2, 1, 1, 1) self.update_queue() self.update_playing_label() def on_display_changed(self, comboboxtext): if comboboxtext.get_a...
tations': self.update_radio_stations() def update_position(self): ''' Update current playing position on Scale. ''' track = sonos.sonos.get_current_track_info() self.labelPosition.set_label(track['position']) position = track['duration'].split(':') ...
rcbuild-info/scrape
rcbi/rcbi/spiders/Shendrones.py
Python
apache-2.0
2,069
0.01015
import scrapy from scrapy import log from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from rcbi.items import Part import copy import json import re VARIANT_JSON_REGEX = re.compile("product: ({.*}),") class ShendronesSpider(CrawlSpider): name = "shendrones" allowed_doma...
shopify_info = json.loads(m.group(1)) global_title = shopify_info["title"] preorder = False if global_titl
e.endswith("Pre Order"): global_title = global_title[:-len("Pre Order")].strip() variant["stock_state"] = "backordered" preorder = True for v in shopify_info["variants"]: if v["title"] != "Default Title": item["name"] = global_title + " " + v["title"] variant["u...
mbelousov/django-celery-model
djcelery_model/models.py
Python
mit
13,807
0.000072
# -*- coding: utf-8 -*- from django.db import models from django.db.models import Q from django.db.models.query import QuerySet from django.conf import settings from django.contrib.contenttypes.models import ContentType from datetime import datetime from django.utils import timezone from django.conf import settings fro...
ks__s
tate=ModelTaskMetaState.PENDING) | Q(tasks__state=ModelTaskMetaState.STARTED) | Q(tasks__state=ModelTaskMetaState.RETRY)) def with_ready_tasks(self): return self.filter(Q(tasks__state=ModelTaskMetaState.FAILURE) | Q(tasks__sta...
Taikatou/oxygine-framework
tools/resbuild/xml_processor.py
Python
mit
9,924
0.01189
from xml.dom import minidom import os import shutil from . import process_atlas from . import process_font from . import process_starling_atlas from . import oxygine_helper def as_bool(attr): if not attr: return False lw = attr.lower() return lw == "true" or lw == "1" class XmlWalker: def __in...
self.debug = args.debug self.processors = {} #self.path_current = "" self._meta_doc = None self._npot = args.npot #self._meta_element = None self.helper = oxygine_helper.helper(os.path.split(__file__)[0] + "/../../") self.register_proc...
essor(process_font.font_Processor()) self.register_processor(process_atlas.atlas_Processor()) self.register_processor(process_starling_atlas.starling_atlas_Processor()) self._current_processor = None def register_processor(self, processor): self.processors[processo...
drepetto/chiplotle
chiplotle/tools/mathtools/polar_to_xy.py
Python
gpl-3.0
434
0.006912
from chiplotle.geometry.core.coordinate
import Coordinate import math #def polar_to_xy(*args): def polar_to_xy(args): '''Converts polar (r, A) to Cartesian (x y) coordinates, where r is the radius and A is the angle in radians. ''' try: r, A = tuple(Coordinate(*args)) except: raise TypeError('`args` must be an (r, A) tup...
x = r * math.cos(A) y = r * math.sin(A) return (x, y)
Wattpad/dd-agent
tests/checks/mock/test_consul.py
Python
bsd-3-clause
21,895
0.002649
import random from tests.checks.common import AgentCheckTest, load_check from utils.containers import hash_mutable MOCK_CONFIG = { 'init_config': {}, 'instances' : [{ 'url': 'http://localhost:8500', 'catalog_checks': True, }] } MOCK_CONFIG_SERVICE_WHITELIST = { 'init_config': {}, ...
LATENCY_CHECKS = { 'init_config': {}, 'instances' : [{ 'url': 'http://localhost:8500', 'catalog_checks': True, 'network_latency_checks': True }] } MOCK_BAD_CONFIG = { 'init_config': {}, 'instances' : [{ # Multiple instances should cause it to fail 'url': 'http://loca...
01', 'catalog_checks': True, 'new_leader_checks': True, 'self_leader_check': True }] } def _get_random_ip(): rand_int = int(15 * random.random()) + 10 return "10.0.2.{0}".format(rand_int) class TestCheckConsul(AgentCheckTest): CHECK_NAME = 'consul' def mock_get_peers_in_cl...
unsalted/color_station
data-processing/crimetojson.py
Python
mit
2,401
0.005414
# First row of the csv file must be header! import csv import datetime import sys import os if len(sys.argv) != 2: os._exit(1) path=sys.argv[1] # get folder as a command line argument os.chdir(path) if not os.path.exists('./json'): os.makedirs('./json') csvFiles = [f for f in os.listdir('.') if f.endswith('....
]+'T'+row[3]+'",'+'\n') jsonData.write('\t\t\t\t'+'"sym": "Dot"'+'\n') jsonData.write('\t\t\t'+'},'+'\n') jsonData.write('\t\t\t'+'"geometry": {'+'\n') jsonData.write('\t\t\t\t'+'"type": "Point",'+'\n') jsonData.write('\t\t\t\
t'+'"coordinates": ['+'\n') jsonData.write('\t\t\t\t\t'+coord[1]+','+'\n') jsonData.write('\t\t\t\t\t'+coord[0]+','+'\n') jsonData.write('\t\t\t\t\t'+'0\n') jsonData.write('\t\t\t\t'+']\n') jsonData.write('\t\t\t'+'}\n') jso...
linpingchuan/misc
python/ml/book1/ch4/bayes2.py
Python
gpl-2.0
2,621
0.027089
# coding=utf-8 import numpy as np def textParse(bigString): import re listOfTokens=re.split(r'\W*',bigString) return [tok.lower() for tok in listOfTokens if len(tok)>2] def createVocabList(docList): vocabList=set([]) for doc in docList: vocabList=vocabList|set(doc) return list(vocabLis...
index(word)]+=1 return returnVec def trainNB0(trainMat,trainCate): numOfWord=len(trainMat[0]) numOfDoc=len(trainMat) p0Num=np.ones(numOfWord) p0Denom=float(2) p1Num=np.ones(numOfWord) p1Denom=float(2) pAbuse=sum(trainCate)/float(numOfDoc) for i in range(numOfDoc): if t
rainCate[i]==0: p0Num += trainMat[i] p0Denom += sum(trainMat[i]) else: p1Num+=trainMat[i] p1Denom+=sum(trainMat[i]) p0Vec = np.log(p0Num / p0Denom) p1Vec=np.log(p1Num/p1Denom) return p0Vec,p1Vec,pAbuse def classifyNB0(wordVec,p0Vec,p1Vec,pAbuse): ...
internap/fake-switches
fake_switches/cisco/command_processor/config_vlan.py
Python
apache-2.0
1,182
0.002538
# Copyright 2015 Internap. # # 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, so...
onfigVlanCommandProcessor, self).init(switch_configuration, terminal_controller, logger, piping_processor) self.vlan = args[0] def get_prompt(self): return self.switch_configuration.name + "(config-vlan)#" def do_name(self, *args): self.vlan.name
= (args[0][:32]) def do_exit(self): self.is_done = True
dkriegner/xrayutilities
tests/test_materials.py
Python
gpl-2.0
4,883
0
# This file is part of xrayutilities. # # xrayutilities is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed...
ce.c = self.c self.p1mat.lattice.alpha = self.alpha self.p1mat.lattice.beta = self.beta self.p1mat.lattice.gamma = self.gamma self.test_Bmatrix() def test_environment(self): maxdist = max(self.a, self.b, self.c) + 0.01 e = self.p1mat.environment((0, 0, 0), maxdist=ma...
or dis in (0.0, self.a, self.b, self.c): found = False for d, at, mult in e: if numpy.isclose(d, dis): found = True self.assertTrue(found, "expected atomic distance not found") def test_environment_Si(self): a = xu.materials.Si.a ...
GeoMop/GeoMop
src/gm_base/model_data/format.py
Python
gpl-3.0
4,784
0.000209
""" Contains format specification class and methods to parse it from JSON. .. codeauthor:: Tomas Krizek <tomas.krizek1@tul.cz> """ import json import re def get_root_input_type_from_json(data): """Return the root input type from JSON formatted string.""" return parse_format(json.loads(data)) def parse_form...
return False return RE_PARAM.match(value) def _substitute_ids_with_references(input_types): """Replaces ids or type names with python object references.""" input_type = {} def _substitute_implementations(): """Replaces implementation ids with input_types.""" impls = {} for i...
ype_ = input_types[id_] impls[type_['name']] = type_ input_type['implementations'] = impls def _substitute_default_descendant(): """Replaces default descendant id with input_type.""" id_ = input_type.get('default_descendant', None) if id_ is not None: input_t...
jacebrowning/gridcommand
gridcommand/tests/test_stores_game.py
Python
lgpl-3.0
2,331
0
# pylint: disable=unused-argument,no-self-use import os import tempfile import logging import pytest from gridcommand.stores import GameMemoryStore, GameFileStore from gridcommand import domain @pytest.mark.parametrize("store_class", [GameMemoryStore, GameFileStore]) class TestGameStore: def setup_method(self...
def test_delete_existing(self, store_class): store = store_class() game = domain.Game() store.create(game) store.delete(game) game2 = store.read(game.key) assert game
2 is None def test_delete_missing(self, store_class): store = store_class() game = domain.Game() store.delete(game) game2 = store.read(game.key) assert game2 is None
laborautonomo/opps
opps/utils/__init__.py
Python
mit
84
0
# coding: utf-8 """ utils module to organiz
e c
ommom use utilities and functions """
jgmanzanas/CMNT_004_15
project-addons/importation/import_account_due_list.py
Python
agpl-3.0
16,719
0.000718
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import xmlrpclib import socket import xlrd import datetime class import_account_entries(object): def __init__(self, dbname, user, passwd, accounts_file, file_type): """método incial""" try: self.url_template = "http://%s:%s/xml...
rr: raise Exception(u'Conexion rechazada: %s!' % err) except xmlrpclib.Fault, err: raise Exception(u'Error %s en write: %s' % (err.faultCode, err.faultString)) def unlink(self, model, ids, context={}): """ Wrapp...
self.user_passwd, model, 'unlink', ids, context) return res except socket.error, err: raise Exception(u'Conexion rechazada: %s!' % err) except xmlrpclib.Fault, err: raise Exception(u'Error %s en ...
dmdm/PySite
pysite/vmailmgr/views/alias.py
Python
agpl-3.0
7,411
0.001079
# -*- coding: utf-8 -*- import copy import colander import sqlalchemy as sa from pyramid.view import view_config, view_defaults import markupsafe import datetime from sqlalchemy.exc import StatementError from sqlalchemy.orm.exc import NoResultFound import pysite.vmailmgr from pysite.vmailmgr.models import AliasDd, Al...
) )) self.DD['domain_name'] = copy.deepcopy(
DomainDd['name']) self.DD['domain_name']['colModel']['editable'] = False self.DD['domain_name']['title'] = 'Domain' # If the fieldnames are fully qualified, this is the prefix, e.g. # ``myschema.mytable.``. Mind the trailing dot! self.PREFIX = '' self.PREFIXLEN = len(sel...
samedder/azure-cli
src/command_modules/azure-cli-monitor/azure/cli/command_modules/monitor/_exception_handler.py
Python
mit
800
0.0025
# ----------------------------------------------------------------------------------------
---- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from azure.cli.
core.util import CLIError def monitor_exception_handler(ex): from azure.mgmt.monitor.models import ErrorResponseException if hasattr(ex, 'inner_exception') and 'MonitoringService' in ex.inner_exception.message: raise CLIError(ex.inner_exception.code) elif isinstance(ex, ErrorResponseException): ...
swift-nav/libsbp
python/sbp/client/drivers/pyserial_driver.py
Python
lgpl-3.0
2,580
0.011628
# Copyright (C) 2015 Swift Navigation Inc. # Contact: Mark Fine <mark@swiftnav.com> # # This source is subject to the license found in the file 'LICENSE' which must # be be distributed together with this source. All other rights reserved. # # THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, #...
print "Piksi disconnected" print raise IOErro
r def write(self, s): """ Write wrapper. Parameters ---------- s : bytes Bytes to write """ try: return self.handle.write(s) except (OSError, serial.SerialException): print print "Piksi disconnected" print raise IOError
munhyunsu/WorkLogger
src/basescanner/base_scanner.py
Python
gpl-3.0
6,046
0.00573
#!/usr/bin/python3 import configparser # ConfigParser import socket # socket import os # path.exists import sys # exit import struct # unstruct import logging # log class BaseScanner(object): """MAC 주소를 스캔하는 클래스 """ # 스니핑 소켓 생성 # @arg: socket - interface 가 있는 config def _create_socket(self): ...
sys.exit(0) if not 'file' in self.config['log']: logging.critical('설정 파일 log
세션에 ' + 'file 항목이 필요합니다.') sys.exit(0) # 로그 레벨, 파일 이름 불러오기 log_level = getattr(logging, self.config['log']['level']) log_file = self.config['log']['file'] # 로그 레벨 세팅 logging.basicConfig(filename = log_file, leve...
vladikoff/fxa-mochitest
tests/mozbase/mozhttpd/tests/basic.py
Python
mpl-2.0
1,260
0.000794
#!/usr/bin/env python import mozhttpd import mozfile import os import tempfile impor
t unittest class TestBasic(unittest.TestCase): """ Test basic Mozhttpd capabilites """ def test_basic(self): """ Test mozhttpd can serve files """ tempdir = tempfile.mkdtemp() # sizes is a dict of the form: n
ame -> [size, binary_string, filepath] sizes = {'small': [128], 'large': [16384]} for k in sizes.keys(): # Generate random binary string sizes[k].append(os.urandom(sizes[k][0])) # Add path of file with binary string to list fpath = os.path.join(tempdir, ...
baptistemanteau/colorharmonies
colorharmonies/tests/test_colorharmonies.py
Python
mit
6,249
0.068651
# -*- coding: utf-8 -*- import unittest from ..colorharmonies import Color, complementaryColor, triadicColor, splitComplementaryColor, tetradicColor, analogousColor, monochromaticColor class colorsHarmonies(unittest.TestCase): # Obtain the complementary color of a color def test_complementaryColor(self): MagentaCo...
nColor)),sorted([[230,66,176],[66,176,230]])) self.assertEqual(sorted(triadicColor(WhiteColor)),sorted([[255,255,255],[255,255,255]])) # Obtain the split complementary colors of a color def test_splitComplementaryColor(self): MagentaC
olor = Color([255,0,255],"","") YellowColor = Color([255,255,0],"","") CyanColor = Color([0,255,255],"","") PurpleColor = Color([222,170,255],"","") GreenColor = Color([176,230,66],"","") WhiteColor = Color([255,255,255],"","") self.assertEqual(sorted(splitComplementaryColor(MagentaColor)),sorted([[0,255,12...
Caoimhinmg/PmagPy
data_files/LearningPython/matplotlib8.py
Python
bsd-3-clause
649
0.035439
#!/usr/bin/env python from __future__ import division from __future__ import print_function from builtins import input from past.utils import old_div import numpy import matplotlib matplotlib.use("TkAgg") import pylab G=6.67e-11 # grav constant in Nm^2/kg^2 (SI) R=2. # radius in meters z=3. # depth of burial drho=500 #...
),(3.*(h**2+z**2))) print(g.ndim) input() pylab.i
mshow(g,interpolation='bilinear',cmap=pylab.cm.Spectral) pylab.colorbar() pylab.axis('equal') pylab.show()
peterjwilliamson/PIC-12F1840-TOOLS
001-Bootloader/Python-PC-Part/wxSerialConfigDialog.py
Python
bsd-3-clause
11,843
0.005826
#!/usr/bin/env python # generated by wxGlade 0.3.1 on Thu Oct 02 23:25:44 2003 #from wxPython.wx import * import wx import serial import serial.tools.list_ports SHOW_BAUDRATE = 1<<0 SHOW_FORMAT = 1<<1 SHOW_FLOW = 1<<2 SHOW_TIMEOUT = 1<<3 SHOW_ALL = SHOW_BAUDRATE|SHOW_FORMAT|SHOW_FLOW|SHOW_TIMEOUT try:...
: self.checkbox_timeout.SetValue(True) self.text_ctrl_timeout.Enable(True) self.text_ctrl_timeout.SetValue(str(self.serial.timeout)) if self.show & SHOW_FLOW: #set the rtscts mode self.checkbox_rtscts.SetValue(self.serial.rtscts) ...
the event handlers self.__attach_events() def __set_properties(self): # begin wxGlade: SerialConfigDialog.__set_properties # end wxGlade self.SetTitle("Serial Port Configuration") if self.show & SHOW_TIMEOUT: self.text_ctrl_timeout.Enable(0) self.button_o...
virtuald/exaile
plugins/currentsong/__init__.py
Python
gpl-2.0
4,483
0.00491
# -*- 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 2, or (at your option) # any later version. # # This program is distributed in the hope that it will be us...
le.PurpleStatusSetAttrString(status, attr, value) return True return False def setTune(self, artist, title, album) : """ Change the tune status Return True if the message is successfully updated """ current = self.purple.PurpleSavedstatusGetCurren...
unts = self.purple.PurpleAccountsGetAll() for account in accounts: if self.purple.PurpleAccountIsConnected(account) != True: continue p = self.purple.PurpleAccountGetPresence(account) status = self.purple.PurplePresenceGetStatus(p, "tune") if sta...
rekbun/project-euler
src/python/problem25.py
Python
apache-2.0
98
0.112245
prev=1 cnt=2 nex
t=1 while(len(str(next)
)<1000): prev,next=next,next+prev cnt+=1 print(cnt)
DPRL/MathSymbolRecognizer
src/test_classifier.py
Python
gpl-3.0
2,679
0.003359
""" DPRL Math Symbol Recognizers Copyright (c) 2012-2014 Kenny Davila, Richard Zanibbi This file is part of DPRL Math Symbol Recognizers. DPRL Math Symbol Recognizers is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by th...
_classes = len(classes_l) # create test characters from points sample_x = [[(-0.8, -0.8), (0.1, 0.12), (0.8, 0.79)], [(-0.85, 0.79), (0.01, 0.005), (0.79, -0.83)]] sample_1 = [[(0.15, 0.7), (0.2, 1.0), (0.21, -1.2)], [(0.05, -1.19), (0.3, -1.25)]] sample_eq = [[(-1.5, -0.4), (1.5, -0.4)], [(-1.5, 0.4),...
fier.classify_points(sample_1) class_eq = classifier.classify_points(sample_eq) print("X classified as " + class_x) print("1 classified as " + class_1) print("= classified as " + class_eq) # now with confidence ... classes_x = classifier.classify_points_prob(sample_x, 3) classes_1 = classi...
P0cL4bs/3vilTwinAttacker
plugins/extension/dump_post_data.py
Python
gpl-3.0
4,003
0.006995
from plugins.extension.plugin import PluginTemplate from mitmproxy.models import decoded from PyQt4.QtCore import QObject,pyqtSignal import re """ Description: This program is a core for wifi-pumpkin.py. file which includes functionality plugins for Pumpkin-Proxy. Copyright: Copyright (C) 2015-2016 Marcos...
est): user_passwd = self.get_password_POST(flow.request.content)
if user_passwd != None: try: http_user = user_passwd[0].decode('utf8') http_pass = user_passwd[1].decode('utf8') # Set a limit on how long they can be prevent false+ if len(http_user) > 75 or len(http_pass) > 75: ...
candlepin/subscription-manager
src/rhsmlib/dbus/facts/base.py
Python
gpl-2.0
2,557
0.000782
# Copyright (c) 2016 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a copy of G...
.collect() cleaned = dict([(str(key), str(value)) for key, value in list(collection.data.items())]) return dbus.Dictionary(cleaned, signature="ss") def class_factory(name, facts_collector=None): """Function used for creating subclasses of class BaseFact""" def __init__(self, conn=None, object_...
object_path=object_path, bus_name=bus_name) self.facts_collector = facts_collector return type(name, (BaseFacts,), {"__init__": __init__}) AllFacts = class_factory('AllFacts', all.AllFactsCollector()) HostFacts = class_factory('Host...
jeffFranklin/uw-restclients
setup.py
Python
apache-2.0
856
0.010514
#!/usr/bin/env python # Taken from django's setup.py: import os from distutils.core import setup import setuptools setup(name='UW-RestClients', version='1.0.4', license = "Apache 2.0", author = "UW-IT ACA", author_email = "pmichaud@u
w.edu", packages=setuptools.find_packages(exclude=["project"]), include_package_data=True, # use MANIFEST.in during install url='https://github.com/uw-it-aca/uw-restclients', description='Clients for a variety of RESTful web services at the University of Washington', install_requires=['Dj...
'ordereddict>=1.1', 'python-dateutil>=2.1', 'unittest2>=0.5.1', 'pytz', 'icalendar', 'AuthZ-Group>=1.1.4', 'Django-UserService'], )
wcong/ridicule
src/register.py
Python
apache-2.0
1,198
0.001669
# encoding=utf8 __author__ = 'wcong' import datetime import web import config import util import pdbc urls = ( '/', 'Index' ) class Index: def GET(self):
input = web.input() email = util.decode_string(input.get("email")) sign = int(util.decode_string(input.get("sign")).replace(email, '')) now_time = util.make_time_stamp() web.setcookie("email", util.encode_string(email))
if (now_time - sign) > config.log_time_interval or not pdbc.User.is_check_sign_same(email, input.get("sign")): web.seeother("../invite/") return data = dict() data['email'] = email return config.render.register(data) def POST(self): email = util.get_user_emai...
DrOctogon/unwash_ecom
oscar/test/testcases.py
Python
bsd-3-clause
3,464
0
from six.moves import http_client from django.core.urlresolvers import reverse from django.contrib.auth.models impo
rt Permission from django_webtest import WebTest from purl import URL from oscar.core.compat import get_user_model User = get_user_model() def add_permissions(user, permissi
ons): """ Grant permissions to the passed user :param permissions: e.g. ['partner.dashboard_access'] """ for permission in permissions: app_label, __, codename = permission.partition('.') perm = Permission.objects.get(content_type__app_label=app_label, ...
itsjeyd/edx-platform
common/test/acceptance/tests/studio/test_studio_help.py
Python
agpl-3.0
48,758
0.002153
""" Test the Studio help links. """ from flaky import flaky from bok_choy.web_app_test import WebAppTest from unittest import skip from common.test.acceptance.fixtures.course import XBlockFixtureDesc from common.test.acceptance.tests.studio.base_studio_test import StudioCourseTest, ContainerBase from common.test.acce...
f.index_page.click_sign_up() # The href we want to see in anchor help element. href = 'http://edx.readthedocs.io/projects/open-edx-building-and-running-a-course/' \ 'en/latest/getting_started/get_started.html' # Assert that help link is correct. assert_nav_help_link( ...
s help links on 'Home'(Courses tab) page. """ def setUp(self): # pylint: disable=arguments-differ super(HomeHelpTest, self).setUp() self.home_page = HomePage(self.browser) self.home_page.visit() def test_course_home_nav_help(self): """ Scenario: Help link in navigat...
vicente-gonzalez-ruiz/QSVC
trunk/src/old_py/texture_expand_lfb_j2k.py
Python
gpl-2.0
4,853
0.00886
#!/usr/bin/python # -*- coding: iso-8859-15 -*- import sys import math from subprocess import check_call from subprocess import CalledProcessError from MCTF_parser import MCTF_parser file = "" rate = 0.0 pictures = 33 pixels_in_x = 352 pixels_in_y = 288 subband = 4 # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ...
d" + " -i " + file + "_U_" + str('%04d' % image_number) + ".j2c" + " -o " + file + "_U_" + str('%04d' % image_number) + ".raw" , shell=True) else : check_call("trace kdu_exp
and" + " -i " + file + "_U_" + str('%04d' % image_number) + ".j2c" + " -o " + file + "_U_" + str('%04d' % image_number) + ".raw" + " -rate " + rate , shell=True) except CalledProcessError: sy...
skirpichev/omg
diofant/vector/basisdependent.py
Python
bsd-3-clause
9,621
0.000104
from ..core import Add, Expr, Integer, Mul, count_ops, diff from ..core.assumptions import StdFactKB from ..core.decorators import _sympifyit, call_highest_priority from ..integrals import Integral from ..polys import factor from ..simplify import simplify, trigsimp class BasisDependent(Expr): """ Super class...
tity. See Also ======== diofant.simplify.trigsimp.trigsimp """ trig_components = [trigsimp(v, **opts) * k for k, v in self.components.items()] return self._add_func(*trig_components) def _eval_simplify(self, ratio, measure): retu...
return self.diff(wrt) def _eval_Integral(self, *symbols, **assumptions): integral_components = [Integral(v, *symbols, **assumptions) * k for k, v in self.components.items()] return self._add_func(*integral_components) def factor(self, *args, **kwargs): ...
qskycolor/viewfinder
backend/db/test/accounting_test.py
Python
apache-2.0
2,951
0.01491
# Copyright 2012 Viewfinder Inc. All Rights Reserved. """Tests for Accounting data object. """ __author__ = 'marc@emailscrubbed.com (Marc Berhault)' import logging import time import unittest from viewfinder.backend.base.testing import async_test from viewfinder.backend.db.accounting import Accounting from viewfind...
b.operation import Operation from viewfinder.backend
.op.op_context import EnterOpContext from base_test import DBBaseTestCase class AccountingTestCase(DBBaseTestCase): def testOperationReplay(self): """Verify that multiple applies for the same operation ID only increment the stats once.""" act = Accounting.CreateViewpointOwnedBy('vp1', 1) act.num_photos...
DayGitH/Python-Challenges
DailyProgrammer/DP20151218C.py
Python
mit
8,638
0.012503
""" [2015-12-18] Challenge #245 [Hard] Guess Who(is)? https://www.reddit.com/r/dailyprogrammer/comments/3xdmtw/20151218_challenge_245_hard_guess_whois/ Guess Who(is)? ============== You are working as the only software engineer at a small but successful startup. One day, though, there is a problem. You got this e-mai...
dia.org/wiki/Classless_Inter-Domain_Routing#CIDR_blocks). * The ranges may (and probably do) overlap. Possibly more th
an two layers deep. * There may be multiple ranges associated with the same name. *If you are unfamiliar with how IPs addresses work, see the section at the bottom of the post.* Sample Input Lookups -------------------- 250.1.3.4 123.50.1.20 189.133.73.57 123.50.1.21 250.1.2.4 123.50.1.21 250.1.3.100 250.1.3....
popazerty/openblackhole-SH4
lib/python/Screens/ChoiceBox.py
Python
gpl-2.0
6,533
0.032757
from Screens.Screen import Screen from Components.ActionMap import NumberActionMap from Components.Label import Label from Components.ChoiceList import ChoiceEntryComponent, ChoiceList from Components.Sources.StaticText impor
t StaticText import enigma class ChoiceBox(Screen): def __init__(self, session, title="", list=None, keys=None, selection=0, skin_
name=None, text=""): if not list: list = [] if not skin_name: skin_name = [] Screen.__init__(self, session) if isinstance(skin_name, str): skin_name = [skin_name] self.skinName = skin_name + ["ChoiceBox"] self["text"] = Label() if title: title = _(title) if len(title) < 55 and title.find('\n') =...
skwash/pgshapely
pgshapely/tests/test_points.py
Python
bsd-3-clause
1,826
0.013143
import unittest import pgshapely from shapely.geometry import Point class TestPoints(unittest.TestCase): database = "test" user = "test" password = "test" def setUp(self): conn = pgshapely.connect(database=self.database, user=self.user, password=self.password) cursor = co...
Point(-122.2482834, 47.4377447) } cursor = self.conn.cursor() sql = "INSERT INTO test VALUES(ST_MakePoint(%(x)s, %(y)s));" cursor.execute(sql, params) sql = "INSERT INTO t
est VALUES(GeomFromText(%(wkt)s));" cursor.execute(sql, params) sql = "INSERT INTO test VALUES(GeomFromEWKT(%(ewkt)s));" cursor.execute(sql, params) sql = "SELECT geometry FROM test" cursor.execute(sql) for row in cursor.fetchall(): point = row[0] ...
Hypernode/xtraceback
xtraceback/reference.py
Python
mit
1,552
0.000644
import sys import pprint class Reference(object): def __init__(self, tb_index, varname, target): self.tb_index = tb_index self.varname = varname self.target = target def marker(self, xtb, tb_index, key): return Marker(self, xtb, tb_index, key) class Marker(object): def...
if frame.f_code == code: indent = frame.f_locals["indent"] + 4 break frame = frame.f_back else: # pragma: no cover - defensive raise RuntimeError("Expecting to be called with "
"XTraceback._format_variable in stack") pretty_repr = pprint.pformat(self.reference.target) if indent + len(self.key) + len(pretty_repr) > self.xtb.print_width \ or pretty_repr.find("\n") > 0: name = "" if self.reference.varname == self.key \ ...
yuxiang-zhou/menpofit
menpofit/aam/base.py
Python
bsd-3-clause
66,618
0.00048
from __future__ import division import warnings import numpy as np from menpo.feature import no_op from menpo.visualize import print_dynamic from menpo.model import PCAModel from menpo.transform import Scale from menpo.shape import mean_pointcloud from menpo.base import name_of_callable from menpofit import checks fr...
ce_shape, densify_shapes, extract_patches, MenpoFitBuilderWarning, compute_reference_shape) class AAM(object): r""" Class for training a multi-scale holistic Active Appearance Model. Please see the references for a basic list of relevant papers. Parameters ---------- image
s : `list` of `menpo.image.Image` The `list` of training images. group : `str` or ``None``, optional The landmark group that will be used to train the AAM. If ``None`` and the images only have a single landmark group, then that is the one that will be used. Note that all the training...
iAddz/allianceauth
services/modules/ips4/admin.py
Python
gpl-2.0
300
0.006667
from __future__ impo
rt unicode_literals from django.contrib import admin from .models import Ips4User class Ips4UserAdmin(admin.ModelAdmin): list_display = ('user', 'us
ername', 'id') search_fields = ('user__username', 'username', 'id') admin.site.register(Ips4User, Ips4UserAdmin)
Loenberg123/ansible-icinga2-client
scripts/check_nginx.py
Python
gpl-3.0
3,388
0.025679
# -*- coding: utf-8 -*- #!/usr/bin/python # check_nginx is a Nagios to monitor nginx status # my blog: http://www.nginxs.com # The version is 1.0.1 # MSN: yangzi2008@126.com import string import urllib2 import getopt import sys def usage(): print """check_nginx is a Nagios to monitor nginx status Usage: che...
%s,reading:%s,writing:%s,waiting:%s' % (ActiveConn,reading,writing,waiting) perfdata = 'ActiveConn:%
s,reading:%s,writing:%s,waiting:%s' % (ActiveConn,reading,writing,waiting) except Exception: print "NGINX STATUS unknown: Error while getting Connection" sys.exit(3) if 'warning' in dir() and 'critical' in dir(): if ActiveConn >= warning: print 'WARNING - %s|%s' % (output,perfdata) sys.exit(2) ...
mlibrary/image-conversion-and-validation
falcom/api/uri/__init__.py
Python
bsd-3-clause
236
0
# Cop
yright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. from .api_querier import APIQuerie
r from .uri import URI
calebtrahan/KujiIn_Python
backup/guitemplates/helpmaindialog.py
Python
mit
4,238
0.005191
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'helpmaindialog.ui' # # Created by: PyQt4 UI code generator 4.11.1 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf...
topLabel")) self.verticalLayoutWidget = QtGui.QWidget(Dialog) self.verticalLayoutWidget.setGeometry(QtCore.QRect(39, 29, 271, 331)) self.verticalLayoutWidget.setObjectName(_fromUtf8("verticalLayoutWidget")) self.helpbuttonsLayout = QtGui.QVBoxLayout(self.verticalLayoutWidget) sel...
icalLayoutWidget) self.helpcreatingsessionsButton.setObjectName(_fromUtf8("helpcreatingsessionsButton")) self.helpbuttonsLayout.addWidget(self.helpcreatingsessionsButton) self.helpaddingambienceButton = QtGui.QPushButton(self.verticalLayoutWidget) self.helpaddingambienceButton.setObjectN...
ooici/marine-integrations
mi/instrument/mclane/driver.py
Python
bsd-2-clause
50,088
0.002895
""" @package mi.instrument.mclane.driver @file marine-integrations/mi/instrument/mclane/driver.py @author Dan Mergens @brief Driver base class for McLane instruments Release notes: initial version """ import datetime __author__ = 'Dan Mergens' __license__ = 'Apache 2.0' import re import time from mi.core.log import...
rotocolEvent.CLOCK_SYNC ACQUIRE_SAMPLE = ProtocolEvent.ACQUIRE_SAMPLE # ACQUIRE_STATUS = ProtocolEvent.ACQUIRE_STATUS CLEAR = ProtocolEvent.CLEAR class Parameter(DriverParameter): """ Device specific parameters. """
FLUSH_VOLUME = "flush_volume" FLUSH_FLOWRATE = "flush_flowrate" FLUSH_MINFLOW = "flush_minflow" FILL_VOLUME = "fill_volume" FILL_FLOWRATE = "fill_flowrate" FILL_MINFLOW = "fill_minflow" CLEAR_VOLUME = "clear_volume" CLEAR_FLOWRATE = "clear_flowrate" CLEAR_MINFLOW = "clear_minflow" c...