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
Sw4T/Warband-Development
mb_warband_module_system_1166/Module_system 1.166/compiler.py
Python
mit
91,472
0.028982
import sys sys.dont_write_bytecode = True from traceback import format_exc as formatted_exception, extract_stack from inspect import currentframe as inspect_currentframe, getmembers as inspect_getmembers from os.path import split as path_split, exists as path_exists from copy import deepcopy get_globals = globals ge...
e = value self.is_static = static def __add__(self, other): return VARIABLE(operands = [self, other], operation = '+') def __sub__(self, other): return VARIABLE(operands = [self, other], operation = '-') def __mul__(self, other)
: return VARIABLE(operands = [self, other], operation = '*') def __div__(self, other): return VARIABLE(operands = [self, other], operation = '/') def __mod__(self, other): return VARIABLE(operands = [self, other], operation = '%') def __pow__(self, other): return VARIABLE(operands = [self, other], operat...
projectatomic/atomic-reactor
atomic_reactor/plugin.py
Python
bsd-3-clause
24,497
0.002449
""" Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. definition of plugin system plugins are supposed to be run when image is built and we need to extract some information """ from __future__ impo...
None, exception=None): pass def save_plugin_timestamp(self, plugin, timestamp): pass def save_plugin_duration(self, plugin, duration): pass def get_available_plugins(self): """ check requested plugins availability and handle missing plugins :return...
a', 'name, plugin_class, conf, is_allowed_to_fail') for plugin_request in self.plugins_conf: plugin_name = plugin_request['name'] try: plugin_class = self.plugin_classes[plugin_name] except KeyError: if plugin_request.get('required', True): ...
anish/buildbot
master/buildbot/status/__init__.py
Python
gpl-2.0
714
0
from buildbot.status import build from buildbot.status import builder from buildbot.status import buildrequest from buildbot.status import buildset from buildbot.status import master # styles.Versioned requires this, as it keys the version numbers on the fully # qualified class n
ame; see master/buildbot/test/regressions/test_unpickling.py build.BuildStatus.__module__ = 'buildbot.status.builder' # add all of these classes to builder; this is a form of late binding to allow # circular module references among the status modules builder.BuildSetStatus = buildset.BuildSetStatus builder.Status = ma...
buildrequest.BuildRequestStatus
sonaht/ansible
lib/ansible/modules/network/ios/ios_logging.py
Python
gpl-3.0
9,798
0.000714
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Ansible by Red Hat, inc # # This file is part of Ansible by Red Hat # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Li...
st == 'host': match = re.search(r'logging host (\S+)', line, re.M) if match: name = match.
group(1) else: name = None return name def parse_level(line, dest): level_group = ('emergencies', 'alerts', 'critical', 'errors', 'warnings', 'notifications', 'informational', 'debugging') if dest == 'host': level = 'debugging' else: match = re.search(...
berkeley-stat159/project-iota
code/utils/conv_response/combine_convo_point_script.py
Python
bsd-3-clause
1,565
0.008946
import matplotlib.pyplot as plt import numpy as np from sys import argv f1 = argv[1] # task001_run001 block_convo = np.array([]) full_convo = np.array([]) block_num = [1,4,5] full_num = range(1,7,1) """ block_list = ['task001_run001/cond001.txt', 'task001_run001/cond004.txt', 'task001_run001dconv005.txt'] """ block...
02.txt', 'task001_run001/cond003.txt', 'task001_run001/cond004.txt', 'task001_run001/cond005.txt', 'task001_
run001/cond006.txt'] """ full_list = [] for i in full_num: full_list.append(f1 + '/cond00' + str(i) + '.txt') for i in block_list: block_convo = np.append(block_convo, np.loadtxt('../../../data/sub001/onsets/' + i)) for i in full_list: full_convo = np.append(full_convo, np.loadtxt('../../../data/sub001/onsets/'...
SymbiFlow/fasm
update_version.py
Python
isc
3,846
0
#!/usr/bin/env python3 import platform import subprocess import sys VERSION_FILE = 'fasm/version.py' VERSION_FILE_TEMPLATE = '''\ #!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2017-2022 F4PGA Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except ...
NING ** version_str = "{version}" version_tuple = {version_tuple} try: from packaging.version import Version as V pversion = V("{version}") except ImportError: pass git_hash = "{git_hash}" git_describe = "{git_describe}" git_msg = """\\ {git_msg} """ ''' GIT = 'git' if platform.system() == 'Windows': ...
_output(cmd).decode('utf-8').strip() except OSError: print(cmd) raise def get_describe(): cmd = [ GIT, 'describe', '--tags', 'HEAD', '--match', 'v*', '--exclude', '*-r*' ] try: return subprocess.check_output(cmd).decode('utf-8').strip() except OSError: print...
cpausmit/Kraken
filefi/024/writeCfg.py
Python
mit
6,916
0.005928
#!/usr/bin/env python """ Re-write config file and optionally convert to python """ __revision__ = "$Id: writeCfg.py,v 1.1 2011/09/19 21:41:44 paus Exp $" __version__ = "$Revision: 1.1 $" import getopt import imp import os import pickle import sys import xml.dom.minidom from random import SystemRandom from ProdCom...
rce.firstEvent = CfgTypes.untracked(CfgTypes.uint32(firstEvent)) if inputFiles: inputFileNames = inputFiles.split(',') inModule.setFileNames(*inputFileNames) # handle parent files if needed if parentFiles: parentFileNames = parentFiles.split(',') inModule.setSecondaryFileNa...
) if lumis: if CMSSW_major < 3: # FUTURE: Can remove this check print "Cannot skip lumis for CMSSW 2_x" else: lumiRanges = lumis.split(',') inModule.setLumisToProcess(*lumiRanges) # Pythia parameters if (firstRun): inModule.setFirstRun(firstRun) ...
crezefire/angle
src/tests/deqp_support/generate_case_lists.py
Python
bsd-3-clause
1,684
0.003563
#!/usr/bin/python # # Copyright 2015 The ANGLE Project Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # # generate_case_lists.py: # Helper script for updating the dEQP case list files, stored in the repo. # Generally only used when...
e can # make some options into c
ommand line arguments with default values. script_dir = os.path.dirname(sys.argv[0]) path_to_deqp_exe = os.path.join('..', '..', build_dir) deqp_data_path = os.path.join('third_party', 'deqp', 'data') os.chdir(os.path.join(script_dir, '..')) run_deqp(os.path.join(path_to_deqp_exe, 'angle_deqp_gles2_tests' + os_suffix)...
alfa-jor/addon
plugin.video.alfa/lib/python_libtorrent/python_libtorrent/functions.py
Python
gpl-3.0
9,266
0.012089
#-*- coding: utf-8 -*- ''' python-libtorrent for Kodi (script.module.libtorrent) Copyright (C) 2015-2016 DiMartino, srg70, RussakHH, aisman 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 t...
except: log('Sin
PERMISOS ROOT: %s' % str(command)) if not filetools.exists(new_libpath): log('Deleted: (%s) %s -> (%s) %s' %(size, libpath, new_size, new_libpath)) if not filetools.exists(new_libpath): filetools.copy(libp...
RobbieClarken/python3-microstacknode
tests/test_display.py
Python
gpl-3.0
2,175
0.002299
#!/usr/bin/env python3 import os import sys parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, parentdir) import time import unittest import microstacknode.hardware.display.ssd1306 from microstacknode.hardware.display.font import (FourByFiveFont, ...
sprite.rotate90(3) # self.display.clear_display() # self.display.draw_sprite(0, 0, sprite) # # time.sleep(1) # # sprite.rotate90() # # self.display.clear_display() # # self.display.draw_sprite(0, 0, sprite) # # time.sleep(1) # # sprite.rotate90() # ...
splay.ssd1306.SSD1306() as ssd1306: ssd1306.set_pixel(0, 0, 1) if __name__ == "__main__": unittest.main()
NicolasPresta/ReconoBook
reconobook_train.py
Python
mit
5,180
0.002511
# coding=utf-8 # ============================================================================== """Entrenamiento del modelo""" # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function...
FLAGS.summar
y_dir_train) else: shutil.rmtree(FLAGS.summary_dir_train) os.mkdir(FLAGS.summary_dir_train) # creamos el directorio de checkpoint_dir si no existe, y si existe lo borramos y creamos de nuevo if not os.path.exists(FLAGS.checkpoint_dir): os.mkdir(FLAGS.checkpoint_dir) else: ...
MyRobotLab/pyrobotlab
service/OculusRift.py
Python
apache-2.0
73
0.027397
# start the service oculusrift = Runtime.start("oculusrift
","Oc
ulusRift")
brownplt/k3
dj-resume/resume/generate.py
Python
apache-2.0
3,738
0.016854
import resume.models as rmod import random import logging from django.http import HttpResponse from datetime import date logger = logging.getLogger('default') def generate(request): cs_objs = rmod.Department.objects.filter(shortname='cs') if len(cs_objs) == 0: logger.info('created cs dept') cs = rmod.Depa...
ge='', headerBgImage='',\ brandColor='blue', contactName='Donald Knuth', contactEmail='test@example.com',\ techEmail='tech@example.com') cs.save() else: logger.info('used pre-existing cs dept') cs = cs_objs[0] ct_objs = rmod.ComponentType
.objects.filter(short='ta') if len(ct_objs) == 0: logger.info('created component type') ct = rmod.ComponentType(type='contactlong', name='type a', short='ta', department=cs) ct.save() else: logger.info('used existing component type') ct = ct_objs[0] ct_objs = rmod.ComponentType.objects.filter...
vakaras/nmadb-registration
src/nmadb_registration/views.py
Python
lgpl-3.0
4,119
0
from django.contrib import admin from django.db import transaction from django.core import urlresolvers from django.utils.translation import ugettext as _ from django import shortcuts from django.contrib import messages from annoying.decorators import render_to from nmadb_registration import forms, models @admin.sit...
icipality.code = row[u'code'] municipality.save() counter += 1 msg = _(u'{0} municipalities successfully imported.' ).format(counter) messages.success(request, msg) return shortcuts.redirect( 'admin:nmadb...
'app_url': urlresolvers.reverse( 'admin:app_list', kwargs={'app_label': 'nmadb_registration'}), 'app_label': _(u'NMADB Registration'), 'form': form, }
BadSingleton/pyside2
tests/signals/signal2signal_connect_test.py
Python
lgpl-2.1
3,340
0.004491
# -*- coding: utf-8 -*- ''' Test case for signal to signal connections.''' import unittest from PySide2.QtCore import * def cute_slot(): pass class TestSignal2SignalConnect(unittest.TestCase): '''Test case for signal to signal connections''' def setUp(self): #Set up the basic resources needed ...
elf): QObject.connect(self.sender, SIGNAL("mysignal(int)"), self.forwarder, SIGNAL("mysignal(int)")) QObject.connect(self.forwarder, SIGNAL("mysignal(int)"), self.callback_args) self.args = (19,) self.sender.emit(SIGNAL('mysignal(int)')
, *self.args) self.assert_(self.called) def testSignalWithMultiplePrimitiveTypeArguments(self): QObject.connect(self.sender, SIGNAL("mysignal(int,int)"), self.forwarder, SIGNAL("mysignal(int,int)")) QObject.connect(self.forwarder, SIGNAL("mysignal(int,int)"), ...
Yinan-Zhang/RichCSpace
alphashape/Homotopy.py
Python
mit
6,570
0.049772
""" This class is about determine two path homotopy classes using Constraint Satisfication Programming techniques.+ """ __author__ = 'Yinan Zhang' __revision__ = '$Revision$' import pdb import sys, os, math, time, pygame, time, copy sys.path.append('../basics/math') sys.path.append('../basics/algorithm') from numpy...
center = None; for s in union1.spheres: if center is None: center = copy.copy( s.center ); else: center += s.center; for s in union2.spheres: center += s.center; center /= ( len(union1.spheres) + len(union2.spheres) ); return center; def dist(sphere, union): '''min_dist from ...
for s in union.get_spheres(): dist = (s.center - sphere.center).r(); if dist <= min_dist: min_dist = dist; return min_dist; def heur_dist( sphere, union1, union2 ): '''returns the heuristic of the sphere''' return dist(sphere, union1) + dist(sphere, union2); def heur_cent( sphere, center ): ...
Stanford-Online/edx-platform
cms/djangoapps/contentstore/utils.py
Python
agpl-3.0
18,481
0.002705
""" Common utility functions useful throughout the contentstore """ import logging from datetime import datetime from django.conf import settings from django.urls import reverse from django.utils.translation import ugettext as _ from opaque_keys.edx.keys import CourseKey, UsageKey from pytz import UTC from six import...
ock responsible for setting this xblock's staff lock, or None if the xblock is not staff locked. If this xblock is explicitly locked, return it, otherwise find the ancestor which sets this xblock's staff lock. """
# Stop searching if this xblock has explicitly set its own staff lock if xblock.fields['visible_to_staff_only'].is_set_on(xblock): return xbloc
GripQA/client-tools
jira-access/jira_descr.py
Python
apache-2.0
2,675
0.006729
#!/usr/bin/python3 """jira_descr.py queries JIRA for issue description info The information includes, values for: - issue type - status - resolution - priority The information is retrieved and formatted for nice printing. This is a utility for configuring the JIRA access for a new project. Source documentation: http...
specific language governing permissions and limitations under the License. """ __author__ = "Dean Stevens" __copyright__ = "Copyright 2015, Grip QA" __license__ = "Apache License, Version 2.0" __status__ = "Prototype" __version__ = "0.01" import sys import textwrap from grip_import import ERR_LABEL from grip_impor...
rapper(initial_indent = " " ,subsequent_indent = ' '*16) for i in jsn: o_str = "{0} -- {1}".format(i['name'], i['description']) for l in wrapper.wrap(o_str): print(l) def descr_main(config): """Main function for retrieving and displaying Java iss...
Rostlab/nalaf
tests/features/test_simple.py
Python
apache-2.0
1,582
0.004425
import unittest from nalaf.structures.data import Dataset, Document, Part, Token from nalaf.features.simple import SimpleFeatureGenerator, SentenceMarkerFeatureGenerator class TestSimpleFeatureGenerator(unittest.TestCase): def setUp(self): part = Part('Word1 word2 word3. Word4 word5 word6.') part....
rator.generate(self.dataset) features = [token.features for token in self.dataset.tokens()] expected = iter([{'BOS[0]': 1}, {}, {'EOS[0]': 1}, {'BOS[0]': 1}, {}, {'EOS[0]': 1}]) for feature in features:
self.assertEqual(feature, next(expected)) if __name__ == '__main__': unittest.main()
pombredanne/python-npm
setup.py
Python
mit
472
0.004237
from setuptools import setup, find_packages import npm
setup( name='npm', version=npm.VERSION, packages=find_packages(exclude=('tests',)), description=
'Python bindings and utils for npm.', long_description='Documentation at https://github.com/markfinger/python-npm', install_requires=[ 'optional-django==0.1.0', ], author='Mark Finger', author_email='markfinger@gmail.com', url='https://github.com/markfinger/python-npm', )
italopaiva/your.car
yourcar/telegram_bot/migrations/0001_initial.py
Python
bsd-2-clause
818
0.002445
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-07-06 22:06 from __fut
ure__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UserBotConversation', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('cha...
bencastan/LPTHW
ex32.py
Python
gpl-3.0
736
0.012228
the_count = [1, 2, 3, 4, 5] fruits
= ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # ihis firat
kind of for-loop goes through a list for number in the_count: print "This is the count %d" % number # same as above for fruit in fruits: print "A fruit of type: %s" % fruit # also we can go through mixed lists # notice we have to use %r since we don't know what is in it for i in change: print "I got %r" %i # we...
roadmapper/ansible
lib/ansible/modules/network/aci/aci_firmware_group_node.py
Python
gpl-3.0
6,497
0.001847
#!/usr/bin/python # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUM...
- The alias for the current object. This relates to the nameAlias field in ACI. type: str extends_documentation_fragment: - aci author: - Steven Gerhart (@sgerhart) ''' EXAMPLES = ''' - name: add firmware group node aci_firmware_group_node: host: "{{ inventory_hostname }}" ...
username: "{{ user }}" password: "{{ pass }}" validate_certs: no group: testingfwgrp node: 1001 state: present - name: Remove firmware group node aci_firmware_group_node: host: "{{ inventory_hostname }}" username: "{{ user }}" password: "{{ pass...
dasbruns/netzob
src/netzob/Common/Models/Grammar/States/PrismaState.py
Python
gpl-3.0
5,647
0.007793
#-*- coding: utf-8 -*- #+---------------------------------------------------------------------------+ #| 01001110 01100101 01110100 01111010 01101111 01100010 | #| | #| Netzob : Inferring communication protocols...
id: self.trans.remove(c) if len(self.trans) == 0: self.invalid = True if
self.name.split('|')[-1] == 'START': exit() # if c in self.trans: if len(self.trans) <= len(self.usedTransitions): self.usedTransitions = [] return c def setTransitions(self, transitions): self.trans = transitions @property def transitions(s...
tedlaz/pyted
pykoinoxrista/u_dbcon.py
Python
gpl-3.0
5,047
0
# -*- coding: utf-8 -*- import sqlite3 import os from logger import log from collections import OrderedDict as odi CREATE, INSERT, UPDATE, DELETE, SCRIPT, SELECT = range(6) SQL_CREATE = 'sql_create.sql' class Sqlcon(object): def __new__(cls, action, db, sql): if not action: return None ...
def _connect(self): self.conn = sqlite3.connect(self.db) self.conn.execute('pragma foreign_keys = on') self.conn.commit() self.cur = self.conn.cursor() def select(self, sql): self.cur.execute(sql) self.conn.commit() columnNames = [t[0] for t in self.cur.des...
data = self.cur.fetchall() listdict = [] for row in data: tdic = odi() for i, col in enumerate(row): tdic[columnNames[i]] = col listdict.append(tdic) return listdict def select_one(self, table, id): sql = "SELECT * FROM %s WHER...
brandonmburroughs/food2vec
dat/RecipesScraper/RecipesScraper/settings.py
Python
mit
864
0.002315
""" Scrapy settings for RecipesScraper project. """ # Names BOT_NAME = 'RecipesScraper' SPIDER_MODULES = ['RecipesScraper.spiders'] NEWSPIDER_MODULE = 'RecipesScraper.spiders' # Obey robots.txt r
ules ROBOTSTXT_OBEY = True # Disable cookies (enabled by default) COOKIES_ENABLED = False # Configure item pipelines ITEM_PIPELINES = { 'RecipesScraper.pipelines.JsonPipeline': 300, } # Enable and configure the AutoThrottle extension (disabled by default) AUTOTHROTTL
E_ENABLED = True # The initial download delay AUTOTHROTTLE_START_DELAY = 3 # The maximum download delay to be set in case of high latencies AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server AUTOTHROTTLE_TARGET_CONCURRENCY = 2.0 # Enable showing thr...
peterwilletts24/Python-Scripts
plot_scripts/EMBRACE/plot_from_pp_geop_height_by_day_dkbhu.py
Python
mit
12,998
0.018926
""" Load pp, plot and save 8km difference """ import os, sys #%matplotlib inline #%pylab inline import matplotlib matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab! from matplotlib import rc from matplotlib.font_manager import FontProperties from matplotlib import rcParams from mpl_to...
ort matplotlib.ticker as mticker from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER import datetime from mpl_toolkits.basemap import cm import imp from textwrap import wrap import
re import iris.analysis.cartography import math from dateutil import tz #import multiprocessing as mp import gc import types import pdb save_path='/nfs/a90/eepdw/Figures/EMBRACE/' model_name_convert_title = imp.load_source('util', '/nfs/see-fs-01_users/eepdw/python_scripts/modules/model_name_convert_title.py'...
JohnMnemonick/UralsCoin
qa/pull-tester/pull-tester.py
Python
mit
8,944
0.007044
#!/usr/bin/python # Copyright (c) 2013 The Bitsend Core developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import json from urllib import urlopen import requests import getpass from string import Template import sys i...
message} resp = requests.post(commentUrl, json.dumps(post_data), auth=(os.environ['GITHUB_USER'], os.environ["GITHUB_AUTH_TOKEN"])) def testpull(number, comment_url, clone_url, commit): print("Testing pull %d: %s : %s"%(number, clone_url,commit))
dir = os.environ["RESULTS_DIR"] + "/" + commit + "/" print(" ouput to %s"%dir) if os.path.exists(dir): os.system("rm -r " + dir) os.makedirs(dir) currentdir = os.environ["RESULTS_DIR"] + "/current" os.system("rm -r "+currentdir) os.system("ln -s " + dir + " " + currentdir) out = open...
bollwyvl/ipytangle
ipytangle/__init__.py
Python
bsd-3-clause
5,335
0
import inspect from IPython.utils.traitlets import ( Any, CInt, CBool, CFloat, Dict, Tuple, link, ) from IPython.html.widgets import Widget from IPython.html.widgets.widget_selection import _Selection from .widgets import Tangle __all__ = ["Tangle", "tangle"] function = type(lambda: 0)...
__class__
class_attrs["_links"].append((key, value)) elif hasattr(value[1], "__call__"): example, fn = value traitlet_args = [example] traitlet_cls = _get_primitive(example) subscribed = inspect.getargspec(fn).args class_attrs["...
angr/angr
angr/engines/pcode/arch/ArchPcode_dsPIC33E_LE_24_default.py
Python
bsd-2-clause
4,846
0.000619
### ### This file was automatically generated ### from archinfo.arch import register_arch, Endness, Register from .common import ArchPcode class ArchPcode_dsPIC33E_LE_24_default(ArchPcode): name = 'dsPIC33E:LE:24:default' pcode_arch = 'dsPIC33E:LE:24:default' description = 'dsPIC33E' bits = 24 i...
', 1, 0xc), Register('w7', 2, 0xe), Register('w7byte', 1, 0xe), Register('w9w8', 4, 0x10), Register('w8', 2, 0x10), Register('w8byte', 1, 0x10), Register('w9', 2, 0x12), Register('w9byte', 1, 0x12), Register('w11w10', 4, 0x14), Register('w10', 2, 0...
Register('w12', 2, 0x18), Register('w12byte', 1, 0x18), Register('w13', 2, 0x1a), Register('w13byte', 1, 0x1a), Register('w15w14', 4, 0x1c), Register('w14', 2, 0x1c), Register('w14byte', 1, 0x1c), Register('w15', 2, 0x1e), Register('w15byte', 1, 0x1e), ...
ansible/tower-cli
docs/source/cli_ref/examples/inventory_script_example.py
Python
apache-2.0
327
0.003058
#!/usr/bin/env python impo
rt json inv = { '_meta': { 'hostvars': {} }, 'hosts': [] } for num in range(0, 3): host = u"host-%0.2d" % num inv['hosts'].append(host) inv['_meta']
['hostvars'][host] = dict(ansible_ssh_host='127.0.0.1', ansible_connection='local') print(json.dumps(inv, indent=2))
swiftstack/swift
test/unit/proxy/test_sysmeta.py
Python
apache-2.0
21,779
0
# Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
m swift.proxy.controllers.base import get_object_info from test.unit import FakeMemcache, debug_logger, FakeRing, \ fake_http_connect, patch_policies, skip_if_no_xattrs class FakeServerConnection(WSGIContext): '''Fakes an HTTPConnection to a server instance.''' def __init__(self, app): super(FakeS...
self.data = b'' def getheaders(self): return self._response_headers def read(self, amt=None): try: return next(self.resp_iter) except StopIteration: return b'' def getheader(self, name, default=None): result = self._response_header_value(name) ...
axbaretto/beam
sdks/python/.tox/py27gcp/lib/python2.7/site-packages/google/cloud/_testing.py
Python
apache-2.0
3,140
0
# Copyright 2014 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
_error(StatusCode.FAILED_PRECONDITION) def _make_grpc_deadline_exceeded(self): from grpc import StatusCode return self._make_grpc_error(StatusCode.DEADLINE_EXCEEDED) class _GAXPageIterator(object): def __init__(self, *pages, **kwargs): self._pages
= iter(pages) self.page_token = kwargs.get('page_token') def next(self): import six return six.next(self._pages) __next__ = next
EmanueleCannizzaro/scons
src/engine/SCons/Tool/mssdk.py
Python
mit
1,834
0.001636
# # Copyright (c) 2001 - 2016 The SCons Foundation # # 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...
PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION #...
FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/mssdk.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog" """engine.SCons.Tool.mssdk Tool-specific initialization for Microsoft SDKs, both Platform SDKs and Windows SDKs. ...
adamcandy/qgis-plugins-meshing
dev/tests/gaussian_bump.py
Python
lgpl-2.1
4,413
0.009517
#!/usr/bin/env python ########################################################################## # # QGIS-meshing plugins. # # Copyright (C) 2012-2013 Imperial College London and others. # # Please see the AUTHORS file in the main source directory for a # full list of copyright holders. # # Dr Adam S. Can...
fl 50.0 NETCDF:"'+output_file+'":z 50_contour.shp') if __name__ == "__main__":
main()
auspex/sonyutilities
iterator.py
Python
gpl-3.0
1,536
0.013672
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import (division, absolute_import, print_function) __license__ = 'GPL v3' __copyright__ = '2014, Derek Broughton <auspex@pointerstop.ca>' __docformat__ = 'restructuredtext en' from calibre.ebooks.oeb.iterator.book import EbookI...
okmark(self, bm): prefi
x = self._tdir.tdir+'/' filename = self.spine[bm['spine']].rpartition(prefix)[2] pos = bm['pos'].split('/') # ADE doesn't count the <HEAD> tag if pos[1] == '2': pos[1] = '1' bookmark = "%s#point(%s)" % filename, '/'.join(pos...
cpina/science-cruise-data-management
ScienceCruiseDataManagement/main/management/commands/exportgpstracks.py
Python
mit
8,461
0.004728
from django.core.management.base import BaseCommand, CommandError from ship_data.models import GpggaGpsFix import datetime from main import utils import csv import os from django.db.models import Q import glob from main.management.commands import findgpsgaps gps_bridge_working_intervals = None # This file is part of ...
e_string = date_time_string else: if gps_info.device_id == 63: l = [gps_info.date_time.strftime("%Y-%m-%d %H:%M:%S"),
"{:.4f}".format(gps_info.latitude), "{:.4f}".format(gps_info.longitude)] # print(l) csv_writer.writerow(l) previous_date_time_string = date_time_string def delete_files(files): for file in files: print("Deleti...
alienlike/hypertextual
hypertextual/models/breadcrumb.py
Python
agpl-3.0
100
0.01
class Breadcrumb: def __init__(s
elf, text, url): self.text = text self.url =
url
UManPychron/pychron
pychron/hardware/environmental_probe.py
Python
apache-2.0
1,717
0.000582
# =============================================================================== # Copyright 2014 Jake Ross # # 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...
=============== # ============= enthought library imports ======================= # ============= standard librar
y imports ======================== # ============= local library imports ========================== from __future__ import absolute_import from pychron.hardware.core.core_device import CoreDevice class TempHumMicroServer(CoreDevice): """ http://www.omega.com/Manuals/manualpdf/M3861.pdf iServer MicroServ...
ryanjw/co-occurrence_python
first_attempt.py
Python
gpl-2.0
1,125
0.022222
# need to pass it a file, where data starts, path to write # things to import import sys import pandas import scipy import numpy from scipy import stats from scipy.stats import t # arguments being passed p
ath_of_file=sys.argv[1] last_metadata_column=int(sys.argv[2]) path_to_write=sys.argv[3] # spearman p calc based on two tailed t-test def spearmanp(r,n): tstat=r*numpy.sqrt((n-2)/(1-r**2)) return t.cdf(-abs(tstat),n-2)*2 # read in the data df=pandas.read_table(path_of_file,index_col=False) # remove metadata co...
corr(method="spearman") #make column based on rows (called indexes in python) df_corr_matrix["otus"]=df_corr_matrix.index #melt dataframe but maintain indices now called otus df_melt=pandas.melt(df_corr_matrix,id_vars="otus") # remove NAs or NaNs which are result of non-existent otus (all 0 values) df_melt=df_melt[nump...
Lothiraldan/ZeroServices
tests/utils.py
Python
mit
3,193
0.000313
import asyncio try: from unittest.mock import Mock, create_autospec except ImportError: from mock import Mock, create_autospec from uuid import uuid4 from functools import wraps from copy import copy from unittest import TestCase as unittestTestCase from zeroservices.exceptions import ServiceUnavailable from...
infos) base_in
fos.update(super().service_info()) return base_infos @asyncio.coroutine def on_message(self, *args, **kwargs): return self.on_message_mock(*args, **kwargs) @asyncio.coroutine def on_event(self, *args, **kwargs): return self.on_event_mock(*args, **kwargs) def _create_test_serv...
agoravoting/election-orchestra
public_api.py
Python
agpl-3.0
8,209
0.001707
# -*- coding: utf-8 -*- # # SPDX-FileCopyrightText: 2013-2021 Agora Voting SL <contact@nvotes.com> # # SPDX-License-Identifier: AGPL-3.0-only # import pickle import base64 import json import re from datetime import datetime from flask import Blueprint, request, make_response, abort from frestq.utils import loads, du...
}, "end_date": "2013-12-09T18:17:14.457000", "start_date": "2013-12-06T18:17:14.457000", "questions": [ { "description": "", "layout": "pcandidates-election", "max": 1, "min": 0, "num_winners": 1, "title"...
-large", "answer_total_votes_percentage": "over-total-valid-votes", "answers": [ { "id": 0, "category": "Equipo de Enfermeras", "details": "", "sort_order": 1, "urls": [ ...
ygravrand/pyconfr2015
breizhcamp2016/ex2_multi_process/fast_food.py
Python
mit
429
0
# Encoding: utf-8 import sys import time from flask import Flask app = Flask(__name__) def kitchen_work(): time.sleep(5)
@app.route('/') def fast_food_host(): print 'Order sent to the kit
chen, waiting...' sys.stdout.flush() kitchen_work() print 'Burger received from kitchen!' sys.stdout.flush() return 'Here\'s your order.' if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
jasonljc/enterprise-price-monitor
django_monitor/price_monitor/spider/data_loader.py
Python
mit
3,067
0.005217
from price_monitor.models import Site, Price, SiteQuery import json from os import path import os import logging logging.basicConfig(level=logging.DEBUG, filename="logfile", filemode="a+", format="%(asctime)-15s %(levelname)-8s %(message)s") logger = logging.getLogger(__name__) class DataLoader(o...
return Site.objects.get(site_location=d['location']) def build_site_query(d, site): site_query_set = SiteQuery.objects.filter(search_time=d['
search_time'], site_id=site) if not site_query_set: start_date = '%s%s'%(d['start_date_month'], d['start_date_input'].zfill(2)) end_date = '%s%s'%(d['end_date_month'], d['end_date_input'].zfill(2)) site_query = SiteQuery(search_time=d['search_time'], ...
jamespcole/home-assistant
homeassistant/components/edp_redy/sensor.py
Python
apache-2.0
3,481
0
"""Support for EDP re:dy sensors.""" import logging from homeassistant.const import POWER_WATT from homeassistant.helpers.entity import Entity from . import EDP_REDY, EdpRedyDevice _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['edp_redy'] # Load power in watts (W) ATTR_ACTIVE_POWER = 'active_power' async...
device_json = self._session.modules_dict[self._id] self._parse_data(device_json) else: self._is_available = False def _parse_data(self, data): """Parse data received from the server.""" super()._parse_data(data
) _LOGGER.debug("Sensor data: %s", str(data)) for state_var in data['StateVars']: if state_var['Name'] == 'ActivePower': try: self._state = float(state_var['Value']) * 1000 except ValueError: _LOGGER.error("Could not p...
HybridF5/jacket
jacket/api/compute/openstack/compute/flavors_extraspecs.py
Python
apache-2.0
6,329
0
# Copyright 2010 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
smatch') raise webob.exc.HTTPBadRequest(explanation=expl) flavor = common.get_flavor(context, flavor_id) try: flavor.extra_specs = dict(flavor.extra_specs, **body) flavo
r.save() except exception.FlavorExtraSpecUpdateCreateFailed as e: raise webob.exc.HTTPConflict(explanation=e.format_message()) except exception.FlavorNotFound as e: raise webob.exc.HTTPNotFound(explanation=e.format_message()) return body @extensions.expected_errors(4...
CALlanoR/virtual_environments
medical_etls/part1/etls/utils.py
Python
apache-2.0
607
0.011532
import os import csv def get_value_or_default(value, default=None): result = value.strip() if len(result) == 0: result = default return result def read_csv_file(csv_file_name, delimiter,
quote_char='"', skip_header=True, encoding='latin-1'): print(csv_file_name) fd = open(file=csv_file_name, mode='r', encoding=encoding) csv_reader = csv.reader(fd, delimiter=delimiter, qu
otechar=quote_char) if skip_header: next(csv_reader) for row in csv_reader: yield row fd.close()
banwagong-news/ssbc
workers/clean_rubbish_res.py
Python
gpl-2.0
1,384
0.011561
#!/usr/bin/env python #coding: utf8 import MySQLdb as mdb import MySQLdb.cursors SRC_HOST = '127.0.0.1' SRC_USER = 'root' SRC_PASS = '' DATABASE_NAME = '' DST_HOST = '127.0.0.1' DST_USER = 'root' DST_PASS = '' src_conn = mdb.connect(SRC_HOST, SRC_USER, SRC_PASS, DATABASE_NAME, charset='utf8', cursorc...
dst_curr.exe
cute('delete from rt_main where id = %s'%(id)) if __name__ == '__main__': delete(sys.argv[1])
ucrcsedept/galah
galah/db/models/classes.py
Python
apache-2.0
145
0.02069
from
mongoengine import * class Class(Document): name = StringField(required = True)
meta = { "allow_inheritance": False }
monal94/digits-scikit-learn
main.py
Python
mit
2,459
0.001627
# Import 'datasets' from 'sklearn' import numpy as np from sklearn import datasets from sklearn.decomposition import PCA, RandomizedPCA import matplotlib.pyplot as plt # Load in the 'digits' data digits = datasets.load_digits() # Print the 'digits' data print(digits) # Print the keys print(digits.keys) # Print out ...
the target value ax.text(0, 7, str(digits.target[i])) # Show the plot plt.show() # Create a Randomized PCA model that takes two components randomized_pca = RandomizedPCA(n_components=2) # Fit and transform the data to the model reduced_data_rpca = randomized_pca.fit_transform(digits.data) # Create a regular PC...
transform the data to the model reduced_data_pca = pca.fit_transform(digits.data) # Inspect the shape print(reduced_data_pca.shape) # Print out the data print(reduced_data_rpca) print(reduced_data_pca) colors = ['black', 'blue', 'purple', 'yellow', 'white', 'red', 'lime', 'cyan', 'orange', 'gray'] for i in range(len...
LockScreen/Backend
venv/lib/python2.7/site-packages/awscli/customizations/codedeploy/systems.py
Python
mit
7,661
0.000131
# Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
mport os import subprocess DEFAULT_CONFIG_FILE = 'codedeploy.onpremises.yml' class System: UNSUPPORTED_SYSTEM_MSG = ( 'Only Ubuntu Server, Red Hat Enterprise Linux Server and ' 'Windows Server operating systems are supported.' ) def __init__(self, params): self.session = params.s...
date_administrator(self): raise NotImplementedError('validate_administrator') def install(self, params): raise NotImplementedError('install') def uninstall(self, params): raise NotImplementedError('uninstall') class Windows(System): CONFIG_DIR = r'C:\ProgramData\Amazon\CodeDeploy...
Shea690901/mudrpc
python/lib/PickleRPC/setup.py
Python
isc
690
0.004348
f
rom setuptools import setup, find_packages import sys, os version = '0.0' setup(name='PickleRPC', version=version, description="RPC using pickle", long_description="""\ """, classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='', autho...
license='', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, install_requires=[ # -*- Extra requirements: -*- ], entry_points=""" # -*- Entry points: -*- """, )
akx/coffin
coffin/views/generic/__init__.py
Python
bsd-3-clause
35
0
from django
.views.generic import *
litex-hub/pythondata-cpu-blackparrot
pythondata_cpu_blackparrot/system_verilog/black-parrot/external/basejump_stl/testing/bsg_cache/regression_non_blocking/test_block_ld2.py
Python
bsd-3-clause
747
0.024096
import sys import random from test_base import * class TestBlockLD2(TestBase): def generate(self): self.clear_tag() for n in range(50000): tag = random.randint(0, 15)
index = random.randint(0,self.sets_p-1) taddr = self.get_addr(tag,index) op = random.randint(0,2) if op ==
0: self.send_block_st(taddr) elif op == 1: self.send_block_ld(taddr) else: self.send_aflinv(taddr) self.tg.done() def send_block_st(self, addr): base_addr = addr - (addr % (self.block_size_in_words_p*4)) for i in range(self.block_size_in_words_p): self.send_sw...
RedHatEMEA/aws-ose3
target/reip.py
Python
apache-2.0
18,095
0.003426
#!/usr/bin/python import OpenSSL.crypto import argparse import base64 import glob import k8s import os import shutil import yaml def sn(): sn = int(open("/etc/origin/master/ca.serial.txt").read(), 16) sntext = "%X" % (sn + 1) if len(sntext) % 2: sntext = "0" + sntext open("/etc/origin/maste...
er.local", "openshift", "openshift.default", "openshift.default.svc", "openshift.default
.svc.cluster.local", args.private_ip, args.private_hostname, args.public_ip, args.public_hostname ] y["etcdClientInfo"]["urls"] = ["https://" + args.private_host...
georgemarshall/django
django/contrib/admin/templatetags/admin_list.py
Python
bsd-3-clause
18,018
0.001665
import datetime from django.contrib.admin.templatetags.admin_urls import add_preserved_filters from django.contrib.admin.utils import ( display_for_field, display_for_value, label_for_field, lookup_field, ) from django.contrib.admin.views.main import ( ALL_VAR, ORDER_VAR, PAGE_VAR, SEARCH_VAR, ) from django.co...
_name(field_name, i) # Potentially not sortable # if the field is the action checkbox: no sorting and special class if field_name == 'action_checkbox': yield { "text": text, "class_attrib": mark_safe('
class="action-checkbox-column"'), "sortable": False, } continue admin_order_field = getattr(attr, "admin_order_field", None) # Set ordering for attr that is a property, if defined. if isinstance(attr, property) and hasattr(attr, '...
trafferty/utils
python/buildVideoXML.py
Python
gpl-2.0
3,204
0.006554
#!/Library/Frameworks/Python.framework/Versions/Current/bin/python import os from os.path import join, getsize from random import randint def addEntry (XMLFile, finfo, dirs, NASPath): #finfo[1].replace(' ', '_') finfo[1] = finfo[1].replace('.', '_', finfo.count('.')-1) title = finfo[1].split('.')[0] ...
le.close() print 'Built XML media file for ' + str(len(allfiles) + 1
) + ' movies'
shutej/tapcfg
drivers/osx/tuntap/test/tuntap/tuntap_tests.py
Python
lgpl-2.1
4,009
0.012472
# Copyright (c) 2011 Mattias Nissler <mattias.nissler@gmx.de> # # Redistribution and use in source and binary forms, with or without modification, are permitted # provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of # condition...
THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCL...
ROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBIL...
Tha-Robert/kademlia
kademlia/storage.py
Python
mit
2,552
0.000784
import time from itertools import izip from itertools import imap from itertools import takewhile import operator from collections import OrderedDict from zope.interface import implements from zope.interface import Interface class IStorage(Interface): """ Local storage for this node. """ def __setit...
ta: return False, self[key] return False, default def __getitem__(self, key): self.cull() return self.data[key][1] def __iter__(
self): self.cull() return iter(self.data) def __repr__(self): self.cull() return repr(self.data) def iteritemsOlderThan(self, secondsOld): minBirthday = time.time() - secondsOld zipped = self._tripleIterable() matches = takewhile(lambda r: minBirthday >=...
aarongarrett/inspyred
examples/advanced/parallel_evaluation_pp_example.py
Python
mit
1,728
0.011574
from random import Random from time import time import inspyred import math # Define an additional "necessary" function for the evaluator # to see how it must be handled when using pp. def my_squa
ring_function(x): return x**2 def generate_rastrigin(random, args): size = args.get('num_inputs', 10) return [random.uniform(-5.12, 5.12) for i in range(size)] def evaluate_rastrigin(candidates, args): fitness = [] for cs in candidates: fit = 10
* len(cs) + sum([(my_squaring_function(x - 1) - 10 * math.cos(2 * math.pi * (x - 1))) for x in cs]) fitness.append(fit) return fitness def main(prng=None, display=False): if prng is None: prng = Random() prn...
dh1tw/pyhamtools
docs/source/conf.py
Python
mit
8,402
0.006308
# -*- coding: utf-8 -*- # # pyhamtools documentation build configuration file, created by # sphinx-quickstart on Thu Apr 24 01:00:39 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # ...
short X.Y version
. version = __version__ # The full version, including alpha/beta/rc tags. release = __release__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false valu...
sputnick-dev/weboob
modules/hellobank/perso/transactions.py
Python
agpl-3.0
4,962
0.007457
# -*- coding: utf-8 -*- # Copyright(C) 2013 Christophe Lampin # Copyright(C) 2009-2012 Romain Bignon # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either ...
\d*X*\d*)?$'), FrenchTransaction.TYPE_CARD), (re.compile('^(?P<category>(PRELEVEMENT|TELEREGLEMENT|TIP)) (?P<text>.*)'), FrenchTransaction.TYPE_ORDER),
(re.compile('^(?P<category>ECHEANCEPRET)(?P<text>.*)'), FrenchTransaction.TYPE_LOAN_PAYMENT), (re.compile('^(?P<category>RETRAIT DAB) (?P<dd>\d{2})/(?P<mm>\d{2})/(?P<yy>\d{2})( (?P<HH>\d+)H(?P<MM>\d+))? (?P<text>.*)'), FrenchTransact...
emilybache/texttest-runner
src/main/python/lib/default/batch/batchutils.py
Python
mit
1,956
0.005624
import plugins, datetime, time, os class BatchVersionFilter: def __init__(self, batchSession): self.batchSession = batchSession def verifyVersions(self, app): badVersion = self.findUnacceptableVersion(app) if badVersion is not None: raise plugins.TextTestError, "unregistere...
datetime.timedelta(hours=8) return timeToUse.strftime("%d%b%Y") def parseFileName(fileName, diag): versionStr = fileName[5:-5] components = versionStr.split("_")
diag.info("Parsing file with components " + repr(components)) for index, component in enumerate(components[1:]): try: diag.info("Trying to parse " + component + " as date") date = time.strptime(component, "%d%b%Y") version = "_".join(components[:index + 1]) ...
Com-Mean/MLinAcition
chapter9/treeExplore.py
Python
gpl-3.0
1,329
0.009916
#!/usr/bin/env python # -*- coding: utf-8 -*- ######################################################################### # File Name: treeExplore.py # Author: lpqiu # mail: qlp_1018@126.com # Created Time: 2014年09月13日 星期六 21时42分58秒 ######################################################################### from numpy imp...
ert(0, '1.0') Button(root, text='ReDraw', command=drawNewTree).grid(row=1, column=2,\ rowspan=3) chkBtnVar = IntVar() chkBtn = Checkbutton(root, text='Model Tree', variable=chkBtnVar) chkBtn.grid(row=3, column=0, columnspan=2) reDraw.drawDat= mat(regTrees.loadDataSet('sine.txt')) r...
) root.mainloop() if __name__=="__main__": treeExplore()
allisson/django-tiny-rest
tiny_rest/tests/test_authorization.py
Python
mit
3,377
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.test import TestCase, RequestFactory from django.contrib.auth import get_user_model, authenticate from django.contrib.auth.models import AnonymousUser import json import status from tiny_rest.views import APIView from tiny_rest.authorization ...
ory = RequestFactory() self.user = User.objects.create_user( 'user', 'user@email.com', '
123456' ) class TestIsAuthenticatedAPIView(BaseTestCase): def test_authenticate(self): request = self.factory.get('/') request.user = authenticate(username='user', password='123456') response = IsAuthenticatedAPIView.as_view()(request) data = json.loads(response.content.de...
YoQuieroSaber/yournextrepresentative
candidates/management/commands/candidates_delete_party_images.py
Python
agpl-3.0
1,053
0.00095
from candidates.models import PopItPerson from candidates.popit import PopItApiMixin, popit_unwrap_pagination from django.core.management.base import BaseCommand class Command(PopItApiMixin, BaseCommand): def handle(self, **options): for o in popit_unwrap_pagination( self.api.organization...
date the cache
# entries for any person who's a member of this party: for membership in o.get('memberships', []): person = PopItPerson.create_from_dict(membership['person_id']) person.invalidate_cache_entries()
jasonwee/asus-rt-n14uhp-mrtg
src/lesson_mathematics/fractions_limit_denominator.py
Python
apache-2.0
249
0
import fractions import math print('P
I =', math.pi) f_pi = fractions.Fraction(str(math.pi)) print('No limit =', f_pi) for i in [1, 6, 11, 60, 70, 90, 100]: limited = f_pi.limit_denominator(i) print('{0:8} = {1}
'.format(i, limited))
nuagenetworks/vspk-python
vspk/v6/nugatewayslocation.py
Python
bsd-3-clause
17,817
0.008868
# -*- coding: utf-8 -*- # # Copyright (c) 2015, Alcatel-Lucent Inc, 2017 Nokia # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyrigh...
remote_name="associatedEntityName", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name="associated_entity_type", remote_name="associatedEntityType", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name="state"
, remote_name="state", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name="owner", remote_name="owner", attribute_type=str, is_required=False, is_unique=False) self.expose_attribute(local_name="external_id", remote_name="externalID", attribute_type=str, is_required=...
tseaver/gcloud-python
monitoring/google/cloud/monitoring_v3/gapic/enums.py
Python
apache-2.0
21,475
0.003679
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
SOUTH_AMERICA (int): Allows checks to run from locations within the continent of South America. ASIA_PACIFIC (int): Allows checks
to run from locations within the Asia Pacific area (ex: Singapore). """ REGION_UNSPECIFIED = 0 USA = 1 EUROPE = 2 SOUTH_AMERICA = 3 ASIA_PACIFIC = 4 class GroupResourceType(enum.IntEnum): """ The supported resource types that can be used as values of group_resource.resource_t...
joke2k/faker
faker/providers/person/or_IN/__init__.py
Python
mit
35,828
0
from .. import Provider as PersonProvider class Provider(PersonProvider): formats_female = ( "{{first_name_female}} {{last_name}}", "{{first_name_unisex}} {{last_name}}", "{{prefix_female}} {{first_name_unisex}} {{last_name}}", "{{prefix_female}} {{first_name_female}} {{last_name}}...
"ଓମ୍", "କନକବର୍ଦ୍ଧନ", "କପିଳ", "କମଳାକାନ୍ତ", "କରୁଣାକର", "କରେନ୍ଦ୍ର", "କଳିଙ୍ଗ", "କଳ୍ପତରୁ", "କହ୍ନେଇ", "କାଙ୍ଗାଳି", "କାଙ୍ଗୋଇ", "କାର୍ତ୍ତିକ", "କାର୍ତ୍ତିକେଶ୍ୱର", "କାଳନ୍ଦ
ୀ", "କାଳିଆ", "କାଳୁଖଣ୍ଡାୟତ", "କାଶୀନାଥ", "କାହ୍ନୁ", "କାହ୍ନୁରାମ", "କିରଣ", "କିଶୋରଚନ୍ଦ୍ର", "କିଶୋରୀମଣି", "କୁଞ୍ଜବିହାରୀ", "କୁଣାଳ", "କୁନା", "କୁମୁଦ", "କୁଳମଣି", "କୃଷ୍ଣ", "କୃଷ୍ଣଚନ୍ଦ୍ର", "କେଦାର", "କ...
AtteqCom/zsl
src/zsl/db/helpers/sorter.py
Python
mit
3,601
0.003888
""" :mod:`zsl.db.helpers.sorter` ---------------------------- """ from __future__ import unicode_literals from builtins import object, zip from sqlalchemy import asc, desc DEFAULT_SORT_ORDER = 'ASC'
# If changed, look at the condition in apply_sorter if self.
get_order() == "DESC":. class Sorter(object): """ Helper class for applying ordering criteria to query. """ def __init__(self, sorter, mappings=None): """ sorter = {'sortby': string, 'sort': string} sortby - string of comma-separated column names by which you want to order...
gundalow/ansible-modules-core
network/nxos/nxos_udld_interface.py
Python
gpl-3.0
15,900
0.001195
#!/usr/bin/python # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distribut...
error=str(clie), commands=commands) except AttributeError: try: commands.insert(0, 'configure') module.cli.add_commands(commands, output='config')
module.cli.run_commands() except ShellError: clie
Star2Billing/cdr-stats
cdr_stats/import_cdr/models.py
Python
mpl-2.0
2,641
0.002272
# # CDR-Stats License # http://www.cdr-stats.org # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (C) 2011-2015 Star2Billing S.L. # # The Initial Develope...
ld(blank=True, null=True) waitsec = models.IntegerField(blank=True, null=True) hangup_cause_id = models.IntegerField(blank=True, null=True) hangup_cause = models.CharField(max_length=80, blank=True) direction = models.IntegerField(blank=
True, null=True) country_code = models.CharField(max_length=3, blank=True) accountcode = models.CharField(max_length=40, blank=True) buy_rate = models.DecimalField(max_digits=10, decimal_places=5, blank=True, null=True) buy_cost = models.DecimalField(max_digits=12, decimal_places=5, blank=True, null=Tru...
j831/zulip
zerver/tests/test_bots.py
Python
apache-2.0
34,708
0.001441
from __future__ import absolute_import from __future__ import print_function import filecmp import os import ujson from django.core import mail from django.http import HttpResponse from django.test import override_settings from mock import patch from typing import Any, Dict, List from zerver.lib.actions import do_ch...
m) event = [e for e in events if e['event']['type'] == 'realm_bot'][0] self.assertEqual( dict( type='realm_bot', op='add', bot=dict(email='hambot-bot@zulip.testserver', user_id=bot.id, full_nam...
et', is_active=True, api_key=result['api_key'], avatar_url=result['avatar_url'], default_sending_stream=None, default_events_register_stream=None, default_all_public_stre...
ilique/webpushkin
pushkin/migrations/0025_auto_20160616_1637.py
Python
mit
495
0.00202
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-06-16 16:37 from __future_
_ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pushkin', '0024_authparam_secret'), ] operations = [ migrations.AlterField(
model_name='command', name='arguments', field=models.ManyToManyField(blank=True, null=True, to='pushkin.CommandArgument'), ), ]
Micronaet/micronaet-migration
script6_7/migrate.py
Python
agpl-3.0
52,936
0.026269
#!/usr/bin/python # coding=utf-8 ############################################################################### # # Micronaet S.r.l., Migration script for PostgreSQL # Copyright (C) 2002-2013 Micronaet SRL (<http://www.micronaet.it>). # All Rights Reserved # # This program is free software: you can redistr...
6: 14, # tax 7: 5, # cash 8: 6, # asset 9: 4, # b
ank 10: 15, # equity }, ) #account_account_type.migrate() # Operation: manually mapping # # | > (account.payment.term.line >> on line_ids type one2many) account_payment_term = table( name = 'account.payment.term', key = 'name', o6 = o6, o7 = o7, mapping_databases = berkeley_tables, ...
LukeBaal/PublicProjects
python tree diagrams/bin_tree.py
Python
mit
3,330
0.009309
class Leaf(): def __init__(self, screen, xy_pos=[0, 0], value="", radius=15, color=[0, 0, 0]): self.screen = screen self.color = color self.value = value self.radius = radius self.width = 1 self.
x = coord[0] self.y = coord[1] self.top_y = self.y - self.radius self.bot_y = self.y + self.radius self.left = None self.right = None # ----------------------SET METHODS------------------------- def set_color(self, color): self.color = color ...
# ----------------------GET METHODS-------------------- def get_value(self): return self.value def get_left(self): return self.left def get_right(self): return self.right def get_pos(self): return self.x, self.y def get_x(self): retu...
vakila/de-stress
testproject/testapp/migrations/0001_initial.py
Python
mit
1,334
0.002249
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Exercise', fields=[ ('id', models.AutoField(ser...
exercises', models.ManyToManyField(help_text='', to='testapp.Exercise')), ], options={ }, bases=(models.Model,),
), ]
miku/siskin
siskin/test_conversions.py
Python
gpl-3.0
11,642
0.001117
import json import pymarc from siskin.conversions import (de_listify, imslp_xml_to_marc, osf_to_intermediate) def test_imslp_xml_to_marc(): example = """<?xml version="1.0"?> <document docID="imslpvalsskramstadhans"> <localClass localClassName="col">imslp</localClass> <localClass localClassName=...
ang menyimpang dan mengarahkan seseorang dalam memahami konsep Allah yang benar sesuai dengan pernyataan Allah m", "is_published": true, "is_preprint_orphan": false, "license_record": { "copyright_holders": [ "" ], ...
"2021" }, "tags": [ "Gambar", "Respon", "Teologi Proses", "Tuhan" ], "preprint_doi_created": "2021-07-19T07:42:12.695116", "date_withdrawn": null, "curr...
carvalhomb/tsmells
lib/Cheetah/src/Parser.py
Python
gpl-2.0
101,244
0.006568
#!/usr/bin/env python # $Id: Parser.py,v 1.135 2007/11/16 18:26:01 tavis_rudd Exp $ """Parser classes for Cheetah's Compiler Classes: ParseError( Exception ) _LowLevelParser( Cheetah.SourceReader.SourceReader ), basically a lexer _HighLevelParser( _LowLevelParser ) Parser === _HighLevelParser (an alias) Meta-...
start + r').*?' + r'(?:' + end + r')', re.DOTALL) for start, end in tripleQuotedStringPairs.items(): tripleQuotedStringREs[start] = makeTripleQuoteRe(start, end) WS
= r'[ \f\t]*' EOL = r'\r\n|\n|\r' EOLZ = EOL + r'|\Z' escCharLookBehind = nongroup(r'(?<=\A)',r'(?<!\\)') nameCharLookAhead = r'(?=[A-Za-z_])' identRE=re.compile(r'[a-zA-Z_][a-zA-Z_0-9]*') EOLre=re.compile(r'(?:\r\n|\r|\n)') specialVarRE=re.compile(r'([a-zA-z_]+)@') # for matching specialVar comments # e.g. ##author...
Diaoul/subliminal
subliminal/__init__.py
Python
mit
818
0.002445
# -*- coding: utf-8 -*- __title__ = 'subliminal' __version__ = '2.1.0' __short_version__ = '.'.join(__version__.split('.')[:2]) __author__ = 'Antoine Bertin' __license__ = 'MIT' __copyright__ = 'Copyright 2016, Antoine Bertin' import logging from .core import (AsyncProviderPool, ProviderPool, check_video, download_be...
import Error, ProviderError from .extensions import provider_manager, refiner_manager from .providers import Provider from .score import compute_score, get_scores from .subtitle import SUBTITLE_EXTENSIONS, Subtitle from .video import VIDEO_EXTENSIONS, Episod
e, Movie, Video logging.getLogger(__name__).addHandler(logging.NullHandler())
Sheeo/pygit2
setup.py
Python
gpl-2.0
6,812
0.000441
# -*- coding: utf-8 -*- # coding: UTF-8 # # Copyright 2010-2015 The pygit2 contributors # # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License, version 2, # as published by the Free Software Foundation. # # In addition to the permissions in the GNU G...
s': [ Extension('_pygit2', pygit2_exts, libraries=['git2'], include_dirs=[libgit2_include], library_dirs=[libgit2_lib]), # FFI is added in the build step ], } if cffi_major_version == 0: extra_args['ext_modules'].append(ffi.verifier.get_extension()) else: ...
name='pygit2', description='Python bindings for libgit2.', keywords='git', version=__version__, url='http://github.com/libgit2/pygit2', classifiers=classifiers, license='GPLv2 with linking exception', maintainer=u('J. David Ibáñez'), maintainer_email='jdavid.ibp@gmail.com...
rohitranjan1991/home-assistant
tests/components/cpuspeed/test_config_flow.py
Python
mit
2,642
0
"""Tests for the CPU Speed config flow.""" from unittest.mock import AsyncMock, MagicMock from homeassistant.components.cpuspeed.const import DOMAIN from homeassistant.config_entries import SOURCE_USER fro
m homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import ( RESULT_TYPE_ABORT, RESULT_TYPE_CREATE_ENTRY, RESULT_TYPE_FORM, ) from tests.common import MockConfigEntry async def test_full_user_flow( hass: HomeAssistant, mock_cpuinfo_config_flow: MagicMock, mock_setup_e...
"""Test the full user configuration flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result.get("type") == RESULT_TYPE_FORM assert result.get("step_id") == SOURCE_USER assert "flow_id" in result result2 = await hass.config...
ryandoherty/RaceCapture_App
autosportlabs/uix/gauge/bargraphgauge.py
Python
gpl-3.0
1,453
0.015141
import kivy kivy.require('1.9.1') from kivy.uix.anchorlayout import AnchorLayout from kivy.uix.relativelayout import RelativeLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.boxlayout import BoxLayout from kivy.uix.stencilview import StencilView from fieldlabel import FieldLabel from kivy.properties im...
phics import Color, Rectangle from utils import * from random import random as r Builder.load_file('autosportlabs/uix/gauge/bargraphgauge.kv') class BarGraphGauge(AnchorLayo
ut): minval = NumericProperty(0) maxval = NumericProperty(100) value = NumericProperty(0) color = ListProperty([1, 1, 1, 0.5]) def __init__(self, **kwargs): super(BarGraphGauge, self).__init__(**kwargs) def on_minval(self, instance, value): self._refresh...
SoftwearDevelopment/spynl
spynl/main/serial/cli.py
Python
mit
1,287
0.000777
"""Command-line tool to test the (de)serialisation live.""" from sys import stdin, stdout from argparse import ArgumentParser from spynl.main.serial import negotiate_content_type, loads, dumps def main(): """main function for converting between formats""" parser = ArgumentParser(description='Convert between...
parser.add_argument( '--output-type', metavar='TYPE', dest='output_type', default='json', help='output type e.g. JSON or XML etc.', ) parser
.add_argument( '--input-type', metavar='TYPE', dest='input_type', default=None, help='suggested input type. See --output-type', ) args = parser.parse_args() request = stdin.read() request = loads(request, negotiate_content_type(request, args.input_type)) res...
all-of-us/raw-data-repository
rdr_service/lib_fhir/fhirclient_4_0_0/models/medicationstatement.py
Python
bsd-3-clause
8,384
0.005725
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/MedicationStatement) on 2019-05-07. # 2019, SMART Health IT. from . import domainresource class MedicationStatement(domainresource.DomainResource): """ Record of medication being take...
scription bottle, or from a list of medications the patient, clinician or other par
ty maintains. The primary difference between a medication statement and a medication administration is that the medication administration has complete administration information and is based on actual administration information from the person who administered the medication. A medication stat...
kevintumbo/Checkpoint2_Bucketlist
tests/base_test.py
Python
mit
2,589
0.011587
from bucketlist import create_app, db from bucketlist.models import User, Bucketlist, Item import json import unittest class BaseTestCase(unittest.TestCase): def setUp(self): """ this function creates the base test""" self.app = create_app(config_name="development") self.client = self.ap...
ata.decode())['access_token'] self.my_header = dict(Authorization="Bearer " + access_token) # create bucketlist bucket_response = self.client().post('/api/v1.0/bucketlists/',
data=self.bucketlists3, headers=self.my_header) def tearDown(self): """ removes resources once tests have run """ with self.app.app_context(): db.session.remove() db.drop_all()
kenorb/BitTorrent
twisted/web/test/test_xml.py
Python
gpl-3.0
23,878
0.003015
# -*- test-case-name: twisted.web.test.test_xml -*- # # Copyright (c) 2001-2004 Twisted Matrix Laboratories. # See LICENSE for details. # """Some fairly inadequate testcases for Twisted XML support.""" from __future__ import nested_scopes from twisted.trial.unittest import TestCase from twisted.web import sux fro...
ms.connectionMade() ms.dataReceived(s) self.failUnlessEqual(len(ms.getTagStarts()),3) class MicroDOMTest(TestCase): def testCaseSensitiveSoonCloser(self): s
= """ <HTML><BODY> <P ALIGN="CENTER"> <A HREF="http://www.apache.org/"><IMG SRC="/icons/apache_pb.gif"></A> </P> <P> This is an insane set of text nodes that should NOT be gathered under the A tag above. ...
Fillll/reddit2telegram
reddit2telegram/channels/~inactive/comedynecrophilia/app.py
Python
mit
155
0.006452
#
encoding:utf-8 subreddit = 'comedynecrophilia' t_channel = '@comedynecrophilia' def send_post(submission, r2t): return r2t.send_simple(submission)
google-code-export/los-cocos
test/test_recorder.py
Python
bsd-3-clause
1,317
0.023538
from __future__ import division, print_function, unicode_literals # This code is so you can run the samples without installing the package import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__
), '..')) # # this test is not suitable for autotest because it uses a special clock # that clashes with the clock used to autotest. So no testinfo here. tags = "recorder" import cocos from cocos.director import director from cocos.actions import JumpTo, JumpBy from cocos.sprite import Sprite import pyglet class Tes...
e() self.sprite = Sprite( 'grossini.png', (x//5, y//3*2) ) self.add( self.sprite ) self.sprite.do( JumpTo( (x//5*4, 100), 100, 10, 6 ) ) self.sprite2 = Sprite( 'grossini.png', (x//5, y//3) ) self.add( self.sprite2 ) self.sprite2.do( JumpBy( (x//5*4, 100), 100, 10, 6 ) )...
abreen/socrates.py
filetypes/jflapfile.py
Python
gpl-2.0
1,386
0.002165
from filetypes.basefile import BaseFile from filetypes.plainfile import PlainFile from filetypes.plainfile import ReviewTest import filetypes class JFLAPReviewTest(ReviewTest): def __init__(self, dict_, file_type): super().__init__(dict_, file_type) def run(self, path): """A JFLAP review test ...
_cls(t, JFLAPFile.yaml_type)) def run_tests(self): results = [] for t in self.tests: result = t.run(self.path) if result: if type(result) is list:
for r in result: results.append(r) else: results.append(result) return results def __str__(self): return self.path + " (JFLAP file)"
qiyuangong/leetcode
python/006_ZigZag_Conversion.py
Python
mit
1,447
0.000691
class Solution(object): # def convert(self, s, numRows): # """ # :type s: str # :type numRows: int # :rtype: str # """ # ls = len(s) # if ls <= 1 or numRows == 1: # return s # temp_s = [] # for i in range(numRows): # tem...
# return result def convert(self, s, numRows): # https://leetcode.com/discuss/90908/easy-python-o-n-solution-94%25-with-explanations if numRows == 1: return s # calculate period p = 2 * (numRows - 1) result = [""] * numRow
s for i in xrange(len(s)): floor = i % p if floor >= p//2: floor = p - floor result[floor] += s[i] return "".join(result) if __name__ == '__main__': # begin s = Solution() print s.convert("PAYPALISHIRING", 3)
joelwilson/caniflymykite
geonames.py
Python
gpl-3.0
1,582
0.001264
import json import os import requests USERNAME = os.environ['GEONAMES_USER'] BASE_URL = 'http://api.geonames.org' def search(term, user=USERNAME): '''Returns a dict of results for a search to geonames.''' r = requests.get(BASE_URL + '/searchJSON', params={'q': term, ...
k else None def weather(lat, lon, user=USERNAME): '''Returns a dict of current weather conditions of the station closest to lat, lon. ''' r = requests.get(BASE_URL + '/findNearByWeatherJSON', params={'lat': lat, 'lng': lon, ...
eturn None def nearestplace(lat, lon, user=USERNAME): ''''Returns a dict of attributes of the closest geographical place.''' r = requests.get(BASE_URL + '/findNearbyPlaceNameJSON', params={'lat': lat, 'lng': lon, 'username': user, ...
jwhui/openthread
tools/otci/otci/command_handlers.py
Python
bsd-3-clause
9,542
0.001782
#!/usr/bin/env python3 # # Copyright (c) 2020, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # ...
timeout -= 1 for line in lines: output.append(line) if match_line(line, expect_line): done = True
break if not done: raise ExpectLineTimeoutError(expect_line) return output def __otcli_read_routine(self): while not self.__should_close.is_set(): try: line = self.__otcli.readline() except Exception: ...
h01ger/voctomix
voctocore/lib/controlserver.py
Python
mit
5,365
0
import logging from queue import Queue from gi.repository import GObject from lib.commands import ControlServerCommands from lib.tcpmulticonnection import TCPMultiConnection from lib.response import NotifyResponse class ControlServer(TCPMultiConnection): def __init__(self, pipeline): '''Initialize serve...
self.log.debug('on_loop called') if self.command_queue.empty(): self.log.debug('command_queue is empty again, ' 'stopping on_loop scheduling') return False
line, requestor = self.command_queue.get() words = line.split() if len(words) < 1: self.log.debug('command_queue is empty again, ' 'stopping on_loop scheduling') return True command = words[0] args = words[1:] self.log.info...
manojngb/Crazyfly_simple_lift
src/cfclient/utils/input/inputinterfaces/__init__.py
Python
gpl-2.0
3,515
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # || ____ _ __ # +------+ / __ )(_) /_______________ _____ ___ # | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ # +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ # || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ # # Copyright (C) 20...
program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. """ Find all the available input interfaces and try to initialize them. """ import os import glob import logging from ..inputreaderinterface import InputReaderInterface __author__ = 'Bi...
putInterface'] logger = logging.getLogger(__name__) found_interfaces = [os.path.splitext(os.path.basename(f))[0] for f in glob.glob(os.path.dirname(__file__) + "/[A-Za-z]*.py")] if len(found_interfaces) == 0: found_interfaces = [os.path.splitext(os.path.basename(f))[0] for ...
andreasplesch/QGIS-X3D-Processing
scripts/generate_X3D_Shape.py
Python
gpl-3.0
495
0.032323
##X3D=group ##X3D Shape node from Appearance and Geometry=name ##X3D_Geometry_file=file ##appearance=strin
g <Appearance><Material></Material></Appearance> ##output_X3D_Shape_file=output file out=open(output_X3D_Shape_file,'w'
) geofile=open(X3D_Geometry_file,'r') # no error checking, use elementtree later out.write( '<Shape>\n' ) out.write( appearance+'\n' ) for g in geofile: out.write(g) # just write incrementally since may be large out.write( '</Shape>\n') geofile.close() out.close()
khchine5/xl
lino_xl/lib/ledger/models.py
Python
bsd-2-clause
32,456
0.003143
# -*- coding: UTF-8 -*- # Copyright 2008-2018 Rumma & Ko Ltd # License: BSD (see file COPYING for details) """Database models for this plugin. """ from __future__ import unicode_literals, print_function import six from builtins import str import logging logger = logging.getLogger(__name__) import datetime from d...
try: return cls.objects.get(user=user) except cls.DoesNotExist: return cls(user=user) @dd.python_2_unicode_compatible class Journal(mixins.BabelNa
med, mixins.Sequenced, mixins.Referrable, PrintableType): class Meta: app_label = 'ledger' verbose_name = _("Journal") verbose_name_plural = _("Journals") trade_type = TradeTypes.field(blank=True) voucher_type = VoucherTypes.field() jou...
KMFleischer/PyEarthScience
Visualization/PyNGL/vectors_simple_PyNGL.py
Python
mit
3,506
0.042499
""" PyEarthScience: PyNGL vector example - vectors on map plot - rectilinear grid (lat/lon) 09.10.15 kmf """ import Ngl,Nio #-- define variables diri = "/Users/k204045/NCL/general/data/new_data/" #-- data directory fname = "rectilinear_grid_2D.nc" #-- data file name minval = 250. ...
CornerLatF = float(lat[0]) #-- left latitude value res.mpRightCornerLatF = float(lat[len(lat[:])-1])
#-- right latitude value res.mpGridSpacingF = 30 #-- map grid spacing res.mpPerimOn = True #-- turn on map perimeter res.vpXF = 0.1 #-- viewport x-position res.vpYF = 0.9...
rhd/meson
mesonbuild/modules/qt4.py
Python
apache-2.0
7,453
0.00161
# Copyright 2015 The Meson development team # 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 ...
tput': name + '.cpp', 'command': [self.rcc, '-o', '@OUTPUT@', '@INPUT@'], 'depend_files': qrc_deps} res_target = build.CustomTarget(name, state.subdir, rcc_kwargs) sources.append(res_target)
if len(ui_files) > 0: if not self.uic.found(): raise MesonException(err_msg.format('UIC', 'uic-qt4')) ui_kwargs = {'output': 'ui_@BASENAME@.h', 'arguments': ['-o', '@OUTPUT@', '@INPUT@']} ui_gen = build.Generator([self.uic], ui_kwargs) ...