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
samuto/Honeybee
src/Honeybee_Set EnergyPlus Zone Schedules.py
Python
gpl-3.0
11,139
0.013107
# # Honeybee: A Plugin for Environmental Analysis (GPL) started by Mostapha Sadeghipour Roudsari # # This file is part of Honeybee. # # Copyright (c) 2013-2015, Mostapha Sadeghipour Roudsari <Sadeghipour@gmail.com> # Honeybee is free software; you can redistribute it and/or modify # it under the terms of the GNU Ge...
the HVAC availability that you want t
o use. This can be either a shcedule from the schedule libirary or a CSV file path to a CSV schedule you created with the "Honeybee_Create CSV Schedule" component. Returns: schedules: A report of what shcedules are assigned to each zone. HBZones: HBZones that have had thier shcedules modified. """ ...
evansde77/cirrus
src/cirrus/builder_plugin.py
Python
apache-2.0
4,230
0.001418
#!/usr/bin/env python """ builder plugin Define the plugin base API for builders for managing virtualenvs of various flavours """ import os import re import argparse import subprocess from collections import namedtuple from cirrus.configuration import load_configuration from cirrus.environment import repo_directory...
python runtime environment at the location provided """ pass def clean(self, **kwargs): """ _clean_ remove the specified runtime environment """ pass def activate(self): """ return a shell command string to activate the ...
LOGGER.info("Running setup.py develop...") activate = self.activate() local( '{} && python setup.py develop'.format( activate ) ) def venv_python_version(self): """ get the python version from the virtualenv/conda env/pipenv wh...
NoelDeMartin/Japanese-Character-Recognition
data/prepare.py
Python
mit
3,120
0.023871
# coding=utf-8 import zipfile import struct import random import os import numpy as np from PIL import Image, ImageEnhance # If this is set to True, only アイウエオカキク characters will be extracted, # which make for a faster training time with better accuracy at the cost # of
learning less characters. REDUCED_TRAINING_SET = True def main(): extract_zip() unpack_katakana() # Method definitions def relative_path(path): return os.path.dirname(os.path.realpath(__file__)) + '/' + path def extract_zip(): output_dir = relative_path('raw/ETL1') if not os.path.exists(output_dir): print 'E...
ETL1.zip...' with zipfile.ZipFile(relative_path('raw/ETL1.zip'), 'r') as file: file.extractall(relative_path('raw')) print 'raw/ETL1.zip extracted!' def unpack_katakana(): output_dir = relative_path('katakana') if not os.path.exists(output_dir): print 'Unpacking katakana...' os.makedirs(output_dir) i...
citationfinder/scholarly_citation_finder
scholarly_citation_finder/apps/citation/evaluation/tasks.py
Python
mit
5,022
0.005177
from __future__ import absolute_import from celery import shared_task import os.path import logging import csv from django.core.exceptions import ObjectDoesNotExist from .RandomAuthorSet import RandomAuthorSet from ..CitationFinder import CitationFinder, EmptyPublicationSetException from scholarly_citation_finder impo...
_dir = os.path.join(config.EVALUATION_DIR, name) with open(os.path.join(evaluation_dir, AUTHOR_SET_FILENAME)) as author_set_file: reader = csv.DictReader(author_set_file) for row in reader: if len(row) == 3:
try: strategies_result = evaluation_citations(author_id=row['author_id'], evaluation_name=name, strategies=strategies) for strategy_result in strategies_result: __store_evaluation_result(path=evaluation_dir, ...
watty62/jazz_birthdays
old versions/extraction4.py
Python
cc0-1.0
7,375
0.03322
# -*- coding:utf-8 -*- import xml.etree.ElementTree as etree import re import datetime #set the output file name for the 'good' data #needs to be to a structured format - but dump to text for now #clean_output = 'clean_out.csv' clean_output = 'clean.txt' #set the dirty output file where we'll dump the awkward lines...
an_output, 'w') #open the clean output file f3 = open(dirty_output, 'w') #probably a better way of doing this - but set up a list of valide months to compare against (maybe move nearer to this code?) month_list = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August','September', 'October', 'Novemb...
", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december") #initialise integer values for month and day birth_day = 0 birth_month = 0 # First function: cleans out (invisible) ascii chars 132 and 160 from some lines which was causing problems def remove_non_ascii_1(text): ...
JBed/Simple_Theano
4_simple_conv_net/better_conv_net.py
Python
apache-2.0
2,609
0.004216
import theano import theano.tensor as T import numpy as np import sys sys.path.insert(0, '../data_loader/') import load from theano.tensor.nnet.conv import conv2d from theano.tensor.signal.downsample import max_pool_2d # load data x_train, t_train, x_test, t_test = load.cifar10(dtype=theano.config.floatX, grayscale=F...
=updates) predict = theano.function([x], y) # train model batch_size = 50 for i in range(50): print "iteration {}".format(i + 1) for start in range(0, len(x_train), batch_size): x_batch = x_train[start:start + batch_size] t_batch = t_trai
n[start:start + batch_size] cost = train(x_batch, t_batch) predictions_test = predict(x_test) accuracy = np.mean(predictions_test == labels_test) print "accuracy: {}\n".format(accuracy)
andrewsmedina/horizon
horizon/horizon/dashboards/nova/instances_and_volumes/panel.py
Python
apache-2.0
870
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 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 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 permiss...
slug = 'instances_and_volumes' dashboard.Nova.register(InstancesAndVolumes)
stoeps13/ibmcnx2
ibmcnx/menu/docs.py
Python
apache-2.0
3,638
0.002199
''' Menu for Community Scripts Author: Christoph Stoettner Mail: christoph.stoettner@stoeps.de Documentation: http://scripting101.stoeps.de Version: 5.0.1 Date: 09/19/2015 License: Apache 2.0 History: Changed by Jan Alderlieste ''' import sys import os import ibmcnx.funct...
ls() def docDocumentation(): print '###########################################################' print '# #' print '# Not implemented in the menu! #' print '# #' ...
print '# #' print '###########################################################' # execfile( 'ibmcnx/doc/Documentation.py', globdict ) global globdict globdict = globals() doc = ibmcnx.menu.MenuClass.cnxMenu() doc.AddItem('Show JVM Heap Sizes (ibmcnx/doc/...
KrzysztofStachanczyk/Sensors-WWW-website
www/env/lib/python2.7/site-packages/django/conf/locale/de_CH/formats.py
Python
gpl-3.0
1,445
0.000692
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date from __future__ import unicode_literals DATE_FORMAT = 'j. F Y' TIME_FORMAT = 'H:i' DATE...
%d. %b. %Y', # '25. October 2006', '25. Oct. 2006' ] DATETIME_INPUT_FORMATS = [ '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' ] # these are the separators for n...
details, please refer to http://www.bk.admin.ch/dokumentation/sprachen/04915/05016/index.html?lang=de # (in German) and the documentation DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3
OBIGOGIT/etch
binding-python/runtime/src/main/python/etch/compiler/__init__.py
Python
apache-2.0
1,061
0.001885
""" # 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...
ou 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 * # * # Unl...
buted 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. """ from __future__ import absolute_import
inquisite/Inquisite-Core
api/__init__.py
Python
gpl-3.0
2,483
0.003222
import os import json import collections import datetime from flask import Flask, request, current_app, make_response, session, escape, Response, jsonify from flask_jwt_extended import JWTManager, jwt_required, create_access_token, get_jwt_identity from flask_socketio import SocketIO from neo4j.v1 import GraphDatabase,...
import eventlet #eventlet.monkey_patch() # if sys.version_info < (3, 0):
# sys.stdout.write("Sorry, requires Python 3.x, not Python 2.x\n") # sys.exit(1) config = json.load(open('./config.json')); # Init UPLOAD_FOLDER = os.path.dirname(os.path.realpath(__file__)) + "/uploads" x_socketio = SocketIO() def create_app(): app = Flask(__name__) app.debug = True app.config...
lambacck/simpleblog
simpleblog/blog/views.py
Python
mit
4,533
0.001765
import json import datetime from django import forms, http from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.views import redirect_to_login from django.conf import settings from django.contrib import messages from django.core.exceptions import PermissionDenied from django.template import Con...
class PostUpdateView(LoginRequiredMixin, StaffRequiredMixin, PostActionMixin, UpdateView): form = PostForm model = Post action = 'updated' class PostDetailView(DetailView): model
= Post def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) form = context['form'] = CommentForm(initial={'post': context['post'].id}) form.fields['post'].widget = forms.HiddenInput() post = context['post'] comments = post.c...
Axford/AFRo
hardware/ci/build.py
Python
mit
1,275
0.010196
#!/usr/bin/env python # Run the various build scripts import sys import os from parse import parse_machines from machines import machines from assemblies import assemblies from vitamins import vitamins from printed import printed from guides import guides from publish import publish def build(do_publish=0): prin...
): os.rename(outfile, oldfile) errorlevel = 0 errorlevel += parse_machines() if errorlevel == 0: errorlevel += vitamins() if errorlevel == 0: errorlevel
+= printed() if errorlevel == 0: errorlevel += assemblies() if errorlevel == 0: errorlevel += machines() if errorlevel == 0: errorlevel += guides() if errorlevel == 0 and do_publish > 0: publish() # if everything is ok then delete backup - no long...
ngtrhieu/outline_alignment
outline_alignment_params.py
Python
mit
701
0.001427
class OutlineAlignmentParams (object): # FILE_IN_1 = 'img/render.png' # SIZE_IN_1 = (40, 0, 1026
, 632) # BACKGROUND_REMOVAL_1 = None # FILE_IN_2 = 'img/texture.png' # SIZE_IN_2 = (40, 0, 1
026, 632) # BACKGROUND_REMOVAL_2 = None # FILE_IN_1 = 'img2/render-2.png' # SIZE_IN_1 = None # BACKGROUND_REMOVAL_1 = None # FILE_IN_2 = 'img2/texture-2.png' # SIZE_IN_2 = None # BACKGROUND_REMOVAL_2 = "red_background" FILE_IN_1 = 'img3/MeshPurple.png' SIZE_IN_1 = None BACKGROU...
pymango/pymango
misc/python/mango/fmmTest/__init__.py
Python
bsd-2-clause
316
0.012658
import
mango from ._PValueTest import * from ._GeneralisedChiSquaredTe
st import * __all__ = [s for s in dir() if not s.startswith('_')] if mango.haveRestricted: from ._fmmTest import * from ._BinnedGmmEmTest import * from ._SummedBinnedGmmEmTest import *
kyasabu/Telethon
try_telethon.py
Python
mit
1,492
0
#!/usr/bin/env python3 import traceback from telethon_examples.interactive_telegram_client \ import InteractiveTelegramClient def load_settings(path='api/settings'): """Loads the user settings located under `api/`""" result = {} with open(path, 'r', encoding='utf-8') as file: for line in file...
ysocks host, port = settings['socks_proxy'].split(':') kwargs = dict(proxy=(socks.SOCKS5, host, int(port))) client = InteractiveTelegramClient( s
ession_user_id=str(settings.get('session_name', 'anonymous')), user_phone=str(settings['user_phone']), api_id=settings['api_id'], api_hash=str(settings['api_hash']), **kwargs) print('Initialization done!') try: client.run() except Exception as e: print('Une...
palisadoes/switchmap-ng
switchmap/snmp/mib_bridge.py
Python
apache-2.0
13,577
0
#!/usr/bin/env python3 """Class interacts with devices supporting BRIDGE-MIB.""" from collections import defaultdict from switchmap.snmp.base_query import Query from switchmap.snmp import mib_if from switchmap.utils import general def get_query(): """Return this module's Query class.""" return BridgeQuery ...
mbda: defaultdict(dict)) done = False # Check if Cisco VLANS are supported oid_vtpvlanstate = '.1.3.6.1.4.1.9.9.46.1.3.1.1.2' oid_exists = self._snmp_object.oid_exists(oid_vtpvlanstate) if bool(oid_exists) is True: final = self
._macaddresstable_cisco() done = True # Check if Juniper VLANS are supported if done is False: oid_dot1qvlanstaticname = '.1.3.6.1.2.1.17.7.1.4.3.1.1' oid_exists = self._snmp_object.oid_exists( oid_dot1qvlanstaticname) if bool(oid_exists) ...
radome/algorithms_and_data_structures
Python/test/test_dfs.py
Python
apache-2.0
911
0
"""Tests for the DFS module""" import unittest from dfs import dfsTraverse class test_dfsTraverse(unittest.TestCase): """Test the correct order in traversing a graph""" def setUp(self): """Create a graph and a tuple with the correct traverse""" self.correctResTup = ('a', 'b', 'e', 'g', 'f', '...
b': ('e', 'a', 'f'), 'd': ('a', 'f'), 'e': ('b', 'g'), 'g': ('e', 'a'), 'f': ('b', 'd', 'c'),
'c': ('f', 'h'), 'h': ('c')} def test_traverse(self): """Test the traverse function""" result = dfsTraverse(self.graphDict, 'a') self.assertEqual(result, self.correctResTup) if __name__ == '__main__': unittest.main()
txtbits/daw-python
primeros ejercicios/Ejercicios de acumular números/ejercicio3.py
Python
mit
584
0.012153
from easygui import * ''' Escribe un programa que pida un número (el número de notas que vamos a introducir). Después pedirá las notas y calculará la media. ''' # Etiqueta media inicializada a 0 total = 0 numnotas = int(enterbox('Introduce el número de notas: ')) # for ...range para recorrer el numero de notas for nu...
ltado media = total / float(numnotas) msgbox('El resultado es %.2f' %media)
amsehili/auditok
tests/test_signal.py
Python
mit
6,986
0
import unittest from unittest import TestCase from array import array as array_ from genty import genty, genty_dataset import numpy as np from auditok import signal as signal_ from auditok import signal_numpy @genty class TestSignal(TestCase): def setUp(self): self.data = b"012345679ABC" self.nump...
ate_energy_single_channel(x, sample_width) self.assertEqual(energy, expected) energy = signal_numpy.calculate_energy_single_channel(x, sample_width) self.assertEqual(energy, expected) @genty_dataset( min_=( [[300, 320, 400, 600], [150, 160, 200, 300]], 2, ...
max, 52.50624901923348, ), ) def test_calculate_energy_multichannel( self, x, sample_width, aggregation_fn, expected ): x = [array_(signal_.FORMAT[sample_width], xi) for xi in x] energy = signal_.calculate_energy_multichannel( x, sample_width, aggrega...
tensorflow/examples
tensorflow_examples/models/densenet/densenet_distributed_test.py
Python
apache-2.0
2,998
0.002668
# Copyright 2017 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...
. Default range is SOTA. top_1_max: Max value for top_1 accuracy. **kwargs: All args passed to the test. """ start_time_sec = time.time() train_loss, train_acc, _, test_acc = distributed_train.main(**kwargs) wall_time_sec = time.time() - start_time_sec metrics = [] metrics.append({...
ning_accuracy_top_1', 'value': train_acc}) metrics.append({'name': 'train_loss', 'value': train_loss}) self.report_benchmark(wall_time=wall_time_sec, metrics=metrics) if __name__ == '__main__': tf.test.main()
terceiro/squad
squad/ci/tasks.py
Python
agpl-3.0
2,771
0.000361
from squad.celery import app as celery from squad.ci.models import Backend, TestJob from squad.ci.exceptions import SubmissionIssue, FetchIssue from celery.utils.log import get_task_logger from squad.mail import Message from django.conf import settings from django.template.loader import render_to_string logger = get_...
Job.objects.get(pk=job_id) if test_job.fetch_attempts >= test_job.backend.max_fetch_attempts: return logger.info("fetching %s" % test_job) try: test_job.backend.fetch(test_job) except FetchIssue as issue: logger.warn("error fetching job %s: %s" % (test_job.id, str(issue))) ...
= str(issue) test_job.fetched = not issue.retry test_job.fetch_attempts += 1 test_job.save() @celery.task(bind=True) def submit(self, job_id): test_job = TestJob.objects.get(pk=job_id) try: test_job.backend.submit(test_job) test_job.save() except SubmissionIssue as...
tntC4stl3/Learn-Flask
tutorial/learn_upload.py
Python
gpl-2.0
63
0
#!/usr
/bin/env python # coding
: utf-8 __author__ = 'jonathan'
uw-it-aca/bridge-sis-provisioner
sis_provisioner/tests/csv/__init__.py
Python
apache-2.0
784
0
# Copyright 2022 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from django.test.utils import override_settings from sis_provisioner.tests import ( fdao_pws_override, fdao_hrp_override, fdao_bridge_override) from sis_provisioner.tests.account_managers import set_uw_account user_file_name_ov
erride = override_settings( BRIDGE_I
MPORT_USER_FILENAME="users") def set_db_records(): affiemp = set_uw_account("affiemp") javerage = set_uw_account("javerage") ellen = set_uw_account("ellen") staff = set_uw_account("staff") staff.set_disable() retiree = set_uw_account("retiree") tyler = set_uw_account("faculty") l...
graalvm/mx
mx_javacompliance.py
Python
gpl-2.0
12,586
0.002225
# # ---------------------------------------------------------------------------------------------------- # # Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it # u...
dk8, jdk9, jdk13, jdk14, ... "8,11,13+" - jdk8, jdk11, jdk
13, jdk14, ... There can be multiple parts to a version string specifying a non-contiguous range. Part N of a multi-part version string must have a strict upper bound (i.e. cannot end with "+") and its upper bound must be less than the lower bound of part N+1. Only major versions less than 10 can have a...
carlgogo/vip_exoplanets
vip_hci/preproc/subsampling.py
Python
bsd-3-clause
6,167
0.005189
#! /usr/bin/env python """ Module with pixel and frame subsampling functions. """ __author__ = 'Carlos Alberto Gomez Gonzalez, Valentin Christiaens' __all__ = ['cube_collapse', 'cube_subsample', 'cube_subsample_trimmean'] import numpy as np def cube_collapse(cube, mode='median', n=50, w=None)...
for i in range(m): arr[i, :, :] = func(array[n * i:n * i + n, :, :], axis=0) if parallactic is not None: angles[i] = func(parallactic[n * i:n * i + n]) elif array.ndim == 4: m = int(array.shape[1] / n) resid = array.shape[1] % n w = array.sh...
empty([w, m, y, x]) if parallactic is not None: angles = np.zeros(m) for j in range(w): for i in range(m): arr[j, i, :, :] = func(array[j, n * i:n * i + n, :, :], axis=0) if parallactic is not None: angles[i] = func(parallactic...
andreas-p/admin4
xrced/tools.py
Python
apache-2.0
12,508
0.003997
# Name: tools.py # Purpose: XRC editor, toolbar # Author: Roman Rolinsky <rolinsky@mema.ucl.ac.be> # Created: 19.03.2003 # RCS-ID: $Id: tools.py,v 1.12 2006/05/17 03:57:57 RD Exp $ from xxx import * # xxx imports globals and params from tree import ID_NEW # Icons im...
oups.append(customGroup) for grp in groups: self.AddGroup(grp[0]) for b in grp[1:]: self.AddButton(b[0], b[1], g.pullDownMenu.createMap[b[0]]) self.SetAutoLayout(True) self.SetSizerAndFit(self.sizer) # Allow to be resized in vertic
al direction only self.SetSizeHints(self.GetSize()[0], -1) # Events wx.EVT_COMMAND_RANGE(self, ID_NEW.PANEL, ID_NEW.LAST, wx.wxEVT_COMMAND_BUTTON_CLICKED, g.frame.OnCreate) wx.EVT_KEY_DOWN(self, self.OnKeyDown) wx.EVT_KEY_UP(self, self.OnKeyUp) def...
owenson/ardupilot
Tools/autotest/common.py
Python
gpl-3.0
8,336
0.004439
import util, pexpect, time, math from pymavlink import mavwp # a list of pexpect objects to read while waiting for # messages. This keeps the output to stdout flowing expect_list = [] def expect_list_clear(): '''clear the expect list''' global expect_list for p in expect_list[:]: expect_list.remov...
mavproxy.send('rc 7 1000\n') mav.recv_match(condition='RC_CHANNELS_RAW.chan7_raw==1000', blocking=True) def wait_mode(mav, mode): '''wait for a flight mode to be engaged''' print("Waiting for mode %s" % mode) mav.recv_match(condition='MAV.flightmode.upper()=="%s".upper()' % mode, blocking=True) ...
ode) def mission_count(filename): '''load a mission f
edx/edx-platform
openedx/features/course_duration_limits/migrations/0006_auto_20190308_1447.py
Python
agpl-3.0
448
0.002232
# Generat
ed by Django 1.11.20 on 2019-03-08 14:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('course_duration_limits', '0005_auto_20190306_1546'), ] operations = [ migrations.AddIndex( model_name='coursedurationlimitconfig', ...
), ]
lafranceinsoumise/api-django
agir/people/admin/forms.py
Python
agpl-3.0
2,983
0.000336
import traceback from crispy_forms.helper import FormHelper from crispy_
forms.layout import Submit from django import forms from django.core.exceptions import ValidationError from django.utils.html import format_html from agir.lib.form_fields import AdminRichEditorWidget, AdminJsonWidget from agir.lib.forms import CoordinatesFormMixin from agir.people.models import Person from agir.people...
person_forms.actions import ( validate_custom_fields, get_people_form_class, ) class PersonAdminForm(CoordinatesFormMixin, forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["primary_email"] = forms.ModelChoiceField( self.insta...
kickino/aws-scripts
glacier/glacier_push.py
Python
gpl-3.0
896
0.007813
#!/usr/bin/python2.7 from boto.glacier.layer1 import Layer1 from boto.glacier.concurrent import ConcurrentUploader import sys import os.path from time i
mport gmtime, strftime access_key_id = "xxx" secret_key = "xxx" target_vault_name = "xxx" inventory = "xxx" # the file to be uploaded into the vault as an archive fname = sys.argv[1] # a description you give to the file fdes = os.path.basename(sys.argv[1]) if not os.path.isfile(fname) : print("Can't find the f...
ys.exit(-1); # glacier uploader glacier_layer1 = Layer1(aws_access_key_id=access_key_id, aws_secret_access_key=secret_key, is_secure=True) uploader = ConcurrentUploader(glacier_layer1, target_vault_name, part_size=128*1024*1024, num_threads=1) archive_id = uploader.upload(fname, fdes) # write an inventory file f = o...
alexston/calibre-webserver
src/calibre/utils/pyconsole/__init__.py
Python
gpl-3.0
1,289
0.013189
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import sys, os from calibre import prints as prints_, preferred_encoding, isbytestring from calibre.utils.config import Co...
.ipc.launch import Worker from calibre.constants import __appname__, __version__, iswindows from calibre.gui2 import error_dialog # Time to wait for communication to/from the interpreter process POLL_TIMEOUT = 0.01 # seconds preferred_encoding, isbytestring, __appname__, __version__,
error_dialog, \ iswindows def console_config(): desc='Settings to control the calibre console' c = Config('console', desc) c.add_opt('theme', default='native', help='The color theme') c.add_opt('scrollback', default=10000, help='Max number of lines to keep in the scrollback buffer') ...
fharenheit/template-spark-app
src/main/python/mllib/hypothesis_testing_kolmogorov_smirnov_test_example.py
Python
apache-2.0
1,658
0.001206
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License
is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function from pyspark import SparkContext # $example on$ from pyspark.ml...
mit-pdos/secfs-skeleton
setup.py
Python
mit
883
0.002265
#!/usr/bin/env python3 from setuptools import setup setup(
name='SecFS', version='0.1.0', description='6.858 final project --- an encrypted and a
uthenticated file system', long_description= open('README.md', 'r').read(), author='Jon Gjengset', author_email='jon@thesquareplanet.com', maintainer='MIT PDOS', maintainer_email='pdos@csail.mit.edu', url='https://github.com/mit-pdos/6.858-secfs', packages=['secfs', 'secfs.store'], insta...
stephaneAG/FT232H
ft232h__PythonCompanion_WIP_TESTER.py
Python
mit
1,231
0.023558
#!/usr/bin/python import time import serial import sys import json def ftdi232h_cmd(thePort, theBaud, theCommand): ser = serial.Serial( port=thePort, # /dev/ttyUSB0 baudrate=theBaud, # 9600 parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, xonxoff=0, rtscts=0, dsrdtr=0, ...
mmand+"\n") endtime = time.time()+1 #0.2 # wait 0.2 sec result = "" while time.time() < endtime: while ser.inWaiting() > 0: #result=result+ser.read(1) result=result+ser.read() #result=ser.read() ser.close() #return result return 'callback: ['+result.rstrip('\n')+']' if len(sys.argv)!=4: print ...
(sys.argv[1], sys.argv[2], sys.argv[3]).strip() ''' import time import serial import sys import json ser = serial.Serial( port='/dev/ttyUSB0', # or /dev/ttyAMA0 for serial on the Raspberry Pi baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, xonxoff=0, rtscts=0, dsrd...
prokoudine/gimp-deskew-plugin
admin/version.py
Python
gpl-2.0
258
0.007752
# $Id: version.py 148 2006-09-22 01:30
:23Z quarl $ import subprocess def pipefrom(cmd): return subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0] # TODO: get this from config file or vice versa, but don't hard-code both. versio
n = '1.1.0'
joeribekker/restorm
restorm/clients/tests/test_jsonclient.py
Python
mit
2,145
0.006527
from decimal import Decimal import mock from unittest2
import TestCase from restorm.clients.jsonclient import JSONClient, JSONClientMixin class JSONClientTests(TestCase): def setUp(self): self.client = JSONClient() @mock.patch('httplib2.Http.request') def test_get(self, request): request.return_value = ({'Status': 200, 'Content-Type'...
='http://localhost/api') data = response.content self.assertIsInstance(data, dict) self.assertTrue('foo' in data) self.assertEqual(data['foo'], 'bar') @mock.patch('httplib2.Http.request') def test_incorrect_content_type(self, request): request.return_value = ({'...
ox-it/humfrey
humfrey/sparql/models.py
Python
bsd-3-clause
1,393
0.001436
from django.db import models from django.conf import settings from django.contrib.auth.models import User, Group from .endpoint import Endpoint DEFAULT_STORE_SLUG = getattr(settings, 'DEFAULT_STORE_SLUG', 'public') class Store(models.Model): slug = models.SlugField(primary_key=True) name = models.CharField(m...
tore', 'can update')) class UserPrivileges(models.Model): user = models.ForeignKey(User, null=True, blank=True) group = models.ForeignKey(Group, null=True, blank=True) allow_concurrent_queries = models.BooleanField() disable_throttle = models.BooleanField() throttle_threshold = models.FloatField(n...
eld(null=True, blank=True) disable_timeout = models.BooleanField() maximum_timeout = models.IntegerField(null=True)
OpenSoccerManager/opensoccermanager-editor
uigtk/nations.py
Python
gpl-3.0
6,581
0.000608
#!/usr/bin/env python3 # This file is part of OpenSoccerManager-Editor. # # OpenSoccerManager 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 la...
iter: nationid = model[treeiter][0] if data.preferences.confirm_remove: nation = data.nations.get_nation_by_id(nationid) dialog = uigtk.dialogs.RemoveItem("Nation", nati
on.name) if dialog.show(): self.delete_nation(nationid) else: self.delete_nation(nationid) def delete_nation(self, nationid): ''' Remove nation from working data and repopulate list. ''' data.nations.remove_nation(nati...
ywcui1990/nupic
tests/integration/nupic/opf/opf_checkpoint_test/experiments/temporal_multi_step/a_plus_b/description.py
Python
agpl-3.0
2,100
0.001905
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2011-2015, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software cod
e, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope
that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.g...
Rio517/pledgeservice
unittests/test_Model.py
Python
apache-2.0
4,051
0.007652
import unittest import logging #from datetime import datetime, timedelta #from google.appengine.api import memcache from google.appengine.ext import ndb from google.appengine.ext import testbed import model class TestConfig(unittest.TestCase): def setUp(self): # First, create an instance of the Testbed class. ...
ed.init_datastore_v3_stub() def tearDown(self): self.testbed.deactivate() def test_createOrUpdate(self): '''Create or Update a User''' fake_email = 'john@smith.com' fake_stripe_id = 'should there be a test ID for proper testing?' fake_occupation = 'Lobbyist'
fake_employer = 'Acme' fake_phone = '800-555-1212' fake_target = None logging.info('Testing updating a user that does not exist...') user0 = model.User.createOrUpdate( email=fake_email, occupation = fake_occupation, employer = fake_employer, phone= fake_phone ) self.ass...
waveform80/dbsuite
dbsuite/plugins/xml/__init__.py
Python
gpl-3.0
683
0
# Copyright 2012 Dave Hughes. # # This f
ile is part of dbsuite. # # dbsuite is free software: you can red
istribute 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. # # dbsuite is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied ...
monkeywidget/massive-octo-nemesis
octo_nemesis/octo_nemesis/wsgi.py
Python
gpl-2.0
399
0.002506
""" WS
GI config for octo_nemesis project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "octo_nemesis.settings") from django.co...
plication()
Kalimaha/simple_flask_blueprint
simple_flask_blueprint_test/rest/blueprint_rest_test.py
Python
gpl-2.0
729
0.001372
import unittest from flask import Flask from simple_flask_blueprint.rest.blueprint_rest import bp class SimpleBlueprintRestTest(unittest.TestCase): def setUp(self): self.app = Flask(__name__) self.app.register_blueprint(bp, url_prefix='/test') self.tester = self.app.test_client(self) ...
response = self.tester.get('/test/Kalimaha/', content_type='application/json') self.assertEquals(response.status_code, 200)
self.assertEquals(response.data, 'Hallo Kalimaha!')
knxd/pKNyX
pyknyx/stack/cemi/cemiFactory.py
Python
gpl-3.0
1,718
0.001754
# -*- coding: utf-8 -*- """ Python KNX framework License ======= - B{PyKNyX} (U{https://github.com/knxd/pyknyx}) is Copyright: - © 2016-2017 Matthias Urlichs - PyKNyX is a fork of pKNyX - © 2013-2015 Frédéric Mantegazza This program is free software; you can redistribute it and/or modify it under the terms ...
d have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or see: - U{http://www.gnu.org/licenses/gpl.html} Module purpose ============== cEMI frame manage
ment Implements ========== - B{CEMIFactory} - B{CEMIFactoryValueError} Documentation ============= Usage ===== @author: Frédéric Mantegazza @author: B. Malinowsky @copyright: (C) 2013-2015 Frédéric Mantegazza @copyright: (C) 2006, 2011 B. Malinowsky @license: GPL """ from pyknyx.common.exception import PyKNy...
Outernet-Project/librarian-netinterfaces
librarian_netinterfaces/__init__.py
Python
gpl-3.0
26
0
__ve
rsion__ = '2.0.post6'
Anorov/cloudflare-scrape
setup.py
Python
mit
943
0.002121
import os import re from setuptools import setup base_path = os.path.dirname(__file__) def get_long_description(): readme_md = os.path.join(base_path, "README.md") with open(readme_md) as f: return f.read() with open(os.path.join(base_path, "cfscrape", "__init__.py")) as f: VERSION = re.compile...
dflare-scrape for more information.', long_description=get_long_description(), long_description_content_type="text/markdown", author
="Anorov", author_email="anorov.vorona@gmail.com", url="https://github.com/Anorov/cloudflare-scrape", keywords=["cloudflare", "scraping"], include_package_data=True, install_requires=["requests >= 2.23.0"], )
sdfdemo/replication
agent/agent.py
Python
mit
2,792
0.027937
#!/usr/bin/env python import json import os import requests import urllib import ConfigParser import time import sys from bson.json_util import dumps import pyinotify from multiprocessing import Process config = ConfigParser.ConfigParser() config.read('config.ini') url = config.get("repl", "api-url") base = config.g...
ent.pathname, mask, rec=True) dir=event.pathname.replace(base,'') print "Mkdir:", dir rmkdir(dir) def process_IN_DELETE(self, event): file=event.pathname.replace(base,'') print "Removing:", file delete(file) de
f update(): while True: status() time.sleep(60) if __name__ == "__main__": # args=sys.argv[1:] # if len(args)>1 and args[0]=='transfer': # transfer(args[1]) # if len(args)>1 and args[0]=='delete': # delete(args[1]) # if len(args)>0 and args[0]=='status': # status() ...
rolandshoemaker/luther
luther/__init__.py
Python
gpl-2.0
1,181
0.001693
# _ _ _ # | | | | | | # | | _ _ | |_ | |__ ___ _ __ # | || | | || __|| '_ \ / _ \| '__| # | || |_| || |_ | | | || __/| | # |_| \__,_| \__||_| |_| \___||_| # """ .. module:: luther :synopsis: lightweight DDN
S service with REST API and JS frontend. .. moduleauthor:: Roland Shoemaker <rolandshoemaker@gmail.com> """ from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_envvar('LUTHER_SETTINGS') if app.config.get('OVERRIDE_HTTPS') a
nd app.config['OVERRIDE_HTTPS']: app.config['ROOT_HTTP'] = 'http://'+app.config['ROOT_DOMAIN'] else: app.config['ROOT_HTTP'] = 'https://'+app.config['ROOT_DOMAIN'] app.config['SUB_MAX_LENGTH'] = 255-len('.'+app.config['DNS_ROOT_DOMAIN']) db = SQLAlchemy(app) from luther.apiv1 import api_v1, run_stats app.regi...
vileopratama/vitech
src/addons/l10n_sa/__openerp__.py
Python
mit
765
0
# coding: utf-8 { 'name': 'Saudi Arabia - Accounting', 'version': '1.1', 'author': 'DVIT.ME', 'category': 'Localization', 'description': """ Odoo Arabic localization for most
arabic countries and Saudi Arabia. This initially includes chart of accounts of USA translated to Arabic. In future this module will include some payroll rules for ME . """, 'website': 'http://www.dvit.me', 'depends': ['account', 'l10n_multilang'], 'data': [ 'account.chart.template.xml', '...
auto_install': False, 'post_init_hook': 'load_translations', }
DanielWieczorek/FancyReadmeBuilder
test/business/TemplateManagerTest.py
Python
mit
727
0
from hamcrest.core.assert_that import assert_that from hamcrest.core.core.isequal import equal_to from src.business.TemplateManager import TemplateManager from src.data.template.TemplateReaderFactory import TemplateReaderFactory __author__ = 'DWI' import unittest
class TemplateManagerTest(unittest.TestCase): def test_get_template(self): reader_factory = TemplateReaderFactory() manager = TemplateManager(reader_factory) directory = "./templates" manager.load_templates(directory) assert_that(manager.get_template("test").render(), equal_...
svven/tweepy
tweepy/api.py
Python
mit
44,828
0.002521
# Tweepy # Copyright 2009-2010 Joshua Roesslein # See LICENSE for details. import os import mimetypes import urllib from tweepy.binder import bind_api from tweepy.error import TweepError from tweepy.parsers import ModelParser, Parser from tweepy.utils import list_to_csv class API(object): """Twitter API""" ...
parser=None, compression=False, wait_on_rate_limit=False, wait_on_rate_limit_notify=False, proxy=''): """ Api instance Constructor :param auth_handler: :param host: url of the server of the rest api, default:'api.twitter.com' :param search_host: url of the search serv...
to query if a GET method is used, default:None :param api_root: suffix of the api version, default:'/1.1' :param search_root: suffix of the search version, default:'' :param retry_count: number of allowed retries, default:0 :param retry_delay: delay in second between retries, default:0 ...
wicksy/laptop-build
test/test_packages.py
Python
mit
1,214
0.003295
import pytest @pytest.mark.parametrize("name", [ ("apt-file"), ("apt-transport-https"), ("arandr"), ("atom"), ("blktrace"), ("ca-certificates"), ("chromium-browser"), ("cowsay"), ("cron"), ("curl"), ("deluge"), ("diod"), ("docker-ce"), ("dropbox"), ("fonts-font-awesome"), ("git"),
("gnupg"), ("gnupg2"), ("gnupg-agent"), ("hardinfo"), ("handbrake"), ("handbrake-cli"), ("haveged"), ("htop"), ("i3"), ("iotop"), ("ipython"), ("jq"), ("language-pack-en-base"), ("laptop-mode-tools"),
("meld"), ("nfs-common"), ("ntop"), ("ntp"), ("openssh-client"), ("openssh-server"), ("openssh-sftp-server"), ("openssl"), ("pavucontrol"), ("pinta"), ("pulseaudio"), ("pulseaudio-module-x11"), ("pulseaudio-utils"), ("python"), ("python-pip"), ("scrot"), ("sl"), ("slack-desktop"), ...
redhat-cip/horizon
openstack_dashboard/dashboards/admin/networks/views.py
Python
apache-2.0
7,648
0
# Copyright 2012 NEC Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
subnets = api.neutron.subnet_list(self.request, network_id=network_id) except Exception: subnets = [] msg = _('Subnet list can not be retrieved.') exceptions.handle(self.request, msg) return subnets def get_p...
api.neutron.port_list(self.request, network_id=network_id) except Exception: ports = [] msg = _('Port list can not be retrieved.') exceptions.handle(self.request, msg) return ports def get_agents_data(self): agents = [] try: network_i...
tomkralidis/GeoHealthCheck
GeoHealthCheck/init.py
Python
mit
3,809
0
# ================================================================= # # Authors: Tom Kralidis <tomkralidis@gmail.com> # # Copyright (c) 2014 Tom Kralidis # # 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 ...
configs app.config.from_pyfile('c
onfig_main.py') app.config.from_pyfile('../instance/config_site.py') # Global Logging config logging.basicConfig(level=int(app.config['GHC_LOG_LEVEL']), format=app.config['GHC_LOG_FORMAT']) app.config['GHC_SITE_URL'] = \ app.config['GHC_SITE_URL'...
kagklis/profile-analysis
profile_analysis.py
Python
mit
16,905
0.017569
''' The MIT License (MIT) Copyright (c) 2016 Vasileios Kagklis 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, m...
type in types: N += len(glob.glob(path+"\\profile\\"+file_type)) for file_type in types: for doc in glob.glob(path+"\\profi
le\\"+file_type): if not(re.match('.+bookmark\d{4}\.html$', doc)): dic[i] = os.path.join(path+"\profile\\",doc) else: with open(doc, 'r') as fh: link = fh.readline() dic[i] = re.compi...
harperj/KDTSpecializer
setup.py
Python
bsd-3-clause
6,192
0.028262
#!/usr/bin/env python #export CC=mpicc #export CXX=mpic++ from distutils.core import setup, Extension from distutils import sysconfig import sys print "Remember to set your preferred MPI C++ compiler in the CC and CXX environment variables. For example, in Bash:" print "export CC=mpicxx" print "export CXX=mpicxx" pr...
append(("__STDC_CONSTANT_MACROS", None)) define_macros.append(("__STDC_LIMIT_MACROS", None)) COMBBLAS = "CombBLAS/" PCB = "kdt/pyCombBLAS/" GENERATOR = "CombBLAS/graph500-1.2/generator/" #files for the graph500 graph generator. generator_files = [GENERATOR+"btrd_binomial_distribution.c", GENERATOR+"splittable_mrg.c...
itions.c", GENERATOR+"graph_generator.c", GENERATOR+"permutation_gen.c", GENERATOR+"make_graph.c", GENERATOR+"utils.c", GENERATOR+"scramble_edges.c"] #pyCombBLAS extension which wraps the templated C++ Combinatorial BLAS library. pyCombBLAS_ext = Extension('kdt._pyCombBLAS', [PCB+"pyCombBLAS.cpp", PCB+"pyCombBLAS_wr...
ddico/odoo
addons/snailmail_account/wizard/account_invoice_send.py
Python
agpl-3.0
4,064
0.002953
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import UserError class AccountInvoiceSend(models.TransientModel): _name = 'account.invoice.send' _inherit = 'account.invoice.send' _description =...
_id': invoice.company_id.id, 'report_template': self.env.ref('account.account_invoices').id }) letters |= letter self.invoice_ids.filtered(lambda inv: not inv.is_move_sent).write({'is_move_sent': True}) if len(self.invoice_ids) == 1:
letters._snailmail_print() else: letters._snailmail_print(immediate=False) def send_and_print_action(self): if self.snailmail_is_letter: if self.env['snailmail.confirm.invoice'].show_warning(): wizard = self.env['snailmail.confirm.invoice'].create({'...
americanstone/mongo-connector
tests/test_config.py
Python
apache-2.0
23,616
0.001059
# Copyright 2013-2014 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
ity", }, "authentication": { "adminUsername": u"testAdminUsername", "password": u"testPassword", "passwordFile": u"testPasswordFile", }, "fields": [u"testFields1", u"testField2"], "namespaces": { ...
"mapping": {"testMapKey": u"testMapValue"}, "gridfs": [u"testGridfsSet"], }, } self.load_json(test_config, validate=False) for test_key in test_config: self.assertEqual(self.conf[test_key], test_config[test_key]) # Test for partial...
kpj/OsciPy
system.py
Python
mit
3,392
0.001474
""" Class which stores coupled collection of Kuramoto oscillators """ import numpy as np import pandas as pd from scipy.integrate import odeint import seaborn as sns import matplotlib.pylab as plt class System(object): """ Represent system of oscillators """ def __init__(self, A, B, omega, OMEGA): ...
: """ Plot solution of oscillator system. Arguments: driver_sol Solution of external driver sols List of system solutions ts List of time points of the simulat
ion """ # confine to circular region sols %= 2*np.pi driver_sol %= 2*np.pi # convert to DataFrame df = pd.DataFrame.from_dict([ { 'theta': theta, 'time': ts[i], 'oscillator': osci+1, 'source': 'r...
california-civic-data-coalition/django-calaccess-processed-data
calaccess_processed_flatfiles/migrations/0001_initial.py
Python
mit
1,525
0.001967
# Generated by Django 3.2.4 on 2021-06-11 13:24 import calaccess_processed.proxies from django.db import migrations class Migration(migrations.Migration): initial = True dependencies = [ ('elections', '0008_auto_20181029_1527'), ] operations = [ migrations.CreateModel( ...
cy', calaccess_processed.proxies.OCDProxyModelMixin), ), migrations.CreateModel( name='OCDFlatRetentionContestProxy', fields=[ ], options={ 'verbose_name_plural': 'recall measures', 'proxy': True, 'indexes
': [], 'constraints': [], }, bases=('elections.retentioncontest', calaccess_processed.proxies.OCDProxyModelMixin), ), ]
Anson-Doan/py_stringmatching
py_stringmatching/similarity_measure/affine.py
Python
bsd-3-clause
5,192
0.002119
"""Affine measure""" import numpy as np from py_stringmatching import utils from six.moves import xrange from py_stringmatching.similarity_measure.sequence_similarity_measure import \ SequenceSimilarityMeasure def sim_ident(char1, char2): return int(char1 == ...
dles the longer gaps more gracefully. For more information refer to the string ma
tching chapter in the DI book ("Principles of Data Integration"). Parameters: gap_start (float): Cost for the gap at the start (defaults to 1) gap_continuation (float): Cost for the gap continuation (defaults to 0.5) sim_func (function): Function computing similarity score between two...
RedHatInsights/insights-core
insights/parsers/tests/test_keystone.py
Python
apache-2.0
1,394
0
import doctest from insights.parsers import keystone from insights.tests import context_wrap KEYSTONE_CONF = """ [DEFAULT] # # From keystone # admin_token = ADMIN compute_port = 8774 [identity] # From keystone default_domain_id = default #domain_specific_drivers_enabled = false domain_configurations_from_database ...
onf is not None assert kconf.defaults() == {'admin_token': 'ADMIN', 'compute_port': '8774'} assert 'identity' in kconf assert 'identity_mapping' in kconf assert kconf.has_option('identity', 'default_domain_id') assert kconf.has_option('identity_mapping', 'driver') ...
ert kconf.items('DEFAULT') == {'admin_token': 'ADMIN', 'compute_port': '8774'}
AMOboxTV/AMOBox.LegoBuild
plugin.video.titan/resources/lib/resolvers/zstream.py
Python
gpl-2.0
1,309
0.004584
# -*- coding: utf-8 -*- ''' Genesis Add-on Copyright (C) 2015 lambda 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 ...
embed-%s.html' % url result = client.request(url) url = re.compile('file *: *"(http.+?)"').findall(result) url = [i for i in url if not i.endswith('.srt')][-1] url += headers return url except: return
konieboy/Seng_403
Gender Computer/nameparser/config/suffixes.py
Python
gpl-3.0
1,616
0.003094
# -*- coding: utf-8 -*- from __future__ import unicode_literals SUFFIX_NOT_ACRONYMS = set([ 'esq', 'esquire', 'jr', 'jnr', 'sr', 'snr', '2', 'i', 'ii', 'iii', 'iv', 'v', ]) SUFFIX_ACRONYMS = set([ 'ae', 'afc', 'afm', 'arrc', 'bart', 'bem', 'bt...
'dvm', 'ed', 'erd', 'gbe', 'gc', 'gcb', 'gcie', 'gcmg', 'gcsi', 'gcvo', 'gm', 'idsm', 'iom', 'iso', 'kbe', 'kcb', 'kcie', 'kcmg', 'kcsi', 'kcvo', 'kg', 'kp', 'kt', 'lg', 'lt', 'lvo', 'ma', 'mba', 'mbe', ...
mc', 'md', 'mm', 'mp', 'msm', 'mvo', 'obe', 'obi', 'om', 'phd', 'phr', 'pmp', 'qam', 'qc', 'qfsm', 'qgm', 'qpm', 'rd', 'rrc', 'rvm', 'sgm', 'td', 'ud', 'vc', 'vd', 'vrd', ]) SUFFIXES = SUFFIX_ACRONYMS | SUFFIX_NOT_ACRONY...
evernym/zeno
plenum/test/input_validation/message_validation/test_propagate_message.py
Python
apache-2.0
805
0
from collections import OrderedDict from plenum.common.messages.fields import LimitedLengthStringField from plenum.common.messages.client_request import ClientMessageValidator from plenum.common.messages.node_messages import Propagate EXPECTED_ORDERED_FIELDS = OrderedDict([ ("request", ClientMessageValidator), ...
Field), ]) def test_hash_expected_type(): assert Propagate.typename == "PROPAGATE" def test_has_expected_fields(): actual_field_names = OrderedDict(Propagate.schema).keys() assert list(actual_field_names) == list(EXPECTED_ORDERED_FIELDS.keys()) def test_has_expected_validators(): schema = dict(Pro...
ld, validator in EXPECTED_ORDERED_FIELDS.items(): assert isinstance(schema[field], validator)
iychoi/syndicate-core
python/syndicate/ag/datasets/disk.py
Python
apache-2.0
1,718
0.020955
#/usr/bin/python """ Copyright 2014 The Trustees of Princeton University 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 re...
rip("/") ) ) # build a hierarchy, using sensible default callbacks def build_hierarchy( root_dir, include_cb, disk_specfile_cbs, max_retries=1, num_threads=2, allow_partial_failure=False ): disk_crawler_cbs = AG_crawl.crawler_callbacks( include_cb=in
clude_cb, listdir_cb=disk_listdir, isdir_cb=disk_isdir ) hierarchy = AG_crawl.build_hierarchy( [root_dir] * num_threads, "/", DRIVER_NAME, disk_crawler_cbs, disk_specfile_cbs, allow_partial_failure=allow_partial_f...
chris-statzer/survivebynine
test_states.py
Python
apache-2.0
383
0.005222
import pyglet from gamewindow import GameWindow from menu import Mai
nMenuState from pyglet.gl import * window = GameWindow(width=800, height=600) pyglet
.gl.glClearColor(0.1, 0.1, 1.0, 1.0); glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) pyglet.resource.path = ['assets'] pyglet.resource.reindex() window.push_state(MainMenuState) pyglet.app.run()
MockyJoke/numbers
ex2/code/create_plots.py
Python
mit
1,292
0.01161
# coding: utf-8 # In[1]: import sys import pandas as pd import matplotlib.pyplot as plt filename1 = sys.argv[1] filename2 = sys.argv[2] #filename1 = "pagecounts-20160802-150000.txt" #filename2 = "pagecounts-20160803-150000.txt" # In[2]: dataframe1 = pd.read_table(filename1, sep=' ', header=None, index_col=1, ...
bplot(1, 2, 1) # subplots in 1 row, 2 columns, select the fir
st plt.title('Popularity Distribution') plt.xlabel("Rank") plt.ylabel("Views") plt.plot(dataframe1['views'].values) plt.subplot(1, 2, 2) # ... and then select the second plt.title('Daily Correlation') plt.xlabel("Day 2 views") plt.ylabel("Day 1 views") plt.plot(combo['views'].values,combo['views2'].values,'b.') plt.xs...
timj/scons
test/CacheDir/timestamp-newer.py
Python
mit
2,038
0.008832
#!/usr/bin/env python # # __COPYRIGHT__ # # 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, publi
sh, # distribute, sublicense, and/or sell copies of the S
oftware, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, E...
fnp/librarian
src/librarian/elements/styles/www.py
Python
agpl-3.0
62
0
fro
m ..base import WLElement class WWW(W
LElement): pass
KanoComputing/kano-profile
tests/profile/tracking/test_tracking_events.py
Python
gpl-2.0
1,689
0
# # test_tracking_events.py # # Copyright (C) 2017 Kano Computing Ltd. # License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2 # # Unit tests for functions related to tracking events: # `kano_profile.tracker.tracking_events` # import os import json import time import pytest from kano_profile.paths import t...
OKEN @pytest.mark.parametrize('event_name, event_type, event_data', [ ('low-battery', 'battery', '{"status": "low-charge"}'), ('auto-poweroff', 'battery', '{"status": "automatic-poweroff"}') ]) def test_generate_low_battery_event(event_name, event_type, event_data): if os.path.exists(tracker_events_fi...
.exists(tracker_events_file) events = [] with open(tracker_events_file, 'r') as events_f: events.append(json.loads(events_f.readline())) assert len(events) == 1 event = events[0] expected_keys = [ 'name', 'language', 'type', 'timezone_offset', 'cp...
datacratic/pymldb
pymldb/query.py
Python
isc
6,753
0.000592
# -*- coding: utf-8 -*- # Copyright (c) 2015 Datacratic Inc. All rights reserved. # @Author: Alexis Tremblay # @Email: atremblay@datacratic.com # @Date: 2015-03-06 14:53:37 # @Last Modified by: Alexis Tremblay # @Last Modified time: 2015-04-09 16:54:58 # @File Name: qu...
deepcopy(self.LIMIT) return query def __repr__(self):
return json.dumps(self.buildQuery(), indent=4) def __str__(self): return json.dumps(self.buildQuery(), indent=4)
xlk521/cloudguantou
utils/__init__.py
Python
bsd-3-clause
138
0.014493
from .decorators import render_to_json from .helper import HeadFile
Uploader, ImageFactory, BaseMod
elManager, get_first_letter, convertjson
ms-iot/python
cpython/Lib/imp.py
Python
bsd-3-clause
10,431
0.000096
"""This module provides the components needed to build your own __import__ function. Undocumented functions are obsolete. In most cases it is preferred you consider using the importlib module's functionality over this module. """ # (Probably) need to stay in _imp from _imp import (lock_held, acquire_lock, release_lo...
.cache_tag is None then NotImplementedError is raised. """ with warnings.catch_warnings(): warnings.sim
plefilter('ignore') return util.cache_from_source(path, debug_override) def source_from_cache(path): """**DEPRECATED** Given the path to a .pyc. file, return the path to its .py file. The .pyc file does not need to exist; this simply returns the path to the .py file calculated to correspond ...
ColumbiaCMB/kid_readout
apps/data_taking_scripts/old_scripts/highq_power_sweep_downstairs.py
Python
bsd-2-clause
6,148
0.018705
import matplotlib from kid_readout.roach import baseband matplotlib.use('agg') import numpy as np import time import sys from kid_readout.utils import data_file,sweeps from kid_readout.analysis.resonator.legacy_resonator import fit_best_resonator ri = baseband.RoachBaseband() ri.initialize() #ri.set_fft_gain(6) #f0s...
rt),"seconds" sys.stdout.flush() time.sleep(1) df = data_file.DataFile() #(suffix='led') df.log_hw_state(ri) sweep_data = sweeps.do_prepared_sweep(ri, nchan_per_step=atonce, reads_per_step=8, sweep_data=orig_sweep_data)
df.add_sweep(sweep_data) meas_cfs = [] idxs = [] for m in range(len(f0s)): fr,s21,errors = sweep_data.select_by_freq(f0s[m]) thiscf = f0s[m] s21 = s21*np.exp(2j*np.pi*delay*fr) res = fit_best_resonator(fr,s21,errors=errors) #Resonator(fr,s21,errors=errors) fmin = ...
carborgar/gestionalumnostfg
principal/tests.py
Python
mit
52,227
0.002642
# -*- coding: utf-8 -*- import smtplib from django.contrib.auth.models import Permission from django.test import TestCase from principal.forms import * from principal.models import * from principal.services import DepartmentService, CertificationService, UserService, ImpartSubjectService, \ AdministratorService fr...
acion', curso='4', codigo='2050032', creditos='6', duracion='C', web='http://www.lsi.us.es/docencia/pagina_asignatura.php?id=111', tipo_asignatura='OB', departamento=self.department_lsi, ) self.subject_rc = Asignatura.o
bjects.create( cuatrimestre='1', nombre='Redes de computadores', curso='2', codigo='2050013', creditos='6', duracion='C', web='https://www.dte.us.es/docencia/etsii/gii-is/redes-de-computadores', tipo_asignatura='OB', ...
hickeroar/cahoots
cahoots/parser.py
Python
mit
5,798
0
""" The MIT License (MIT) Copyright (c) Serenity Software, LLC 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, m...
m for thr in threads: results.extend(thr.results) # Unique list of all major types types = list(set([result.type for result in
results])) if results: # Getting a unique list of result types. all_types = [] for res in results: all_types.extend([res.type, res.subtype]) # Hierarchical Confidence Normalization normalizer_chain = HierarchicalNormalizerChain( ...
adelomana/viridis
growthAnalysis/epochGrapher.py
Python
gpl-2.0
2,642
0.032173
import sys,numpy,matplotlib import matplotlib.pyplot, scipy.stats import library def colorDefiner(epoch): if epoch == '0': theColor='blue' elif epoch == '0.5': theColor='red' elif epoch == '1': theColor='green' elif epoch == '1.5': theColor='orange' else: pr...
cture,figureLabel): resolution=1000 figureFile='results/figure_%s.pdf'%figureLabel for epochLabel in dataStructure: e
poch=epochLabel.split('_')[0] localTime=numpy.array(dataStructure[epochLabel][0]) shiftedTime=localTime-min(localTime) localCells=dataStructure[epochLabel][1] highResolutionTime=numpy.linspace(min(shiftedTime),max(shiftedTime),resolution) epochColor=colorDefiner(epoch) ...
alexforsale/manga_downloader
src/outputManager/base.py
Python
mit
881
0.059024
#!/usr/bin/env python # The outputManager synchronizes the output display for all the various threads ##################### import threading class outputStruct(): def __init__( self ): self.id = 0 self.updateObjSem = None self.title = "" self.numOfInc = 0 class outputManager( threading.Thread ): def __in...
utputObjs = dict() self.outputListLock = threading.Lock() # Used to assign the next id for an output object self.nextId = 0 self.isAlive = True def createOutputObj( self, name, numberOfIncrements ): raise NotImplementedError('Should have implemented this') def updateOutputObj( self, objectId )...
tedError('Should have implemented this') def run (self): raise NotImplementedError('Should have implemented this') def stop(self): self.isAlive = False
Azure/azure-sdk-for-python
sdk/cognitivelanguage/azure-ai-language-conversations/samples/async/sample_analyze_conversation_app_async.py
Python
mit
2,671
0.003744
# coding=utf-8 # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ """ FILE: sample_analyze_conversation_app_async.py DESCRIPTION: This sample demonstrates how to analyze user query for intents and entities using a ...
ediction.entities: print("\tcategory: {}".format(entity.category)) print("\ttext: {}".format(entity.text)) print("\tconfidence score: {}".format(entity.confidence_score)) # [END analyze_conversation_app_async] async def main(): await sample_analyze_conversation_app_async() ...
loop() loop.run_until_complete(main())
mzunhammer/hracing
hracing/scrape.py
Python
mit
7,747
0.023106
# Functions to download yesterday's races and associated raceforms from host import configparser import requests import re import sys import time import pymongo import random from datetime import datetime, timedelta from hracing.db import parse_racesheet from hracing.db import mongo_insert_race from hracing.tools imp...
headers = header, cookies=s.cookies)) delay_scrapin
g(start_time_2,form_min_dur) # Try parsing current race and add to mogodb. If something fails # Save race as .txt in folder for troubleshooting. # UNCOMMENT TRY/EXCEPT WHEN UP AND RUNNING #try: race=parse_racesheet(racesheet,forms) mo...
beni55/edx-platform
common/test/acceptance/tests/test_cohorted_courseware.py
Python
agpl-3.0
9,754
0.003793
""" End-to-end test for cohorted courseware. This uses both Studio and LMS. """ import json from nose.plugins.attrib import attr from studio.base_studio_test import ContainerBase from ..pages.studio.settings_group_configurations import GroupConfigurationsPage from ..pages.studio.auto_auth import AutoAuthPage as Stud...
utoAuthPage from ..tests.lms.test_lms_user_preview import verify_expected_problem_visibility from bok_choy.promise import EmptyPromise @attr('shard_1') class EndToEndCohortedCoursewareTest(ContainerBase): def setUp(self, is_staff=True): super(EndToEndCohortedCoursewareTest, sel
f).setUp(is_staff=is_staff) self.staff_user = self.user self.content_group_a = "Content Group A" self.content_group_b = "Content Group B" # Create a student who will be in "Cohort A" self.cohort_a_student_username = "cohort_a_student" self.cohort_a_student_email = "coho...
orgito/ansible
lib/ansible/modules/cloud/google/gcp_compute_health_check.py
Python
gpl-3.0
30,735
0.003677
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # ...
o not respond successfully to some number of probes in a row are marked as unhealthy. No new connections are sent to unhealthy instances, though existing connections will continue. The health check will continue to poll unhealthy instances. If an instance later responds successfully to some number of consecutiv...
ogle Inc. (@googlecloudplatform) requirements: - python >= 2.6 - requests >= 2.18.4 - google-auth >= 1.3.0 options: state: description: - Whether the given object should exist in GCP choices: - present - absent default: present check_interval_sec: description: - How often (in seconds...
monikagrabowska/osf.io
website/conferences/utils.py
Python
apache-2.0
2,561
0.001171
# -*- coding: utf-8 -*- import requests from modularodm import Q from modularodm.exceptions import ModularOdmException from framework.auth import Auth from website import util from website import settings from website.project import new_node from website.models import Node, MailRecord def record_message(message, n...
nceMessage message: :param Node node: :param User user: """ auth = Auth(user=user) node.update_node_wiki('home', message.text, auth) if conference.admins.exists(): node.add_contributors(prepare_contributors(conference.admins.all()), log=False) if not message.is_spam and conference....
eting_creation=True, auth=auth) node.add_tag(message.conference_name, auth=auth) node.add_tag(message.conference_category, auth=auth) for systag in ['emailed', message.conference_name, message.conference_category]: node.add_system_tag(systag, save=False) if message.is_spam: node.add_sys...
codenote/chromium-test
chrome/common/extensions/docs/server2/test_object_store.py
Python
bsd-3-clause
727
0.009629
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file.
from future import Future fr
om object_store import ObjectStore class TestObjectStore(ObjectStore): '''An object store which records its namespace and behaves like a dict, for testing. ''' def __init__(self, namespace): self.namespace = namespace self._store = {} def SetMulti(self, mapping, **optarg): self._store.update(map...
Yarrick13/hwasp
tests/wasp1/AllAnswerSets/bug_09.test.py
Python
apache-2.0
491
0.002037
input = """ q(a,b,c). q(b,c,a). q(c,b,c). q(b,b,c). q(a,b,b). q(c,a,a). s(c,b). s(a,b). s(a,c). s(c,c). t(a). t(b). w(b,c
). w(b,b). w(a,a). p(X,Y) :- q(X,b,Z), r(Z,b,Y), not r(X,
Y,Z). m(X,Y) :- u(a,X,Y,Y,c,X). v(X) :- s(a,X), not t(X). n(X,X) :- q(X,b,X). r(X,Y,Z) :- t(a), s(X,Z), w(X,Y), not p(Z,Y). """ output = """ {n(c,c), q(a,b,b), q(a,b,c), q(b,b,c), q(b,c,a), q(c,a,a), q(c,b,c), r(a,a,b), r(a,a,c), s(a,b), s(a,c), s(c,b), s(c,c), t(a), t(b), v(c), w(a,a), w(b,b), w(b,c)} """
kristoforcarlson/nest-simulator-fork
pynest/examples/twoneurons.py
Python
gpl-2.0
1,209
0.004136
# -*- co
ding: utf-8 -*- # # twoneurons.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 yo...
tion) any later version. # # NEST 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 Publ...
drogenlied/qudi
logic/jupyterkernel/builtin_trap.py
Python
gpl-3.0
4,344
0.003913
# -*- coding: utf-8 -*- """ A context manager for managing things injected into __builtin__. Qudi 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. Qudi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABIL...
ith Qudi. If not, see <http://www.gnu.org/licenses/>. Copyright (c) the Qudi Developers. See the COPYRIGHT.txt file at the top-level directory of this distribution and at <https://github.com/Ulm-IQO/qudi/> """ #----------------------------------------------------------------------------- # Authors: # # * Brian Gran...
khan-git/pialarmclock
faces/alarmsetting.py
Python
mit
3,537
0.009047
from utils.face import Face import pygame from utils.message import Message from utils.alarm import Alarm class Button(pygame.sprite.Sprite): def __init__(self, rect, color=(0,0,255), action=None): pygame.sprite.Sprite.__init__(self) self.color = color self.action = action self...
self.rect.height)) self.image = self.baseImage self._lines = [] for i in range(4): line = pygame.sprite.GroupSingle(Line(pygame.Rect((0, 0),(rect.height/5*4, rect.height/5)), text="Hello"))
line.sprite.rect.topright = (rect.width, rect.height/4*i) self._lines.append(line) def addAlarm(self): line = pygame.sprite.GroupSingle(Button(pygame.Rect((0, 0),(self.rect.height/5, self.rect.height/5)))) line.sprite.rect.topright = (self.rect.width, self.rect.height/...
Katello/katello-cli
src/katello/client/api/content_view.py
Python
gpl-2.0
2,845
0.000703
# -*- coding: utf-8 -*- # # Copyright 2013 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 hav...
bel) view = update_dict_unless_none(view, "description", description) path = "/api/organizations/%s/content_views/%s" % (org_id, cv_id) return self.server.PUT(path, {"content_view": view})[1] def delete(self, org_id, cv_id): path = "/api/organizations/%s/content_views/%s" % (org_id...
return self.server.DELETE(path)[1] def promote(self, cv_id, env_id): path = "/api/content_views/%s/promote" % cv_id params = {"environment_id": env_id} return self.server.POST(path, params)[1] def refresh(self, cv_id): path = "/api/content_views/%s/refresh" % cv_id retu...
chyumin/Codewars
Python/7 kyu/Most Digits.py
Python
mit
330
0.00303
# Kata link: https:
//www.codewars.com/kata/58daa7617332e59593000006 # First solution def find_longest(arr): count = [len(str(v)) for v in arr] max_value = max(count) max_index = count.index(max_value) return arr[max_index] # Another solu
tion def find_longest(arr): return max(arr, key=lambda x: len(str(x)))
beaker-project/beaker
Server/bkr/server/messaging.py
Python
gpl-2.0
11,553
0.000866
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. """ Sending messages to the AMQ """ import json import logging import ...
e_error('transport', event, level=logging.INFO) if (event.transport and event.transport.condition and event.transport.condition.name in self.fatal_conditions): log.error('closing c
onnection to: %s', event.connection.hostname) event.connection.close() class AMQProducer(object): def __init__(self, host=None, port=None, urls=None, certificate=None, private_key=None, trusted_certificates=None, topic=None, ...
netscaler/neutron
neutron/plugins/nicira/api_client/client.py
Python
apache-2.0
10,210
0.000196
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Nicira, Inc. # All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0...
onn)s. %(qsize)d " "connection(s) available."), {'rid': rid, 'conn': _conn_str(conn), 'qsize': qsize}) if
auto_login and self.auth_cookie(conn) is None: self._wait_for_login(conn, headers) return conn def release_connection(self, http_conn, bad_state=False, service_unavail=False, rid=-1): '''Mark HTTPConnection instance as available for check-out. :param...
tpazderka/pysaml2
tests/idp_conf_mdb.py
Python
bsd-2-clause
3,959
0.001011
#!/usr/bin/env python # -*- coding: utf-8 -*- from saml2 import BINDING_SOAP, BINDING_URI from saml2 import BINDING_HTTP_REDIRECT from saml2 import BINDING_HTTP_POST from saml2 import BINDING_HTTP_ARTIFACT from saml2.saml import NAMEID_FORMAT_PERSISTENT from saml2.saml import NAME_FORMAT_URI from pathutils import full...
h("servera.xml"), ), (full_path("vo_metadata.xml"), )], }], "attribute_map_dir": full_path("attributemaps"), "organization": { "name": "Exempel AB", "display_name": [("Exempel ÄB", "se"), ("Example Co.", "en")],
"url": "http://www.example.com/roland", }, "contact_person": [ { "given_name":"John", "sur_name": "Smith", "email_address": ["john.smith@example.com"], "contact_type": "technical", }, ], }
alexander-gridnev/mongstore
code/server/tests/conftest.py
Python
gpl-2.0
1,564
0.000639
import pytest import subprocess import tempfile import shutil import os import config import time import pymongo @pytest.fixture(scope='session') def mongod(request): subprocess.call(['pkill', '-f', 'mongod*tmp']) server = MongoServer() server.start() def stop(): server.stop() server....
rop_database(config.MONGO_DB_NAME) def wait_alive(self): while True: try:
client = pymongo.MongoClient(config.MONGO_URL()) result = client.admin.command('ping') if result['ok']: break except: pass time.sleep(0.1)
zerolab/wagtail
wagtail/core/migrations/0033_remove_golive_expiry_help_text.py
Python
bsd-3-clause
674
0.002967
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-31 14:33 from django.db import migrations, models class Migration(migration
s.Migration): dependencies = [ ('wagtailcore', '0032_add_bulk_delete_page_permission'), ] operations = [ migrations.AlterField( model_name='page', name='expire_at', field=models.DateTimeField(blank=True, null=True, verbose_name='expiry date/time'
), ), migrations.AlterField( model_name='page', name='go_live_at', field=models.DateTimeField(blank=True, null=True, verbose_name='go live date/time'), ), ]
iandees/all-the-places
locations/spiders/spar_no.py
Python
mit
2,746
0.005462
# -*- coding: utf-8 -*- import scrapy from locations.items import GeojsonPointItem DAYS = [ 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su' ] class SparNoSpider(scrapy.Spider): name = "spar_no" allowed_domains = ["spar.no"] start_urls = ( 'https://spar.no/Finn-butikk/', ...
response.urljoin(shop.extract()), callback=self.parse_shop ) def parse_shop(self, response): props = {} ref = response.xpath('//h1[@itemprop="name"]/text()').extract_first() if ref: # some links redirects back to list page p...
ningHoursSpecification"]') if days: for day in days: day_list = day.xpath('.//link[@itemprop="dayOfWeek"]/@href').extract() first = 0 last = 0 for d in day_list: st = d.replace('https://purl.org/g...
uzumaxy/pymodbus3
pymodbus3/bit_write_message.py
Python
bsd-3-clause
8,708
0
# -*- coding: utf-8 -*- """ Bit Writing Request/Response ------------------------------ TODO write mask request/response """ import struct from pymodbus3.constants import ModbusStatus from pymodbus3.pdu import ModbusRequest from pymodbus3.pdu import ModbusResponse from pymodbus3.pdu import ModbusExceptions from pymod...
""" Initializes a new instance :param address: The variable address written to :param value: The value written at address """ ModbusResponse.__init__(self, **kwargs) self.address = address self.value = value def encode(self): """ Encodes write coil re...
""" result = struct.pack('>H', self.address) if self.value: result += _turn_coil_on else: result += _turn_coil_off return result def decode(self, data): """ Decodes a write coil response :param data: The packet data to decode """ ...
dotsdl/PyTables
tables/tests/create_backcompat_indexes.py
Python
bsd-3-clause
1,209
0.000827
# -*- coding: utf-8 -*- # Script for creating different kind of indexes in a small space as possible. # This is intended for testing purposes. import tables class Descr(tables.IsDescription): var1 = tables.StringCol(itemsize=4, shape=(), dflt='', pos=0) var2 = tables.BoolCol(shape=(), dflt=False, pos=1) ...
e h5fname = 'indexes_2_1.h5' h5file = tables.open_file(h5fname, 'w') t1 = h5file.create_table(h5file.root, 'table1', Descr) row = t1.row for i in range(nrows): row['var1'] = i row['var2'] = i row['var3'] = i row['var4'] = i row.append() t1.flush() # Do a copy of table1 t1.copy(h5file.root, 'table2'...
tralight', _blocksizes=small_blocksizes) t1.cols.var2.create_index(3, 'light', _blocksizes=small_blocksizes) t1.cols.var3.create_index(6, 'medium', _blocksizes=small_blocksizes) t1.cols.var4.create_index(9, 'full', _blocksizes=small_blocksizes) h5file.close()