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 |
|---|---|---|---|---|---|---|---|---|
luca-heltai/ePICURE | applications/lib/progress_bar.py | Python | gpl-2.0 | 1,682 | 0.030321 | from lib.font import *
import sys
import fcntl
import termios
import struct
class progress_bar(object):
def __init__(self, tot=100, lenght=10):
self.cp='/-\|'
self.bar_lenght = lenght
self.tot = tot
def startprogress(self, title):
"""Creates a progress bar 40 chars long on the console
and moves cursor ba... | "]" + chr(8) * (self.bar_lenght+1))
sys.stdout.flush()
def progress(self, x):
"""Sets progress bar to a certain percentage x.
Progress is given as whole percentage, i.e. 50% done
is given by x = 50"""
y = int(x)%4
z = int((x/float(self.tot))*self.bar_lenght | )
sys.stdout.write("#" * z + self.cp[y] +"-" * (self.bar_lenght-1 - z) + "] "+ bold(str(int(x))+"/"+str(self.tot)) + chr(8) * (self.bar_lenght+4+len(str(int(x)))+len(str(self.tot)) ))
sys.stdout.flush()
def endprogress(self):
"""End of progress bar;
Write full bar, then move to next lin... |
regmi/codenode-unr | codenode/external/jsonrpc/types.py | Python | bsd-3-clause | 1,860 | 0.013978 | def _types_gen(T):
yield T
if hasattr(T, 't'):
for l in T.t:
yield l
if hasattr(l, 't'):
for ll in _types_gen(l):
yield ll
class Type(type):
""" A rudimentary extension to `type` that provides polymorphic
types for run-time type checking of JSON data types. IE:
assert type... | = Type('Boolean', (object,), {}).I(bool).N('bit')
String = Type('String', (object,), {}).I(str, unicode).N('str')
Array = Type('Array', (object,), {}).I(list, set, tuple).N('arr')
Nil = Type('Nil', (obje | ct,), {}).I(type(None)).N('nil')
Any = Type('Any', (object,), {}).I(
Object, Number, Boolean, String, Array, Nil).N('any')
|
pwong-mapr/private-hue | apps/sqoop/src/sqoop/api/job.py | Python | apache-2.0 | 8,088 | 0.011375 | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... | ftware
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under th | e License.
try:
import json
except ImportError:
import simplejson as json
import logging
import socket
from django.http import HttpResponse
from django.utils.translation import ugettext as _
from sqoop import client, conf
from sqoop.client.exception import SqoopException
from decorators import get_job_or_excepti... |
Darkade/udlap | 6to/simplex.py | Python | apache-2.0 | 14,976 | 0.049195 | #!/usr/bin/env python
# -*- coding: latin-1 -*-
import sys
#################### <FUNCIONES> ####################################################################
##<Obtener el vector C>###################################################################################################
def GetVectorC(eq):
C=[]
j=... | #######################################################
##<Calcular las ecuaciones de transformacion>###################################################### | ######
def Ecuaciones_Trans(A,XB,ZC,entrada,salida) :
if wo == False :
print "Entra: " + str(entrada) + " Sale: " +str(salida) +"\nYij:"
else :
output.write("\n\nEntra: " + str(entrada) + " Sale: " +str(salida) +"\nYij:\n")
Yij=[]
##Calcular Y######
for i in range(l |
antoinecarme/pyaf | tests/artificial/transf_None/trend_LinearTrend/cycle_12/ar_/test_artificial_128_None_LinearTrend_12__20.py | Python | bsd-3-clause | 262 | 0.087786 | import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_art | ificial_dataset as art
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "LinearTrend", cycle_lengt | h = 12, transform = "None", sigma = 0.0, exog_count = 20, ar_order = 0); |
google/flight-lab | controller/common/net.py | Python | apache-2.0 | 1,062 | 0.00565 | # Copyright 2018 Flight Lab authors.
#
# 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, software
# distr | ibuted 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.
"""Library for network related helpers."""
import socket
def get_ip():
"""Ge... |
petercable/mi-dataset | mi/dataset/parser/test/test_fuelcell_eng_dcl.py | Python | bsd-2-clause | 9,992 | 0.001601 | #!/usr/bin/env python
"""
@package mi.dataset.parser.test
@file mi-dataset/mi/dataset/parser/test/test_fuelcell_eng_dcl.py
@author Chris Goodrich
@brief Test code for the fuelcell_eng_dcl parser
Release notes:
initial release
"""
__author__ = 'cgoodrich'
import os
from nose.plugins.attrib import attr
from mi.core... | }
def test_simple(self):
"""
Read | file and verify that all expected particles can be read.
Verify that the contents of the particles are correct.
This is the happy path.
"""
log.debug('===== START TEST SIMPLE =====')
num_particles_to_request = 25
num_expected_particles = 20
# Test the recovered... |
benadida/helios-server | helios_auth/auth_systems/github.py | Python | apache-2.0 | 2,315 | 0.015983 | """
Github Authentication
"""
import httplib2
from django.conf import settings
from django.core.mail import send_mail
from oauth2client.client import OAuth2WebServerFlow
from helios_auth import utils
# some parameters to indicate that status updating is not possible
STATUS_UPDATES = False
# display tweaks
LOGIN_ME... | 'name': '%s (%s)' % (user_id, user_name),
'info': {'email': user_email},
'token': {},
}
def do_logout(user):
return None
def update_status(token, message):
pass
def send_message(user_id, name, user_info, subject, body):
send_mail(
| subject,
body,
settings.SERVER_EMAIL,
["%s <%s>" % (user_id, user_info['email'])],
fail_silently=False,
)
def check_constraint(eligibility, user_info):
pass
#
# Election Creation
#
def can_create_election(user_id, user_info):
return True
|
DIRACGrid/VMDIRAC | VMDIRAC/Resources/Cloud/KeystoneClient.py | Python | gpl-3.0 | 9,771 | 0.007983 | """ KeystoneClient class encapsulates the work with the keystone service interface
"""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import requests
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.Utilities.Time import fromString, dateTime
__RC... | orce=True)
if not result['OK']:
return result
return S_OK()
def getToken(self, force=False):
"""Get the Keystone token
:param force: flag to force getting the token if even there | is one in the cache
:return: S_OK(token) or S_ERROR
"""
if self.token is not None and not force:
if self.expires and (self.expires - dateTime()).seconds > 300:
return S_OK(self.token)
if self.apiVersion == 2:
result = self.__getToken2()
else:
result = self.__getToken3()
... |
bwalks/pymemcache | pymemcache/test/test_client_hash.py | Python | apache-2.0 | 7,403 | 0 | from pymemcache.client.hash import HashClient
from pymemcache.client.base import Client, PooledClient
from pymemcache.exceptions import MemcacheError, MemcacheUnknownError
from pymemcache import pool
from .test_client import ClientTestMixin, MockSocket
import unittest
import pytest
import mock
import socket
class Te... | 'key1', b'key3'])
assert result == {}
def test_gets_many(self):
client = self.make_client(*[
[b'STORED\r\n', b'VALUE key3 0 6 1\r\nvalue2\r\nEND\r\n', ],
[b'STORED\r\n', b'VALUE key1 0 6 1\r\nvalue1\r\nEND\r\n', ],
])
def get_clients(key):
if key... | assert client.set(b'key1', b'value1', noreply=False) is True
assert client.set(b'key3', b'value2', noreply=False) is True
result = client.gets_many([b'key1', b'key3'])
assert (result ==
{b'key1': (b'value1', b'1'), b'key3': (b'value2', b'1')})
def test_no_servers_lef... |
bitmazk/django-people | people/south_migrations/0005_auto__add_field_persontranslation_roman_first_name__add_field_persontr.py | Python | mit | 15,072 | 0.007564 | # flake8: noqa
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'PersonTranslation.roman_first_name'
db.add_column('people_persontranslation',... | = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
| 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'orderi... |
Azulinho/sunflower-file-manager-with-tmsu-tagging-support | application/plugin_base/mount_manager_extension.py | Python | gpl-3.0 | 1,433 | 0.032798 | import gtk
class ExtensionFeatures:
SYSTEM_WIDE = 0
class MountManagerExtension:
"""Base class for mount manager extensions.
Mount manager has only one instance and is created on program startup.
Methods defined in this class are called automatically by the mount manager
so you need to implement them.
""... | er interface
self._container = gtk.VBox(False, 5)
self._controls = gtk.HBox(False, 5)
separator = gtk.HSeparator()
# pack interface
self._container.pack_end(separator, False, False, 0)
self._container.pack_end(self._controls, False, False, 0)
def can_handle( | self, uri):
"""Returns boolean denoting if specified URI can be handled by this extension"""
return False
def get_container(self):
"""Return container widget"""
return self._container
def get_information(self):
"""Returns information about extension"""
icon = None
name = None
return icon, name
de... |
DeltaEpsilon-HackFMI2/FMICalendar-REST | venv/lib/python2.7/site-packages/rest_framework/mixins.py | Python | mit | 6,556 | 0.000915 | """
Basic building blocks for generic class based views.
We don't bind behaviour to http method handlers yet,
which allows mixin classes to be composed in interesting ways.
"""
from __future__ import unicode_literals
from django.http import Http404
from rest_framework import status
from rest_framework.response import... | tatus=success_status_code)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) |
def partial_update(self, request, *args, **kwargs):
kwargs['partial'] = True
return self.update(request, *args, **kwargs)
def get_object_or_none(self):
try:
return self.get_object()
except Http404:
if self.request.method == 'PUT':
# For ... |
dakot/vilay-detect | vilay/detectors/FaceDetector.py | Python | gpl-3.0 | 1,782 | 0.014029 | import cv2
import numpy as np
import os
from vilay.core.Descriptor import MediaTime, Shape
from vilay.detectors.IDetector import IDetector
from vilay.core.DescriptionScheme import DescriptionScheme
class FaceDetector(IDetector):
def getName(self):
return "Face Detector"
def initialize(self):... |
for mediaTime in mediaTimes:
for frameIdx in range(mediaTime.startTime, mediaTime.startTime + mediaTime.duration):
actFrame = film.getFrame(frameIdx)
# preprocessing
actFrame = cv2.cvtColor(actFrame, cv2.cv.CV_BGR2GRAY)
... | s = self.cascade.detectMultiScale(actFrame, 1.2, 3, 0, (5,5))
# create ds and add time and shape descriptor
for faceIdx in range(len(faces)):
[x,y,width,height] = faces[faceIdx,:]
ds = DescriptionScheme('RTI',... |
SickGear/SickGear | tests/common_tests.py | Python | gpl-3.0 | 235,694 | 0.007259 | import unittest
import warnings
warnings.filterwarnings('ignore', module=r'.*fuz.*', message='.*Sequence.*')
import sys
import os.path
sys.path.insert(1, os.path.abspath('..'))
from sickbeard import common
from sickbeard.common import Quality, WantedQualities
from sickbeard.name_parser.parser import NameParser
from s... | common.Quality.combine | Qualities(*show_quality)
wd = common.WantedQualities()
_ = wd.get_wantedlist(sq, False, common.Quality.NONE, common.UNAIRED, manual=True)
for w, v in iteritems(wd):
if w == sq:
for u, o in sorted(iteritems(v)):
self.assertEq... |
zentralopensource/zentral | zentral/core/events/utils.py | Python | apache-2.0 | 851 | 0 | def decode_args(s, delimiter="|", escapechar="\\"):
args = []
escaping = False
current_arg = ""
for c in s:
if escaping:
current_arg += c
escaping = False
elif c == escapechar:
escaping = True
elif c == delimiter:
args.append(curren... | \\"):
encoded_args = ""
for idx, arg in enumerate(args):
if idx > 0:
encoded_args += delimiter
if not isinstance(arg, str):
arg = str(arg)
| for c in arg:
if c == delimiter or c == escapechar:
encoded_args += escapechar
encoded_args += c
return encoded_args
|
i-tek/inet_ncs | simulations/analysis_tools/python/omnet_vector.py | Python | gpl-3.0 | 3,886 | 0.008492 | #
# Python module to parse OMNeT++ vector files
#
# Currently only suitable for small vector files since
# everything is loaded into RAM
#
# Authors: Florian Kauer <florian.kauer@tuhh.de>
#
# Copyright (c) 2015, Institute of Telematics, Hamburg University of Technology
# All rights reserved.
#
# Redistribution and use ... | lf.dataTime[vector] = []
self.dataValues[vector] = []
time = float(m.group(3))
self.dataTime[vector].append(time)
self.maxtime = max(self.maxtime,tim | e)
self.dataValues[vector].append(float(m.group(4)))
else:
# vector 7 Net802154.host[0].ipApp[0] referenceChangeStat:vector ETV
m = re.search("vector *([0-9]*) *([^ ]*) *(.*):vector",line)
if m:
number = int(m.group(1))
... |
quanticle/GorillaBot | gorillabot/plugins/settings.py | Python | mit | 5,087 | 0.009043 | # Copyright (c) 2013-2016 Molly White
#
# 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, publish,
# di... | figuration(m.bot.configuration)
m.bo | t.logger.info(
'"{0}" set to "{1}" in {2} by {3}.'.format(setting, value, chan, m.sender))
m.bot.private_message(m.location, '"{0}" set to "{1}" in {2}.'.format(setting, value, chan))
@admin()
def unset(m):
"""Unset a given setting."""
#- !unset setting [#channel]
#-
#- ```irc... |
ilastik/ilastik-0.5 | ilastik/modules/unsupervised_decomposition/core/testModule.py | Python | bsd-2-clause | 11,269 | 0.011625 | from PyQt4 import QtCore
import sys
from ilastik.core.projectClass import Project
from ilastik.core.testThread import TestThread
from ilastik.modules.unsupervised_decomposition.core.unsupervisedMgr import UnsupervisedDecompositionModuleMgr
from ilastik.modules.unsupervised_decomposition.core.algorithms.unsupervisedDeco... |
if unsupervisedMethod is None:
self.unsupervisedMethod = self.dataMgr.module["Unsupervised_Decomposition"].unsupervisedMethod |
else:
self.unsupervisedMethod = self.dataMgr.module["Unsupervised_Decomposition"].unsupervisedMethod = unsupervisedMethod
if numComponents is not None:
self.unsupervisedMethod.setNumberOfComponents(numComponents)
self.numIterations = numComponents
else:
... |
letops/django-sendgrid-parse | django_sendgrid_parse/__init__.py | Python | mit | 139 | 0 | from django | .utils.translation import ugettext_lazy as _ugl
default_app_config = 'django_sendgrid_parse.apps.Djang | oSendgridParseAppConfig'
|
kayhayen/Nuitka | nuitka/codegen/LineNumberCodes.py | Python | apache-2.0 | 2,550 | 0.000392 | # Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... | 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.
#
""" Generate code that updates the so... |
def getCurrentLineNumberCode(context):
frame_handle = context.getFrameHandle()
if frame_handle is None:
return ""
else:
source_ref = context.getCurrentSourceCodeReference()
if source_ref.isInternal():
return ""
else:
return str(source_ref.getLineNum... |
edusegzy/pychemqt | lib/reaction.py | Python | gpl-3.0 | 9,477 | 0.001478 | #!/usr/bin/python
# -*- coding: utf-8 -*-
###############################################################################
# Module to define chemical reaction functionality
###############################################################################
from math import exp, log
import sqlite3
from numpy import pol... | "formula": False,
"conversion": None,
"keq": None}
kwargsValue = ("Hr",)
kwargsList = ("tipo", "fase", "key", "base")
kwargsCheck = ("customHr", "formula")
calculateValue = ("DeltaP", "DeltaP_f", "DeltaP_ac", "DeltaP_h",
"DeltaP_v", "DeltaP_100ft", ... | ate("pychemqt", "Equilibrium"),
QApplication.translate("pychemqt", "Kinetic"),
QApplication.translate("pychemqt", "Catalitic")]
TEXT_PHASE = [QApplication.translate("pychemqt", "Global"),
QApplication.translate("pychemqt", "Liquid"),
QApplication... |
nive/nive | nive/extensions/path.py | Python | gpl-3.0 | 8,830 | 0.008041 |
import unicodedata
import re
class PathExtension:
"""
Enables readable url path names instead of ids for object traversal.
Names are stored as meta.pool_filename and generated from
title by default. Automatic generation can be disabled by setting
*meta.customfilename* to False for each object.... | ------
def __getitem__(self, id):
"""
Traversal lookup based on object.pool_filename and object.id. Trailing extensions
are ignored.
`file` is a reserved name and used in the current object to map file downloads.
| """
if id == "file":
raise KeyError(id)
if self.extension is None:
id = id.split(".")
if len(id)>2:
id = (".").join(id[:-1])
else:
id = id[0]
try:
id = int(id)
except:
name = ... |
nijinashok/sos | sos/plugins/dracut.py | Python | gpl-2.0 | 862 | 0 | # Copyright (C) 2016 Red Hat, Inc., Bryn M. Reeves <bmr@redhat.com>
# This file is part of the sos project: https://github.com/sosreport/sos
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# version 2 of the GNU General... | t(Plugin, RedHatPlugin):
""" Dracut initramfs generator """
plugin_name = "dracut"
packages = ("dracut",)
| def setup(self):
self.add_copy_spec([
"/etc/dracut.conf",
"/etc/dracut.conf.d"
])
self.add_cmd_output([
"dracut --list-modules",
"dracut --print-cmdline"
])
# vim: set et ts=4 sw=4 :
|
cloudify-cosmo/cloudify-gcp-plugin | cloudify_gcp/admin/__init__.py | Python | apache-2.0 | 1,945 | 0 | # #######
# Copyright (c) 2018-2020 Cloudify Platform Ltd. 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... | RESOURCES_DISCOVERY,
api_version=constants.API_V1):
super(CloudResourcesBase, self).__init__(
config,
logger,
scope,
discovery,
api_version)
def get_credentials(self, scope):
# check
# run: gcloud beta | auth application-default login
# look to ~/.config/gcloud/application_default_credentials.json
credentials = GoogleCredentials(
access_token=None,
client_id=self.auth['client_id'],
client_secret=self.auth['client_secret'],
refresh_token=self.auth['refresh_... |
anhstudios/swganh | data/scripts/templates/object/tangible/ship/components/armor/shared_arm_reward_alderaan_elite.py | Python | mit | 494 | 0.044534 | #### N | OTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/components/armor/shared_arm_reward_alderaan_elite.iff"
result.attrib... | _elite")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
AmatanHead/ardrone-autopilot | nodes_opencv/frame.py | Python | mit | 1,941 | 0.00103 | #!/usr/bin/env python
#
# This code is a part of `ardrone_autopilot` project
# which is distributed under the MIT license.
# See `LICENSE` file for details.
#
"""
This node is based on `base.py`. See there a documentation.
Inputs
------
* in/image -- main picture stream.
Outputs
-------
* out/image -- result imag... | kwargs)
def on_image(self, img):
if self.info is None:
return
self.camera_model.fromCameraInfo(self.info)
# self.camera_model.rectifyImage(img, img)
self.tf.waitForTransform('ardrone/odom',
'ardrone/ardrone_base_frontcam',
... | ,
rospy.Duration(3))
trans, rot = self.tf.lookupTransform('ardrone/odom',
'ardrone/ardrone_base_frontcam',
rospy.Time(0))
rot_matrix = np.array(quaternion_matrix(rot))
fo... |
xhochy/arrow | python/pyarrow/tests/test_compute.py | Python | apache-2.0 | 34,188 | 0 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | le registered functions
for name in pc.list_functions():
func = pc.get_function(name)
reconstructed = pickle.loads(pickle.dumps(func))
assert type(reconstructed) is type(func)
assert reconstructed.name == func.name
assert reconstructed.arity == func.arity
assert recon... | automatic) of registered functions
for name in pc.list_functions():
func = getattr(pc, name)
reconstructed = pickle.loads(pickle.dumps(func))
assert reconstructed is func
def test_function_attributes():
# Sanity check attributes of registered functions
for name in pc.list_functions... |
mapbox/mapbox-sdk-py | tests/test_datasets.py | Python | mit | 8,145 | 0.000859 | import base64
import json
import responses
from mapbox.services.datasets import Datasets
username = 'testuser'
access_token = 'pk.{0}.test'.format(
base64.b64encode(b'{"u":"testuser"}').decode('utf-8'))
def test_class_attrs():
"""Get expected class attr values"""
serv = Datasets()
assert serv.api_... | taset_list_features():
"""Features retrieval work"""
responses.add(
responses.GET,
'https://api.mapbox.com/datasets/v1/{0}/{1}/features?access_token={2}'.format(
username, 'test', access_token),
match_querystring=True,
body=json.dumps({'type': 'FeatureCollection'}),
... | tatus_code == 200
assert response.json()['type'] == 'FeatureCollection'
@responses.activate
def test_dataset_list_features_reverse():
"""Features retrieval in reverse works"""
responses.add(
responses.GET,
'https://api.mapbox.com/datasets/v1/{0}/{1}/features?access_token={2}&reverse=true'... |
neynt/tsundiary | tsundiary/jinja_env.py | Python | mit | 1,603 | 0.00815 | # encoding=utf-8
from tsundiary import app
app.jinja_env.globals.update(theme_nicename = {
'classic': 'Classic Orange',
'tsun-chan': 'Classic Orange w/ Tsundiary-chan',
'minimal': 'Minimal Black/Grey',
'misato-tachibana': 'Misato Tachibana',
'rei-ayanami': 'Rei Ayanami',
'rei-ayanami-2': 'Rei A... | o Sakura',
'colorful': 'Based on favorite color'
})
app.jinja_env.global | s.update(themes = ['classic', 'tsun-chan', 'minimal', 'misato-tachibana', 'rei-ayanami', 'rei-ayanami-2', 'saya', 'yuno', 'colorful'])
app.jinja_env.globals.update(theme_creds = {
'tsun-chan': 'Artist: <span title="<3">bdgtard</span>',
'misato-tachibana': 'Misato Tachibana source: Nichijou OP1.',
'rei-ayan... |
vasily-v-ryabov/pywinauto | pywinauto/unittests/test_win32functions.py | Python | bsd-3-clause | 5,560 | 0.00054 | # GUI Application automation and testing library
# Copyright (C) 2006-2018 Mark Mc Mahon and Contributors
# https://github.com/pywinauto/pywinauto/graphs/contributors
# http://pywinauto.readthedocs.io/en/latest/credits.html
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or with... | assertEqual(1, MakeLong(0, 1))
def testMakeLong_highone(self):
"Make sure MakeLong() function works with high word == 1"
self.assertEqual(0x10000, MakeLong(1, 0))
def testM | akeLong_highbig(self):
"Make sure MakeLong() function works with big numder in high word"
self.assertEqual(0xffff0000, MakeLong(0xffff, 0))
def testMakeLong_lowbig(self):
"Make sure MakeLong() function works with big numder in low word"
self.assertEqual(0xffff, MakeLong(0, 0xf... |
abbgrade/wok_hooks | wok_hooks/hook_distribute.py | Python | mit | 9,715 | 0.001029 | import logging
import os
from ftplib import FTP as FTPClient
from paramiko import SFTPClient, Transport as SFTPTransport
ALLOWED_BACKEND_TYPES = ['ftp', 'sftp']
DEFAULT_BACKEND_TYPE = 'ftp'
from wok_hooks.misc import Configuration as _Configuration
class Configuration(_Configuration):
def __init__(self, path, ... | sftp config.')
if some_changes:
self.config.save()
# cast config types
self.config['sftp_port'] = int(self.config['sftp_port'])
def _init_session(self):
self.connect()
def connect(self):
self._authenticate()
self.state = sel | f.STATE_CONNECTED
def _authenticate(self):
self._transport = SFTPTransport((self.config['sftp_host'],
self.config['sftp_port']))
self._transport.connect(username=self.config['sftp_user'],
password=self.config['sftp_password'])... |
sernst/cauldron | cauldron/test/session/test_session_reloading.py | Python | mit | 4,115 | 0 | from datetime import datetime
from email.mime import text as mime_text
from unittest.mock import MagicMock
from unittest.mock import Mock
from unittest.mock import patch
import cauldron as cd
from cauldron.session import reloading
from cauldron.test import support
from cauldron.test.support import scaffolds
from cauld... | , 0))
self.assertEqual(1, reload.call_count)
@patch('cauldron.session.reloading.os.path')
@patch('cauldron.session.reloading.importlib.reload')
def test_do_reload_skip(self, reload: MagicMock, os_path: MagicMock):
"""
Should skip reloading the specified module because it hasn't been... | = 0
self.assertFalse(reloading.do_reload(target, 10))
self.assertEqual(0, reload.call_count)
def test_reload_children_module(self):
"""Should abort as False for a module that has no children."""
target = Mock()
reloading.reload_children(target, 10)
|
Xycl/plugin.image.mypicsdb | resources/lib/googlemaps.py | Python | gpl-2.0 | 6,409 | 0.021688 | #!/usr/bin/python
# -*- coding: utf8 -*-
"""
Copyright (C) 2012 Xycl
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This pr... | , download it now...
try:
#f=open(unicode(mapfile, 'utf-8'),"wb")
f=open(common.smart_unicode(mapfile), "wb")
exc | ept:
try:
f=open(common.smart_utf8(mapfile), "wb")
except:
print_exc()
#print "GEO Exception: "+mapfile
for i in range(1+(filesize/10)):
f.write(urlfile.read(10))
label.setLabel(common.get... |
buztard/mxpy | examples/test-item-view.py | Python | lgpl-2.1 | 1,682 | 0.002973 | from random import randint
import gobject
import clutter
import mxpy as mx
sort_set = False
filter_set = False
def sort_func(model, a, b, data):
return int(a.to_hls()[0] - b.to_hls()[0])
def filter_func(model, iter, data):
color = iter.get(0)[0]
h = color.to_hls()[0]
return (h > 90 and h < 180)
def ... | iew)
model = clutter.ListModel(clutter.Col | or, "color", float, "size")
for i in range(360):
color = clutter.color_from_hls(randint(0, 255), 0.6, 0.6)
color.alpha = 0xff
model.append(0, color, 1, 32.0)
view.set_model(model)
view.set_item_type(clutter.Rectangle)
view.add_attribute("color", 0)
view.add_attribute("width... |
ck1125/sikuli | sikuli-script/src/main/python/sikuli/VDict.py | Python | mit | 3,120 | 0.030128 | # Copyright 2010-2011, Sikuli.org
# Released under the MIT License.
from org.sikuli.script import VDictProxy
import java.io.File
##
# VDict implements a visual dictionary that has Python's conventional dict
# interfaces.
#
# A visual dictionary is a data type for storing key-value pairs using
# images as keys. Using... | item__(self, key):
self.erase(key)
del self._keys[key]
##
# Returns a list of the keys in this visual dictionary.
#
def keys(self):
return self._keys.keys()
##
# Returns the value to which the specified key is exactly matched in
# this visual dictionary.
#
def get_exact(s... | ctionary with the given similarity and the given maximum
# number of return items.
# @param similarity the similarity for matching.
# @param n maximum number of return items.
#
def get(self, key, similarity=_DEFAULT_SIMILARITY, n=_DEFAULT_GET_ITEM_N):
if key == None: return None
return self.... |
bd-j/hmc | hmc.py | Python | gpl-2.0 | 15,392 | 0.001559 | import numpy as np
import matplotlib.pyplot as pl
class BasicHMC(object):
def __init__(self, model=None, verbose=True):
"""A basic HMC sampling object.
:params model:
An object with the following methods:
* lnprob(theta)
* lnprob_grad(theta)
* (opt... | one)
The stepsize for the leapfrog integrator. Scalar float or ndarray
of shape (ndim,). If `None`, a scalar value will be crudely
estimated.
:param mass_matrix: (optional, default: None)
"Masses" in each dimension used to rescale the momentum vectors in
... | or PDF. If `None` all masses will be
assumed 1. Otherwise can be ndarray of shape (ndim,) for a
diagonal covariance matrix or (ndim, ndim), in which case it must
be positive semi-definite.
:param length:
Number of leapfrog steps to take in each trajectory. Inte... |
fcecin/infinitum | contrib/devtools/symbol-check.py | Python | mit | 6,197 | 0.011457 | #!/usr/bin/python2
# Copyright (c) 2014 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
A script to check that the (Linux) executables produced by gitian only contain
allowed gcc, glibc and libstdc++ ve... | cess.PIPE)
def __call__(self, mangled):
self.proc.stdin.write(mangled + b'\n')
self.proc.stdin.flush()
return self.proc.stdout.readline().rstrip()
def close(self):
self.proc.stdin.close()
self.proc.stdout.close()
self.proc.wait()
def read_symbols(executabl | e, imports=True):
'''
Parse an ELF executable and return a list of (symbol,version) tuples
for dynamic, imported symbols.
'''
p = subprocess.Popen([READELF_CMD, '--dyn-syms', '-W', executable], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
(stdout, stderr) = p.communicat... |
jaseg/python-prompt-toolkit | prompt_toolkit/keys.py | Python | bsd-3-clause | 2,546 | 0.007855 | from __future__ import unicode_literals
__all__ = (
'Key',
'Keys',
)
class Key(object):
def __init__(self, name):
#: Descriptive way of writing keys in configuration files. e.g. <C-A>
#: for ``Control-A``.
self.name = name
def __repr__(self):
return '%s(%r)' % (self.... | S = Key('<C-S>')
ControlT = Key('<C-T>')
ControlU = Key('<C-U>')
ControlV = Key('<C-V>')
ControlW = Key('<C-W>')
ControlX = Key('<C-X>')
ControlY = Key('<C-Y>')
ControlZ = Key('<C-Z>' | )
ControlSpace = Key('<C-Space>')
ControlBackslash = Key('<C-Backslash>')
ControlSquareClose = Key('<C-SquareClose>')
ControlCircumflex = Key('<C-Circumflex>')
ControlUnderscore = Key('<C-Underscore>')
ControlLeft = Key('<C-Left>')
ControlRight = Key('<C-Right>')
... |
meshy/django-conman | tests/routes/test_urls.py | Python | bsd-2-clause | 1,649 | 0.000606 | from django.core.urlresolvers import resolve, Resolver404
from django.test import TestCase
from conman.routes import views
class RouteRouterViewTest(TestCase):
"""Test the route_router view."""
def assert_url_uses_router(self, url):
"""Check a url resolves to the route_router view."""
resolve... | est_child_url(self):
"""A child url is resolved using views.route_router."""
self.assert_url_uses_router('/slug/')
def test_nested_child_url(sel | f):
"""A nested child url is resolved using views.route_router."""
self.assert_url_uses_router('/foo/bar/')
def test_numerical_url(self):
"""A numeric url is resolved using views.route_router."""
self.assert_url_uses_router('/meanings/42/')
def test_without_trailing_slash(self)... |
levithomason/neo | apps/neo_graph_test/urls.py | Python | mit | 388 | 0.002577 | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
| url(r'^', 'apps.neo_graph_test.views.create_graph', name='create_graph'),
url(r'^', include('apps.citizens.urls')),
url(r'^admin/', | include(admin.site.urls)),
)
|
utopianf/maobot_php | imgdl.py | Python | mit | 7,849 | 0.010957 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import re
import os
from urllib.request import urlretrieve
from urllib.request import urlopen
from urllib.request import build_opener, HTTPCookieProcessor
from urllib.parse import urlencode, quote
from http.cookiejar import CookieJar
from configparser import SafeCo... | = "thumb_pix"+imageLoc.split("/")[-1]
thumbnail(loc, thumb)
regImg(loc, orig_url, "./images/thumbnail/"+thumb, type)
print(thumb_lDir+thumb)
elif pix_.match(orig_url):
imageLocs = []
reg = re.compile("https?:\/\/www.pixiv.net\/member_illust.php\?mode=manga_big\&il... | age_id = int(reg.match(orig_url).group(1))
page = int(reg.match(orig_url).group(2))
api = AppPixivAPI()
api.login(pixiuser, pixipass)
json_result = api.illust_detail(image_id, req_auth=True)
imageLocs.append(json_result.illust.meta_pages[page].image_urls.original)
for ima... |
szecsi/Gears | GearsPy/Project/Components/Composition/Min.py | Python | gpl-2.0 | 828 | 0.03744 | import Gears as gears
from .. import *
from ..Pif.Base import *
class Min(Base) :
def applyWithArgs(
self,
spass,
functionName,
*,
pif1 : 'First operand. (Pif.*)'
= Pif.Solid( color = 'white' ),
pif2 : 'Sec... | '_op2')
spass.setShaderFunction( name = functionName, src = self.glslEsc( '''
vec3 @<pattern>@ (vec2 x, float time){
| return min( @<pattern>@_op1(x), @<pattern>@_op2(x) );
}
''').format( pattern=functionName ) )
|
igemsoftware2017/USTC-Software-2017 | tests/core/plugins/bad_plugin/apps.py | Python | gpl-3.0 | 268 | 0 | from biohub.core.plugins import PluginConfig
class BadPluginConfig | (PluginConfig):
name = 'tests.core.plugins.bad_plugin'
title = 'My Plugin'
author = 'hsfzxjy'
description = 'This is my plugin.'
def ready(self):
raise ZeroDivi | sionError
|
jeff-alves/Tera | game/message/unused/S_PARTY_MEMBER_INTERVAL_POS_UPDATE.py | Python | mit | 246 | 0.012195 | from util.tipo | import tipo
class S_PART | Y_MEMBER_INTERVAL_POS_UPDATE(object):
def __init__(self, tracker, time, direction, opcode, data):
print(str(type(self)).split('.')[3]+'('+str(len(data))+'): '+ str(data.get_array_hex(1))[1:-1])
|
ACBL-Bridge/Bridge-Application | Home Files/LoginandSignupV10.py | Python | mit | 17,362 | 0.013708 | from tkinter import *
import mysql.connector as mysql
from MySQLdb import dbConnect
from HomeOOP import *
import datetime
from PIL import Image, ImageTk
class MainMenu(Frame):
def __init__(self, parent): #The very first screen of the web app
Frame.__init__(self, parent)
w, h = parent.winfo_screen... | Arial 14", command=self.myProfileScreen)
myProfileButton.pack()
quitButton = Button(top, text="Log Out", font="Arial 14", command=top.destroy).pack(side="bottom", padx=20)
#top.title(':D')
#top.geometry('250x200')
#get first name and last ... | irstname, lastname FROM playerinfo WHERE username = '%s' AND password = '%s'" % (entry_user.get(), entry_pass.get()))
for namerow in cur.fetchall(): # print all the first cell
fn = namerow[0] #store firstname
ln = namerow[1] #store lastname
rlb1 ... |
akrherz/iem | scripts/dbutil/rwis2archive.py | Python | mit | 5,737 | 0 | """
Copy RWIS data from iem database to its final resting home in 'rwis'
The RWIS data is partitioned by UTC | timestamp
Run at 0Z and 12Z, provided with a timestamp to process
"""
import d | atetime
import sys
import psycopg2.extras
from pyiem.util import get_dbconn, utc
def main(argv):
"""Go main"""
iemdb = get_dbconn("iem")
rwisdb = get_dbconn("rwis")
ts = utc(int(argv[1]), int(argv[2]), int(argv[3]))
ts2 = ts + datetime.timedelta(hours=24)
rcursor = rwisdb.cursor()
# Remo... |
urisimchoni/samba | third_party/waf/wafadmin/Scripting.py | Python | gpl-3.0 | 15,298 | 0.032684 | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2005 (ita)
"Module called for configuring, compiling and installing targets"
import os, sys, shutil, traceback, datetime, inspect, errno
import Utils, Configure, Build, Logs, Options, Environment, Task
from Logs import error, warn, info
from Constants import *
... | ptions.compile_targets = targets
def clean(bld):
'''removes the build files'''
try:
proj = Environment.Environment(Options.lockfile)
except IOError:
raise Utils.WafError('Nothing to clean (project not configured)')
bld.load_dirs(proj[SRCDIR], proj[BLDDIR])
bld.load_envs()
bld.is_install = 0 # False
# rea... | t_path)[0]])
try:
bld.clean()
finally:
bld.save()
def check_configured(bld):
if not Configure.autoconfig:
return bld
conf_cls = getattr(Utils.g_module, 'configure_context', Utils.Context)
bld_cls = getattr(Utils.g_module, 'build_context', Utils.Context)
def reconf(proj):
back = (Options.commands, Opti... |
seungkim11/election-2016 | python_streaming/yesterday_dump.py | Python | apache-2.0 | 1,289 | 0.006206 | import time
from pymongo import MongoClient
from datetime import datetime, timedelta
import json
from bson import Binary, Code
from bson.json_util import dumps
client = MongoClient('localhost', 27017)
db = client['election-2016']
def dumpData(yesterdayStr):
collectionName = 't' + yesterdayStr
cursor = db[... | tweets')
# dump only if data count is greater than 0
if count > 0:
file = open('out/' + yesterdayStr + '.j | son', 'w')
file.write('[')
i = 0
for document in cursor:
doc = dumps(document)
file.write(doc)
if (i != count - 1):
file.write(',\n')
else:
file.write('\n]')
i = i + 1
print('data for ' + yester... |
publysher/rdflib-django | src/rdflib_django/testsettings.py | Python | mit | 1,265 | 0.000791 | """
Settings for testing the application.
"""
import os
DEBUG = True
DJANGO_RDFLIB_DEVELOP = True
DB_PATH = os.path. | abspath(os.path.join(__file__, '..', '..', '..', 'rdflib_django.db'))
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': DB_PATH,
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
| }
}
SITE_ID = 1
STATIC_URL = '/static/'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'r... |
Kuniwak/vint | vint/ast/plugin/scope_plugin/redir_assignment_parser.py | Python | mit | 1,250 | 0.0024 | from vint.ast.traversing import traverse, register_traverser_extension
from vint.ast.parsing import Parser
from vint.ast.node_type import NodeType
REDIR_CONTENT = | 'VINT:redir_content'
class RedirAssignmentParser(object):
" | "" A class to make redir assignment parseable. """
def process(self, ast):
def enter_handler(node):
node_type = NodeType(node['type'])
if node_type is not NodeType.EXCMD:
return
is_redir_command = node['ea']['cmd'].get('name') == 'redir'
if ... |
bmcinnes/VCU-VIP-Nanoinformatics | NERD/CRF/CRF.py | Python | gpl-3.0 | 5,075 | 0.00532 | # Used for when precision or recall == 0 to supress warnings
def warn(*args, **kwargs):
pass
import warnings
warnings.warn = warn
import numpy as np
import sklearn_crfsuite
from sklearn.metrics import make_scorer, confusion_matrix
from sklearn_crfsuite import metrics
from sklearn_crfsuite.utils import flatten
from... | f1_scores": make_scorer(metrics.flat_f1_score, average='weighted', labels=labels),
"precision_scores": make_scorer(metrics.flat_precision_score, average='weighted', labels=labels),
"recall_scores": make_scorer(metrics.flat_recall_score, average='weighted', labels=labels),
}
scores = cross_valida... | return_train_score=False, n_jobs=-1)
f1_scores = scores['test_f1_scores']
precision_scores = scores['test_precision_scores']
recall_scores = scores['test_recall_scores']
for x in range(NUMBER_OF_FOLDS):
print("Fold number: ", x)
print("Precision: ", precision_scores[x])
print(... |
possatti/memoo | converter.py | Python | mit | 6,467 | 0.025472 | '''Biblioteca que contém as rotinas de coversão dos diferentes tipos
de máquinas.
Autor: Lucas Possatti
'''
import re
import collections
def mealy_to_moore(me):
'''Converte o parâmetro 'me' (que deve ser uma máquina Mealy) para
uma máquina de Moore, que é retornada.
'''
# Verifica se a máquina recebida, realemen... | puts[state]) == 1:
# Adiciona o estado, a lista de estados da nova máquina
moore_states.append(state)
# Pega a única saí | da desse estado.
output = state_outputs[state][0]
# Forma a tupla para a função de saída (out-fn).
out_fn.append([state, output])
# Caso o estado não tenha qualquer output (como por exemplo, se
# não houver qualquer transição com destino a ele).
else:
# Adiciona o estado, a lista de estados da nova má... |
kipe/enocean | enocean/protocol/tests/test_temperature_sensors.py | Python | mit | 1,616 | 0.005569 | # -*- encoding: utf-8 -*-
from __future__ import print_function, unicode_literals, division, absolute_import
from enocean.protocol.eep import EEP
eep = EEP()
# profiles = eep.
def test_first_range():
offset = -40
values = range(0x01, 0x0C)
for i in range(len(values)):
minimum = float(i * 10 + off... | file.find('value', {'shortcut': 'TMP'}).find('scale | ').find('max').text)
profile = eep.find_profile([], 0xA5, 0x02, 0x30)
assert -40 == float(profile.find('value', {'shortcut': 'TMP'}).find('scale').find('min').text)
assert +62.3 == float(profile.find('value', {'shortcut': 'TMP'}).find('scale').find('max').text)
|
adamnovak/hgvm-graph-bakeoff-evalutations | scripts/computeVariantsDistances.py | Python | mit | 67,700 | 0.005628 | #!/usr/bin/env python2.7
"""
Compare all sample graphs to baseline graphs (platvcf and g1kvcf).
depends on callVariants.py output directory structure. Can do:
1)kmer set (jaccard and recall)
2)corg overlap
"""
import argparse, sys, os, os.path, random, subprocess, shutil, itertools, glob
import doctest, re, json, col... | graph + ".index"
def compute_kmer_index(job, graph, options):
""" run vg index (if necessary) and vg compare on the input
vg indexes are just created in place, ie same dir as graph,
so need to have write permission there
"""
# Move to the appropriate working dire | ctory from wherever Toil dropped us
os.chdir(options.cwd)
out_index_path = index_path(graph, options)
do_index = options.overwrite or not os.path.exists(out_index_path)
index_opts = "-s -k {} -t {}".format(options.kmer, options.vg_cores)
|
grepme/CMPUT410Lab01 | virt_env/virt1/lib/python2.7/site-packages/PasteDeploy-1.5.2-py2.7.egg/paste/deploy/compat.py | Python | apache-2.0 | 961 | 0.007284 | # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
"""Python 2<->3 compatibility module"""
import sy | s
def print_(template, *args, **kwargs):
template = str(template)
if args:
template = template % args
elif kwargs:
template = template % kwargs
sys.stdout.writelines(template)
if sys.version_info < (3, 0):
basestring = basestring
from ConfigParser import ConfigParser
from ... |
basestring = str
from configparser import ConfigParser
from urllib.parse import unquote
iteritems = lambda d: d.items()
dictkeys = lambda d: list(d.keys())
def reraise(t, e, tb):
raise e.with_traceback(tb)
|
Hackers-To-Engineers/ghdata-sprint1team-2 | organizationHistory/pythonBlameHistoryTree.py | Python | mit | 12,918 | 0.014476 | #How to run this:
#Python libraries needed to run this file: Flask, Git Python, SQLAlchemy
#You will need to have Git installed, and it will need to be in your path.
#For example, on Windows you should be able to run a command like 'git pull' from the
#ordinary Windows command prompt and not just from Git Bash.
#You... | the browser tab.
#the output shows the commit number and date, the total lines of code and other files (for example, the readme)
#and the percentage written by each organization.
#expected output for ghdata should show only the spdx-tools organization (Matt is a member)
#Number of lines corresponds to | the lines written by Matt.
#You can see that earlier commits are lower on the page, and chronologically later ones appear higher up.
#An "error" I expect us to encounter when testing other repos:
#The way my sql query works right now, a user can be a member of multiple organizations.
#For a simple case of expected ou... |
spdx/tools-python | spdx/parsers/__init__.py | Python | apache-2.0 | 577 | 0 | # Copyright (c) 2014 Ahmed H. Ismail
# 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/l | icenses/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.
# S | ee the License for the specific language governing permissions and
# limitations under the License.
|
safl/wtty | wtty/iod.py | Python | apache-2.0 | 5,729 | 0.002095 | #!/usr/bin/env python
# -*- coding: ascii -*-
from subprocess import Popen, PIPE
import threading
import select
import logging
import fcntl
import time
import sys
import os
TTY_OPTS="-icrnl -onlcr -imaxbel -opost -isig -icanon -echo line 0 kill ^H min 100 time 2 brkint 115200"
READERS = []
WRITERS = []
SELECT_TO = 0.1... | write(line.strip())
logging.debug("dev_w.write -- DONE")
time | .sleep(0.1)
logging.debug("dev_w.write CR")
dev_w.write('\r')
logging.debug("dev_w.write CR -- DONE")
except:
logging.error("error(%s)" % str(sys.exc_info()))
def main(cfg, state):
"""Entry point for wtty-iod"""
... |
romanoved/nanomsg-python | setup.py | Python | mit | 2,912 | 0.003777 | from __future__ import division, absolute_import, print_function,\
unicode_literals
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup, Extension
from distutils.core import Extension
from distutils.errors import DistutilsError
from distutils.command.bui... | nfig
cpy_extension = Extension(str('_nanomsg_cpy'),
define_macros=[('WITH_NANOCONFIG', '1')],
sources=[str('_nanomsg_cpy/wrapper.c')],
libraries=[str('nanomsg'), str('nanoconfig')],
)
install_requires = []
try:
impo... | nstall_requires.append('importlib')
setup(
name='nanomsg',
version=__version__,
packages=[str('nanomsg'), str('_nanomsg_ctypes'), str('nanomsg_wrappers')],
ext_modules=[cpy_extension],
cmdclass = {'build_ext': skippable_build_ext},
install_requires=install_requires,
description='Python lib... |
LamCiuLoeng/budget | budget/model/__init__.py | Python | mit | 2,408 | 0.009551 | # -*- coding: utf-8 -*-
"""The application's model objects"""
from zope.sqlalchemy import ZopeTran | sactionExtension
from sqlalchemy.orm import scoped_session, sessionmaker
# from | sqlalchemy import MetaData
from sqlalchemy.ext.declarative import declarative_base
# Global session manager: DBSession() returns the Thread-local
# session object appropriate for the current web request.
maker = sessionmaker( autoflush = True, autocommit = False,
extension = ZopeTransactionExtensi... |
PyBossa/mnemosyne | mnemosyne/core.py | Python | agpl-3.0 | 1,728 | 0.001159 | # -*- coding: utf8 -*-
# This file is part of Mnemosyne.
#
# Copyright (C) 2013 Daniel Lombraña González
#
# Mnemosyne is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or... | ('MNEMOSY | NE_SETTINGS', silent=False)
if db_name:
app.config['SQLALCHEMY_DATABASE_URI'] = db_name
db.init_app(app)
app.register_blueprint(frontend)
return app
|
diefenbach/django-lfs | lfs/criteria/utils.py | Python | bsd-3-clause | 3,002 | 0.001666 | from django.contrib.contenttypes.models import ContentType
from lfs.core.utils import import_symbol
from lfs.criteria.models import Criterion
import logging
logger = logging.getLogger(__name__)
# DEPRECATED 0.8
def is_vali | d(request, object, product=None):
"""
Returns True if the given object is valid. | This is calculated via the
attached criteria.
Passed object is an object which can have criteria. At the moment these are
discounts, shipping/payment methods and shipping/payment prices.
"""
logger.info("Decprecated: lfs.criteria.utils.is_valid: this function is deprecated. Please use the Criteria... |
nhsengland/publish-o-matic | datasets/ccgois/load.py | Python | mit | 3,287 | 0.003651 | """
Load the CCGOIS datasets into a CKAN instance
"""
import dc
import json
import slugify
import ffs
def make_name_from_title(title):
# For some reason, we're finding duplicate names
name = slugify.slugify(title).lower()[:99]
if not name.startswith('ccgois-'):
name = u"ccgois-{}".format(name)
... | dc.Dataset.create_or_update(
name=metadata['name'],
title=metadata['title'],
state='active',
license_id='uk-ogl',
notes=metadata['description'],
origin='https://indicators.ic.nhs.uk/webview/',
tags=dc.tags(*metadata['keyword(s)'])... | ency'], ],
owner_org='hscic',
extras=[
dict(key='frequency', value=metadata.get('frequency', '')),
dict(key='coverage_start_date', value=metadata['coverage_start_date']),
dict(key='coverage_end_date', value=metadata['coverage_end_date']),
... |
SUSE/azure-sdk-for-python | azure-mgmt-notificationhubs/azure/mgmt/notificationhubs/models/namespace_create_or_update_parameters.py | Python | mit | 4,958 | 0.001412 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | None, service_bus_endpoint=None, subscription_id=None, scale_unit=None, enabled=None, critical=None, namespace_type=None):
super(NamespaceCreateOrUpdateParameters, self).__init__(location=location, tags=tags, sku=sku)
self.namespace_create_or_update_parameters_name = namespace_create_or_update_parameter... | ovisioning_state = provisioning_state
self.region = region
self.status = status
self.created_at = created_at
self.service_bus_endpoint = service_bus_endpoint
self.subscription_id = subscription_id
self.scale_unit = scale_unit
self.enabled = enabled
self.cr... |
fritzo/loom | loom/gridding.py | Python | bsd-3-clause | 3,080 | 0.000649 | # Copyright (c) 2014, Salesforce.com, Inc. All rights reserved.
# Copyright (c) 2015, Google, Inc.
#
# 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 copyright
... | n_d = float(min_d)
max_d = float(max_d)
lower_triangle = [
(x, y)
for x in center_heavy(0, 1, alpha_count)
for y in left_heavy(0, | 1, d_count)
if x + y < 1
]
alpha = lambda x: min_alpha * (max_alpha / min_alpha) ** x
d = lambda y: min_d + (max_d - min_d) * y
grid = [
{'alpha': alpha(x), 'd': d(y)}
for (x, y) in lower_triangle
]
return grid
|
isandlaTech/cohorte-demos | led/dump/led-demo-yun/cohorte/dist/cohorte-1.0.0-20141216.234517-57-python-distribution/repo/pelix/shell/core.py | Python | apache-2.0 | 48,234 | 0 | #!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
Pelix shell bundle.
Provides the basic command parsing and execution support to make a Pelix shell.
:author: Thomas Calmant
:copyright: Copyright 2014, isandlaTech
:license: Apache License 2.0
:version: 0.5.8
:status: Beta
..
Copyright 2014 isandlaTech
... | if column != nb_columns:
# Check if all lines have the same number of columns
| raise ValueError("Different sizes for header and lines "
"(line {0})".format(idx + 1))
# Prepare the head (centered text)
format_str = "{0}|".format(prefix)
for column, length in enumerate(lengths):
format_str += " {%d:^%d} |" ... |
poppy-project/pypot | pypot/sensor/__init__.py | Python | gpl-3.0 | 117 | 0 | from .de | pth import *
from .camera import *
from .contact import *
from .imag | efeature import *
from .arduino import *
|
pombredanne/https-git.fedorahosted.org-git-kobo | kobo/django/auth/krb5.py | Python | lgpl-2.1 | 1,587 | 0.00189 | # -*- coding: utf-8 -*-
"""
# This is authentication backend for Django middleware.
# In settings.py you need to set:
MIDDLEWARE_CLASSES = (
...
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.RemoteUserMiddleware',
...
)
AUTHENTICATION_BACKENDS = (
'kob... | ew.as_view(template = 'auth/krb5login.html'),
url(r'^auth/logout/$', 'django.contrib.auth.views.logout', kwargs={"next_page": "/"}),
...
)
# Set a httpd config to protect krb5login page with kerberos.
# You need to have mo | d_auth_kerb installed to use kerberos auth.
# Httpd config /etc/httpd/conf.d/<project>.conf should look like this:
<Location "/">
SetHandler python-program
PythonHandler django.core.handlers.modpython
SetEnv DJANGO_SETTINGS_MODULE <project>.settings
PythonDebug On
</Location>
<Location "/auth/krb5logi... |
GooeyComps/gooey-dist | setup.py | Python | mit | 542 | 0.068266 | from distutils.core import setup
from setuptools import setup, find_packages
setup(
name = 'go | oeydist',
packages = find_packages(), # this must be the same as the name above
version = '0.2',
description = 'Gooey Language',
author = | 'Gooey Comps',
author_email = 'harrise@carleton.edu',
url = 'https://github.com/GooeyComps/gooey-dist', # use the URL to the github repo
download_url = 'https://github.com/GooeyComps/gooey-dist/tarball/0.2', # I'll explain this in a second
keywords = ['gui'], # arbitrary keywords
classifiers = [],
) |
mistermatti/plugz | plugz/__init__.py | Python | bsd-3-clause | 317 | 0 | # -*- coding: utf- | 8 -*-
from loading import load_plugins, register_plugin
from plugz import PluginTypeBase
from plugintypes import StandardPluginType
__author__ = 'Matti Gruener'
__email__ = 'matti@mistermatti.com'
__version__ = '0.1.5'
__A | LL__ = [load_plugins, register_plugin, StandardPluginType, PluginTypeBase]
|
pombredanne/PythonJS | regtests/go/list_comprehension.py | Python | bsd-3-clause | 167 | 0.107784 | '''
go list comp | rehensions
'''
def main():
a = []int(x for x in range(3))
TestError( len(a)==3 )
TestError( a[0]==0 )
TestError( a[1]==1 )
TestError | ( a[2]==2 )
|
LennonChin/Django-Practices | MxOnline/apps/courses/migrations/0007_course_teacher.py | Python | apache-2.0 | 640 | 0.001563 | # -*- coding: utf-8 -*-
# Generated by Django 1 | .9.8 on 2017-09-14 23:53
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('organization', '0004_teacher_image'),
('courses', '0006_auto_20170914_2345'),
]
operations... | name='teacher',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='organization.Teacher', verbose_name='\u8bb2\u5e08'),
),
]
|
shinsterneck/pdns | regression-tests.recursor-dnssec/test_RoutingTag.py | Python | gpl-2.0 | 11,767 | 0.003144 | import dns
import os
import socket
import struct
import threading
import time
import clientsubnetoption
import subprocess
from recursortests import RecursorTest
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
emptyECSText = 'No ECS received'
nameECS = 'ecs-echo.example.'
nam... | d1)
| # Now check a cache hit with the same routingTag (but no ECS)
query = dns.message.make_query(nameECS, 'TXT', 'IN')
self.checkECSQueryHit(query, expected1)
expected2 = dns.rrset.from_text(nameECS, ttlECS, dns.rdataclass.IN, 'TXT', '127.0.0.0/24')
# And see if a different tag does *n... |
jvrsantacruz/XlsxWriter | xlsxwriter/test/comparison/test_utf8_03.py | Python | bsd-2-clause | 1,089 | 0 | ################################################################## | #############
# _*_ coding: utf-8
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org
#
from __future__ import unicode_literals
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
| Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'utf8_03.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + '_test_' + filename
self.exp_filename = test_dir + 'xlsx_files/'... |
freedomtan/tensorflow | tensorflow/python/training/ftrl.py | Python | apache-2.0 | 13,362 | 0.00232 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ame or self._name)
def _prepare(self):
self._learning_rate_tensor = ops.convert_to_tensor(
self._learning_rate, name="learning_rate")
self._l1_regularization_strength_tensor = ops.convert_to_tensor(
self._l1_regularization_strength, name="l1_regularization_strength")
# L2 regu | larization strength with beta added in so that the underlying
# TensorFlow ops do not need to include that parameter.
self._adjusted_l2_regularization_strength_tensor = ops.convert_to_tensor(
self._l2_regularization_strength + self._beta /
(2. * math_ops.maximum(self._learning_rate, 1e-36)),
... |
SHA2017-badge/micropython-esp32 | esp32/modules/setup.py | Python | mit | 894 | 0.004474 | # File: setup.py
# Version: 3
# Description: Setup for SHA2017 badge
# License: MIT
# Authors: Renze Nicolai | <renze@rnplus.nl>
# Thomas Roos <?>
import ugfx, badge, appglue, dialogs, easydraw, time
def asked_nickname(value):
if value:
badge.nvs_set_str("owner", "name", value)
# Do the firstboot magic
newState = 1 if badge.nvs_get_u8('badge', 'setup.state', 0) == | 0 else 3
badge.nvs_set_u8('badge', 'setup.state', newState)
# Show the user that we are done
easydraw.msg("Hi "+value+"!", 'Your nick has been stored to flash!')
time.sleep(0.5)
else:
badge.nvs_set_u8('badge', 'setup.state', 2) # Skip the sponsors
badge.nvs_set_u8('... |
MADindustries/WhatManager2 | WhatManager2/checks.py | Python | mit | 2,864 | 0.003492 | import os
from home.models import ReplicaSet, WhatTorrent, WhatFulltext
def run_checks():
errors = []
warnings = []
# Check WhatFulltext integrity
def check_whatfulltext():
w_torrents = dict((w.id, w) for w in WhatTorrent.objects.defer('torrent_file').all())
w_fulltext = dict((w.id, ... | f in files_in_dir):
errors.append(u'Missing .torrent file for {0} at {1}'
| .format(m_torrent, instance))
if not any('ReleaseInfo2.txt' == f for f in files_in_dir):
errors.append(u'Missing ReleaseInfo2.txt for {0} at {1}'
.format(m_torrent, instance))
for hash, t_torrent in i_t_torrents.ite... |
asposecells/Aspose_Cells_Cloud | Examples/Python/Examples/ClearCellFormattingInExcelWorksheet.py | Python | mit | 1,485 | 0.010101 | import asposecellscloud
from asposecellscloud.CellsApi import CellsApi
from asposecellscloud.CellsApi import ApiException
import asposestoragecloud
from asposestoragecloud.StorageApi import StorageApi
apiKey = "XXXXX" #sepcify App Key
appSid = "XXXXX" #sepcify App SID
apiServer = "http://api.aspose.com/v1.1"
data_fol... |
sheetName = "Sheet1"
range = "A1:A12"
#upload fi | le to aspose cloud storage
storageApi.PutCreate(Path=filename, file=data_folder + filename)
try:
#invoke Aspose.Cells Cloud SDK API to clear cells formatting in a worksheet
response = cellsApi.PostClearFormats(name=filename, sheetName=sheetName, range=range)
if response.Status == "OK":
#download u... |
CivicKnowledge/censuslib | censuslib/__init__.py | Python | mit | 3,138 | 0.013384 | # Support for building census bundles in Ambry
__version__ = 0.8
__author__ = 'eric@civicknowledge.com'
from .generator import *
from .schema import *
from .sources import *
from .transforms import *
import ambry.bundle
class AcsBundle(ambry.bundle.Bundle, MakeTablesMixin, MakeSourcesMixin,
JamValue... | .etl import SelectPartitionFromSource
# THe partition is named only after the table.
def select_f(pipe, bundle, source, row):
return | source.dest_table.name
pipeline.select_partition = SelectPartitionFromSource(select_f)
@CaptureException
def _pre_download(self, gen_cls):
"""Override the ingestion process to download all of the input files at once. This resolves
the contention for the files that would occurr if man... |
TakeshiTseng/SDN-Work | mininet/bgp/topo.py | Python | mit | 3,549 | 0.001972 | #!/usr/bin/python
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.cli import CLI
from mininet.log import setLogLevel, info, debug
from mininet.node import Host, RemoteController, OVSSwitch
# Must exist and be owned by quagga user (quagga:quagga by default on Ubuntu)
QUAGGA_RUN_DIR = '/var/r... | f.cmd('zebra -d -f %s -z %s/zebra%s.api -i %s/zebra%s.pid' % (self.zebraConfFile, QUAGGA_RUN_DIR, self.name, QUAGGA_RUN_DIR, self.name))
self.cmd('bgpd -d -f %s -z %s/zebra%s.api -i %s/bgpd%s.pid' % (self.quaggaConfFile, QUAGGA_RUN_DIR, self.name, QUAGGA_RUN_DIR, self.name))
| def terminate(self):
self.cmd("ps ax | egrep 'bgpd%s.pid|zebra%s.pid' | awk '{print $1}' | xargs kill" % (self.name, self.name))
Host.terminate(self)
class SdnIpTopo(Topo):
def build(self):
zebraConf = '{}/zebra.conf'.format(ZCONFIG_DIR)
s1 = self.addSwitch('s1', dpid='000000... |
huyphan/pyyawhois | test/record/parser/test_response_whois_nic_pw_status_available.py | Python | mit | 2,000 | 0.003 |
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# spec/fixtures/responses/whois.nic.pw/status_available
#
# and regenerate the tests with the following script
#
# $ scripts/generate_tests.py
#
fr | om nose.tools import *
from dateutil.parser import parse as time_parse
import yawhois
class TestWhoisNicPwStatusAvailable(object):
def setUp(self):
fixture_path = "spec/fixtures/responses/whois.nic.pw/status_available.txt"
| host = "whois.nic.pw"
part = yawhois.record.Part(open(fixture_path, "r").read(), host)
self.record = yawhois.record.Record(None, [part])
def test_status(self):
eq_(self.record.status, [])
def test_available(self):
eq_(self.record.available, True)
def t... |
kd0aij/matrixpilot_old | Tools/MAVLink/mavlink/pymavlink/generator/mavtemplate.py | Python | gpl-3.0 | 5,130 | 0.003119 | #!/usr/bin/env python
'''
simple templating system for mavlink generator
Copyright Andrew Tridgell 2011
Released under GNU GPL version 3 or later
'''
from mavparse import MAVParseError
class MAVTemplate(object):
'''simple templating system'''
def __init__(self,
start_var_token="... | kmissing = self.checkmissing
# handle repititions
while True:
subidx = text.find(self.start_rep_token)
if subidx == -1:
break
endidx = self.find_rep_end(text[subidx:])
if endidx == -1:
raise | MAVParseError("missing end macro in %s" % text[subidx:])
part1 = text[0:subidx]
part2 = text[subidx+len(self.start_rep_token):subidx+(endidx-len(self.end_rep_token))]
part3 = text[subidx+endidx:]
a = part2.split(':')
field_name = a[0]
rest = ... |
youtube/cobalt | third_party/v8/tools/testrunner/testproc/util.py | Python | bsd-3-clause | 2,389 | 0.007535 | #!/usr/bin/env python
# Copyright 2020 the V8 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.
import heapq
import os
import platform
import random
import signal
import subprocess
# Base dir of the build products for Release an... | n the last element of the tuple
# since those elements might not be comparable.
self.discriminator += 1
return self.discriminator
def as_list(self):
original_data = [rec for (_, _, rec) in self.data] |
return sorted(original_data, key=self.key, reverse=True)
|
thegooglecodearchive/marave | marave/plugins/rst2pdf.py | Python | gpl-2.0 | 1,268 | 0.014984 | # -*- coding: utf-8 -*-
from plugins import Plugin
from PyQt4 import QtCore, QtGui
import tempfile, codecs
import os, subprocess
class rst2pdf(Plugin):
name='rst2pdf'
shortcut='Ctrl+F8'
description='Run through rst2pdf and preview'
tmpf=None
def run(self):
print "Running rst2pdf"
... | lf.client.notify('Running rst2pdf')
subproc | ess.check_call('rst2pdf %s'%self.tmpf.name, shell=True)
except subprocess.CalledProcessError:
#FIXME: show error dialog
return
# Open with default PDF viewer
# FIXME: would be awesome if we could know when this is still open
# and not launch it again, since it re... |
iModels/mbuild | mbuild/formats/hoomd_simulation.py | Python | mit | 16,626 | 0.00012 | """HOOMD simulation format."""
import itertools
import operator
import warnings
from collections import namedtuple
import numpy as np
import parmed as pmd
import mbuild as mb
from mbuild.utils.conversion import RB_to_OPLS
from mbuild.utils.io import import_
from mbuild.utils.sorting import natural_sort
from .hoomd_s... | name,
sigma=atom_type.sigma / ref_distance,
epsilon=atom_type.epsilon / ref_energy,
)
# Cross interactions, mixing rules, NBfixes
all_atomtypes = sorted(atom_type_params.keys())
for a1, a2 in itertools.combinations_with_replacement(all_atomtypes, 2):
nb_fix_ | info = atom_type_params[a1].nbfix.get(a2, None)
# nb_fix_info = (rmin, eps, rmin14, eps14)
if nb_fix_info is None:
|
clione/django-kanban | src/kanban/wsgi.py | Python | mit | 1,419 | 0.000705 | """
WSGI config for kanban project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` s... | GI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorld | Application(application)
|
PyQwt/PyQwt5 | qt3examples/ReallySimpleDemo.py | Python | gpl-2.0 | 2,005 | 0.015461 | #!/usr/bin/env python
# The really simple Python version of Qwt-5.0.0/examples/simple
# for debugging, requires: python configure.py --trace ...
if False:
import sip
sip.settracemask(0x3f)
import sys
import qt
import Qwt5 as Qwt
from Qwt5.anynumpy import *
class SimplePlot(Qwt.QwtPlot):
def __init__... | ))
cCos.setData(x, cos(x))
# | insert a horizontal marker at y = 0
mY = Qwt.QwtPlotMarker()
mY.setLabel(Qwt.QwtText('y = 0'))
mY.setLabelAlignment(qt.Qt.AlignRight | qt.Qt.AlignTop)
mY.setLineStyle(Qwt.QwtPlotMarker.HLine)
mY.setYValue(0.0)
mY.attach(self)
# insert a vertical marker at x = 2 pi
m... |
baroquebobcat/pants | tests/python/pants_test/init/repro_mixin.py | Python | apache-2.0 | 1,635 | 0.004893 | # coding | =utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_fu | nction,
unicode_literals, with_statement)
import os
from pants.util.dirutil import safe_mkdir_for
class ReproMixin(object):
""" Additional helper methods for use in Repro tests"""
def add_file(self, root, path, content):
"""Add a file with specified contents
:param str root: Ro... |
UgCS/vsm-cpp-sdk | tools/mavgen/lib/genxmlif/xmliftest.py | Python | bsd-3-clause | 670 | 0.022388 | import genxmlif
from genxmlif.xmlifODict import odict
xmlIf = genxmlif.chooseXmlIf(genxmlif.XMLIF_ELEMENTTREE)
x | mlTree = xmlIf.createXmlTree(None, "testTree", {"rootAttr1":"RootAttr1"})
xmlRootNode = xmlTree.getRootNode()
myDict = odict( (("childTag1","123"), ("childTag2","123")) )
xmlRootNode.appendChild("childTag", myDict)
xmlRootNode.appendChild("childTag", {"childTag1":"123456", "childTag2":"123456"})
xmlRootNode.appendChild... | "childTag3":"1234", "childTag2":"123456789"})
xmlRootNode.appendChild("childTag", {"childTag1":"1", "childTag2":"1"})
print xmlTree.printTree(prettyPrint=1)
print xmlTree
print xmlTree.getRootNode() |
azer/jsbuild | jsbuild/manifest.py | Python | mit | 673 | 0.028232 | from jsbuild.attrdict import AttrDict
from time import strftime
class Manifest(AttrDict):
def __init__(self,*args,**kwargs):
super(AttrDict, self).__init__(*args,**kwargs)
self._buf | fer_ = None
self._parent_ = None
if not self.__contains__('_dict_'):
self['_dict_'] = {}
self['_dict_']['timestamp'] = int(strftime("%Y%m%d%H%M"))
def __getitem__(self,name):
item = super(Manifest,self).__getitem__(name)
if isinstance(item,Manifest) and not item._parent_:
item... | while root._parent_: root = root._parent_
item = item%root._dict_
return item
|
Javex/qllbot | tests/lib_tests/events.py | Python | bsd-2-clause | 1,213 | 0.000824 | import sys
import unittest
sys.path.append('../../')
import lib.event
class TestEvents(unittest.TestCase):
def setUp(self):
TestEvents.successful = False
TestEvents.successful2 = False
def test_subscribe(self):
@lib.event.subscribe('test')
def subscribe_test():
Te... | f subscribe_test(successful=False):
TestEvents.successful = successful
lib.event.call('test2', {'successful': | True})
self.assertTrue(TestEvents.successful)
def test_subscribe_two_with_params(self):
@lib.event.subscribe('test3')
def subscribe_test(successful=False):
TestEvents.successful = successful
@lib.event.subscribe('test3')
def subscribe_test2(successful=False):
... |
summychou/CSForOSS | CA/OSSQt_DataMasterRigster.py | Python | mit | 2,535 | 0.008748 | # -*- coding: utf-8 -*-
# import sqlite3 as sqlite
import sys
import uuid
from pysqlcipher3 import dbapi2 as sqlite
def main():
print("***************** Welcome to OSS DataMaster-Rigster System *******************")
print("* *")
pri... | *")
print("*********************** Data Master Rigster Is Failed! ***********************")
sys.exit(-1)
c.execute('insert into data_master_system values ("{}", "{}", "{}")'.format(data_master_name, password, unique_id))
conn.commit()
... | *")
print("********************* Data Master Rigster Is Successful! *********************")
if __name__ == '__main__':
main()
|
dmlc/xgboost | tests/python-gpu/test_gpu_prediction.py | Python | apache-2.0 | 17,716 | 0.000903 | import sys
import pytest
import numpy as np
import xgboost as xgb
from xgboost.compat import PANDAS_INSTALLED
from hypothesis import given, strategies, assume, settings
if PANDAS_INSTALLED:
from hypothesis.extra.pandas import column, data_frames, range_indexes
else:
def noop(*args, **kwargs):
pass
... | self.run_inplace_base_margin(booster, dtrain, X, base_margin)
# Create a wide dataset
X = cp_rng.randn(100, 10000)
y = cp_rng.randn(100)
missing_idx = [i for i in range(0, X.shape[1], 16)]
X[:, missing_idx] = missing
reg = xgb.XGBRegressor(tree_method="gpu_hist",... | ict(X)
reg.set_params(predictor="cpu_predictor")
cpu_predt = reg.predict(X)
np.testing.assert_allclose(gpu_predt, cpu_predt, atol=1e-6)
@pytest.mark.skipif(**tm.no_cupy())
@pytest.mark.skipif |
eddiejessup/cellulist | docs/conf.py | Python | bsd-3-clause | 8,421 | 0.005344 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# cellulist documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# 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
# a... | d file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use o... | he project root dir, which is the parent dir of this
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
# Insert the project root dir as the first element in the PYTHONPATH.
# This lets us ensure that the source package is imported, and that its
# version is used.
sys.path.insert(0, project_root)
import cellulist
... |
liqd/a4-meinberlin | tests/kiezkasse/conftest.py | Python | agpl-3.0 | 125 | 0 | from pytest_fact | oryboy import register
from meinberlin.test.factories import kiezkasse
register(kiezkasse.ProposalFactor | y)
|
indico/indico | indico/modules/events/tracks/forms.py | Python | mit | 2,016 | 0.001984 | # This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from wtforms.fields import StringField
from wtforms.validators import DataRequired
from wtforms_sqlalchemy... | ields import IndicoMarkdownField
class TrackForm(IndicoForm):
title = StringField(_('Title'), [DataRequired()])
code = StringField(_('Code'))
track_group = QuerySelectField(_('Track g | roup'), default='', allow_blank=True, get_label='title',
description=_('Select a track group to which this track should belong'))
default_session = QuerySelectField(_('Default session'), default='', allow_blank=True, get_label='title',
descri... |
rmfitzpatrick/ansible | lib/ansible/plugins/action/nxos.py | Python | gpl-3.0 | 4,638 | 0.001725 | #
# (c) 2016 Red Hat Inc.
#
# 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 d... | lf._play_context.remote_addr
if provider.get('port') is None:
if provider.get('use_ssl'):
provider['port'] = 443
else:
provider['port'] = 80
if provider.get('timeout') is None:
provider['timeout'] = C.PERSI... | sword') is None:
provider['password'] = self._play_context.password
if provider.get('use_ssl') is None:
provider['use_ssl'] = False
if provider.get('validate_certs') is None:
provider['validate_certs'] = True
self._task.args['provide... |
plotly/plotly.py | packages/python/plotly/plotly/validators/scatterternary/marker/gradient/_typesrc.py | Python | mit | 454 | 0 | import _plotly_utils.basevalidators
class TypesrcValidator(_plotly_utils.basevalidators.SrcValidator):
d | ef __init__(
self,
plotly_name="typesrc",
parent_name="scatterternary.marker.gradient",
**kwargs
):
super(TypesrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),
... | wargs
)
|
heroku/wal-e | setup.py | Python | bsd-3-clause | 1,831 | 0.001092 | #!/usr/bin/env python
import os.path
import sys
# Version file managment scheme and graceful degredation for
# setuptools borrowed and adapted from GitPython.
try:
from setuptools import setup, find_packages
# Silence pyflakes
assert setup
assert find_packages
except ImportError:
from ez_setup imp... | h.join(os.path.dirname(__file__), fname)) as f:
return f.read()
VERSION = read(os.path.join('wal_e', 'VERSION')).strip()
install_requires = [
l for l in read('requirements.txt').split('\n')
if l and not l.startswith('#')]
if sys.version_info < (2, 7):
install_requires.appen | d('argparse>=0.8')
setup(
name="wal-e",
version=VERSION,
packages=find_packages(),
install_requires=install_requires,
# metadata for upload to PyPI
author="The WAL-E Contributors",
author_email="wal-e@googlegroups.com",
maintainer="Daniel Farina",
maintainer_email="daniel@heroku.c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.