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 |
|---|---|---|---|---|---|---|---|---|
viiru-/pytrainer | pytrainer/gui/windowmain.py | Python | gpl-2.0 | 103,483 | 0.011026 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#Copyright (C) Fiz Vazquez vud1@sindominio.net
# Modified by dgranda
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or... | y1_limits = None
self.y1_color = None
self.y1_linewidth = 1
# setup Search ListView
self.listsearch = ListSearch(sport_service, self, self.pytrainer_main)
self.aboutwindow = None
def new(self):
self.menublocking = 0
self.selected_view="day"
s... | training","window_size").split(',')
self.window1.resize(int(width), int(height))
except:
pass
self.record_list = []
#create the columns for the listdayrecord
if self.pytrainer_main.profile.prf_us_system:
distance_unit = _("Miles")
else:
... |
pudo/aleph | aleph/logic/aggregator.py | Python | mit | 378 | 0 | imp | ort logging
from ftmstore import get_dataset
log = logging.getLogger(__name__)
MODEL_ORIGIN = "model"
def get_aggregator_name(collection):
return "collection_%s" % collection.id
def get_aggregator(collection, origin="aleph"):
"""Connect to a followthemoney dataset."""
dataset = get_aggregator_name(coll... | n=origin)
|
MarionPiEnsg/RaspiModel | Application/Raspberry_Pi/scripts_python/1-activeRobotHaut.py | Python | gpl-3.0 | 910 | 0.015402 | import RPi.GPIO as GPIO
import time
import sys
#on renseigne le pin sur lequel est branché le cable de commande du servo moteur superieur (haut-bas)
servo_pin = 12
#recuperation de la valeur du mouvement a envoyer au servo
duty_cycle = float(sys.argv[1])
GPIO.setmod | e(GPIO.BOARD)
GPIO.setup(servo_pin, GPIO.OUT)
# Creation du cannal PWM sur le servo pin avec une frequence de 50Hz
pwm_servo = GPIO.PWM(servo_pin, 50)
pwm_servo.start(duty_cycle)
try:
while True:
pwm_servo.ChangeDutyCycle(duty_cycle) #le servo se pivote avec la valeur donnee en entree
time.sleep(0... | ue le servo finisse son action
GPIO.cleanup() # on sort proprement de GPIO et on sort de la fonction avec exit()
exit()
except KeyboardInterrupt:
print("CTRL-C: Terminating program.") # si le programme est utilise seul, cela permet de l'eteindre en cas d'urgence
|
DailyActie/Surrogate-Model | 01-codes/scipy-master/scipy/special/_precompute/setup.py | Python | mit | 396 | 0 | #!/usr/bin/env pytho | n
from __future__ import division, print_function, absolute_import
def configuration(parent_name='special', top_path=None):
from numpy.distutils.misc_util import C | onfiguration
config = Configuration('_precompute', parent_name, top_path)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration().todict())
|
tensorflow/tpu | models/experimental/dcgan/mnist_model.py | Python | apache-2.0 | 3,215 | 0.002799 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | O_REUSE):
x = _conv2d(x, 64, 4, 2, name='d_conv1')
x = _leaky_relu(x)
x = _conv2d(x, 128, 4, 2, name='d_conv2')
x = _leaky_relu(_batch_norm(x, is_training, name='d_bn2'))
x = tf.reshape(x, [-1, 7 * 7 * 128])
x = _dense(x, 1024, name='d_fc3')
x = _leaky_relu(_batch_norm(x, is_training, nam... | ef generator(x, is_training=True, scope='Generator'):
# fc1024-bn-relu + fc6272-bn-relu + deconv64-bn-relu + deconv1-tanh
with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
x = _dense(x, 1024, name='g_fc1')
x = tf.nn.relu(_batch_norm(x, is_training, name='g_bn1'))
x = _dense(x, 7 * 7 * 128, name='g_fc... |
yinzishao/NewsScrapy | thepaper/thepaper/spiders/donews_spider.py | Python | lgpl-3.0 | 3,445 | 0.02148 | # -*- coding: utf-8 -*-
__author__ = 'k'
import re
import scrapy
from bs4 import BeautifulSoup
import logging
from thepaper.items import NewsItem
import json
logger = logging.getLogger("NbdSpider")
from thepaper.settings import *
from thepaper.util import judge_news_crawl
import time
class DonewsSpider(scrapy.spiders... | ind_all("p")])
item['referer_web | '] = referer_web
item['content'] = content
item['crawl_date'] = NOW
yield item |
pyparallel/numpy | numpy/ma/tests/test_core.py | Python | bsd-3-clause | 161,025 | 0.000689 | # pylint: disable-msg=W0401,W0511,W0611,W0612,W0614,R0201,E1102
"""Tests suite for MaskedArray & subclassing.
:author: Pierre Gerard-Marchant
:contact: pierregm_at_uga_dot_edu
"""
from __future__ import division, absolute_import, print_function
__author__ = "Pierre GF Gerard-Marchant"
import warnings
import pickle
i... | assert_equal(x.shape, (1, 3))
assert_equal(x._data, [[1, 2, 3]])
assert_equal(x._mask, [[1, 0, 0]])
def test_creation_ndmin_from_maskedarray(self):
# Make sure we're not losing the original mask w/ ndmin
x = array([1, 2, 3])
x[-1] = masked
xx = array(x, ndmin=2,... | def test_creation_maskcreation(self):
# Tests how masks are initialized at the creation of Maskedarrays.
data = arange(24, dtype=float)
data[[3, 6, 15]] = masked
dma_1 = MaskedArray(data)
assert_equal(dma_1.mask, data.mask)
dma_2 = MaskedArray(dma_1)
assert_equ... |
schrockn/graphscale | graphscale/grapple/graphql_impl.py | Python | mit | 2,294 | 0.000872 | from typing import cast, List, TypeVar, Any, Type, Optional
from uuid import UUID
from graphscale import check
from graphscale.pent import (
create_pent,
delete_pent,
update_pent,
Pent,
PentContext,
PentMutationData,
PentMutationPayload,
)
T = TypeVar('T')
def typed_or_none(obj: Any, cl... | dynamic(context: PentContext, out_cls_name: str, obj_id: U | UID) -> Pent:
out_cls = context.cls_from_name(out_cls_name)
pent = await out_cls.gen(context, obj_id)
return cast(Pent, pent)
async def gen_delete_pent_dynamic(
context: PentContext, pent_cls_name: str, payload_cls_name: str, obj_id: UUID
) -> PentMutationPayload:
pent_cls = context.cls_from_name(... |
tidepool-org/dfaker | dfaker/tools.py | Python | bsd-2-clause | 3,495 | 0.009442 | import pytz
from datetime import datetime, timedelta
def is_dst(zonename, date):
local_tz = pytz.timezone(zonename)
localized_time = local_tz.localize(date)
return localized_time.dst() != timedelta(0)
def get_offset(zonename, date):
local_tz = pytz.timezone(zonename)
if zonename == 'UTC':
... | correction) * precision
return round(result, 3)
def make_timesteps(start_time, offset, timelist):
""" Convert list of floats representing time into epoch time
start_time -- a timezone nai | ve datetime object
offset -- offset in minutes
timelist -- a list of incrementing floats representing time increments
"""
timesteps = []
epoch_ts = convert_ISO_to_epoch(str(start_time), '%Y-%m-%d %H:%M:%S')
local_timestamp = epoch_ts - offset*60
for time_item in timelist:
... |
serathius/elasticsearch-raven | tests/test_utils.py | Python | mit | 838 | 0.001193 | import time
from unittest import TestCase
from unittest import mock
from elasticsearch_raven import utils
class RetryLoopTest(TestCase):
@mock.patch('time.sleep')
def test_delay(self, sleep):
retry_generator = utils.retry_loop(1)
for i in range(4):
retry = next(retry_generator)
... | ck_calls)
@mock.patch('time.sleep')
def test_back_off(self, sleep):
retry_generator = utils.retry_loop(1, max_delay=4, back_off=2)
for i in range(5):
retry = next(retry_generator)
retry(Exception('test'))
self.assertEqual([mock.call(1), mock.call(2), mock.call(4)... | sleep.mock_calls)
|
sjl767/woo | gui/qt4/ExceptionDialog.py | Python | gpl-2.0 | 1,473 | 0.017651 | # encoding: utf-8
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class ExceptionDialog(QMessageBox):
def __init__(self,parent,exc,t1=None,t2=None):
QMessageBox.__init__(self,parent)
if t1==None: | t1=(exc.args[0] if len(exc.args)>0 else None)
self.setText(u'<b>'+exc.__class__.__name__+':</b><br>\n'+unicode(t1))
#QMessageBox.setTitle(self,xc.__class__.__name__)
import traceback
| tbRaw=traceback.format_exc()
# newlines are already <br> after Qt.convertFromPlainText, discard to avoid empty lines
tb='<small><pre>'+Qt.convertFromPlainText(tbRaw).replace('\n','')+'</pre></small>'
self.setInformativeText(t2 if t2 else tb)
self.setDetailedText(tbRaw)
self.setI... |
mluo613/osf.io | admin/common_auth/admin.py | Python | apache-2.0 | 2,230 | 0.000897 | from __future__ import absolute_import
from django.contrib import admin
from django.contrib.admin.models import DELETION
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import Permission
from django.core.urlresolvers import reverse
from django.utils.html import escape
from admin.common... |
'message',
]
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return request.user.is_superuser and request.method != 'POST'
def has_delete_permission(self, request, obj=None):
return False
def object_link(sel... | scape(obj.object_repr)
elif obj.content_type is None:
link = escape(obj.object_repr)
else:
ct = obj.content_type
link = u'<a href="%s">%s</a>' % (
reverse('admin:%s_%s_change' % (ct.app_label, ct.model), args=[obj.object_id]),
escape(ob... |
karacos/karacos-wsgi | lib/wsgioauth/request.py | Python | lgpl-3.0 | 3,175 | 0.004409 | # -*- coding: utf-8 -*-
import oauth2 # XXX pumazi: factor this out
from webob.multidict import MultiDict, NestedMultiDict
from webob.request import Request as WebObRequest
__all__ = ['Request']
class Request(WebObRequest):
| """The OAuth version of the WebOb Request.
Provides an easier way to obtain OAuth request parameters
(e.g. oauth_token) from the WSGI environment."""
def _checks_positive_for_oauth(self, params_var):
"""Simple check for the presence of OAuth parameters."""
checks = [ p.find('oauth_ | ') >= 0 for p in params_var ]
return True in checks
@property
def str_oauth_header(self):
extracted = {}
# Check for OAuth in the Header
if 'authorization' in self.headers:
auth_header = self.headers['authorization']
# Check that the authorizatio... |
nnadeau/pybotics | pybotics/geometry.py | Python | mit | 4,716 | 0.000848 | """Geometry functions and utilities."""
from enum import Enum
from typing import Sequence, Union
import numpy as np # type: ignore
from pybotics.errors import PyboticsError
class OrientationConvention(Enum):
"""Orientation of a body with respect to a fixed coordinate system."""
EULER_XYX = "xyx"
EULER... | 3")
| matrix = np.eye(4)
matrix[:-1, -1] = xyz
return matrix
|
jdfekete/progressivis | progressivis/core/changemanager_literal.py | Python | bsd-2-clause | 2,053 | 0.000487 | "Change Manager for literal values (supporting ==)"
from __future__ import annotations
from .bitmap import bitmap
from .index_update import IndexUpdate
from .changemanager_base import BaseChangeManager
from typing import (
Any,
TYPE_CHECKING,
)
if TYPE_CHECKING:
from .slot import Slot
class LiteralChan... | d.update(self.VALUE)
self._last_value = data
return changes
def update(self, run_number: int, data: Any, mid: str) -> None:
# pylint: disable=unused-argument
if run_number != 0 and run_number <= self._last_update:
return
changes = self.compute_updates(data)
... | buffer, self.deleted.buffer
)
|
lawsie/guizero | examples/alert.py | Python | bsd-3-clause | 205 | 0.004878 | from | guizero import App
app = App()
app.info("Info", "This is a guizero app")
app.error("Error", "Try and keep these o | ut your code...")
app.warn("Warning", "These are helpful to alert users")
app.display() |
aldebaran/strong_typing | strong_typing/__init__.py | Python | bsd-3-clause | 4,043 | 0.004116 | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Softbank Robotics Europe
# 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 copyright notice, t... | to endorse or promote products derived from
# this | software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 ... |
johren/RackHD | test/tests/rackhd20/test_rackhd20_api_config.py | Python | apache-2.0 | 3,739 | 0.006419 | '''
Copyright 2016, EMC, Inc.
Author(s):
George Paulos
'''
import fit_path # NOQA: unused import
import os
import sys
import subprocess
import fit_common
from nose.plugins.attrib import attr
@attr(all=True, regression=True, smoke=True)
class rackhd20_api_config(fit_common.unittest.TestCase):
def test_api_20_co... | d')
self.assertIn('authEnabled', endpoin | t, 'missing httpEndpoints authEnabled field')
self.assertIn('httpsEnabled', endpoint, 'missing httpEndpoints httpsEnabled field')
self.assertIn('proxiesEnabled', endpoint, 'missing httpEndpoints proxiesEnabled field')
self.assertIn('routers', endpoint, 'missing httpEndpoints routers ... |
moonbury/notebooks | github/Numpy/Chapter6/lognormaldist.py | Python | gpl-3.0 | 563 | 0.008881 | import numpy as np
import matplotlib.pyplot as plt
N=10000
np.random.seed(34)
lognormal_values = np.random.lognormal(size=N)
_, bins, _ = plt.hist | (lognormal_values, np.sqrt(N), normed=True, lw=1, label="Histogram")
sigma = 1
mu = 0
x = np.linspace(min(bins), max(bins), len(bins))
pdf = np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))/ (x * sigma * np.sqrt(2 * np.pi))
plt.xlim([0, 15])
plt.plot(x, p | df,'--', lw=3, label="PDF")
plt.title('Lognormal distribution')
plt.xlabel('Value')
plt.ylabel('Normalized frequency')
plt.grid()
plt.legend(loc='best')
plt.show()
|
lmallin/coverage_test | python_venv/lib/python2.7/site-packages/pandas/tests/test_common.py | Python | mit | 4,870 | 0.000205 | # -*- coding: utf-8 -*-
import pytest
import numpy as np
from pandas import Series, Timestamp
from pandas.compat import range, lmap
import pandas.core.common as com
import pandas.util.testing as tm
def test_mut_exclusive():
msg = "mutually exclusive arguments: '[ab]' and '[ab]'"
with tm.assert_raises_regex... | _any_none():
assert (com._any_none(1, 2, 3, None))
assert (not com._any_none(1, 2, 3, 4))
def test_all_not_none():
| assert (com._all_not_none(1, 2, 3, 4))
assert (not com._all_not_none(1, 2, 3, None))
assert (not com._all_not_none(None, None, None, None))
def test_iterpairs():
data = [1, 2, 3, 4]
expected = [(1, 2), (2, 3), (3, 4)]
result = list(com.iterpairs(data))
assert (result == expected)
def te... |
onedox/selenium | py/test/selenium/webdriver/firefox/ff_profile_tests.py | Python | apache-2.0 | 8,146 | 0.002701 | #!/usr/bin/python
#
# Copyright 2008-2010 WebDriver committers
# Copyright 2008-2010 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... | the License for the specific language governing permissions and
# limitations under the License.
import base64
import os
import unittest
import zipfile
try:
from io import BytesIO
except ImportError:
from cStringIO import StringIO as BytesIO
try:
unicode
except NameError:
unicode = str
from selenium... | Profile:
def setup_method(self, method):
self.driver = webdriver.Firefox()
self.webserver = SimpleWebServer()
self.webserver.start()
def test_that_we_can_accept_a_profile(self):
profile1 = webdriver.FirefoxProfile()
profile1.set_preference("startup.homepage_welcome_url"... |
jimberlage/servo | tests/wpt/web-platform-tests/tools/ci/taskcluster-run.py | Python | mpl-2.0 | 3,009 | 0.000665 | #!/usr/bin/env python
import argparse
import gzip
import logging
import os
import shutil
import subprocess
browser_specific_args = {
"firefox": ["--install-browser"]
}
def tests_affected(commit_range):
output = subprocess.check_output([
"python", "./wpt", "tests-affected", "--null", commit_range
... | tests = tests_affected(commit_range)
logger.info("Identified %s affected tests" % len(tests))
if not tests:
logger.info("Quitting because no tests were affected.")
| return
else:
tests = []
logger.info("Running all tests")
wpt_args += [
"--log-tbpl-level=info",
"--log-tbpl=-",
"-y",
"--no-pause",
"--no-restart-on-unexpected",
"--install-fonts",
"--no-headless"
]
wpt_args += browser_specific_a... |
stpettersens/Packager | travis.py | Python | mit | 114 | 0 | #!/usr/bin/env python
from subprocess import call
call(["bick | le", "builds", "stpettersens/Packager", | "-n", "5"])
|
prataprc/CouchPy | couchpy/.Attic/attachment.py | Python | gpl-3.0 | 7,105 | 0.024208 | """Module provides provides a convinient class :class:`Attachment` to access (Create,
Read, Delete) document attachments."""
import base64, logging
from os.path import basename
from copy import deepcopy
from mimetypes import guess_type
from httperror import *... | s Attachment( object ) :
def __i | nit__( self, doc, filename ) :
"""Class instance object represents a single attachment in a document,
use the :class:`Document` object and attachment `filename` to create
the instance.
"""
self.doc = doc
self.db = doc.db
self.filename = filename
self.conn ... |
JazzeYoung/VeryDeepAutoEncoder | theano/misc/strutil.py | Python | bsd-3-clause | 1,620 | 0 | from __future__ import absolute_import, print_function, division
from six.moves import xrange
def render_string(string, sub):
"""
string: a string, containing formatting instructions
sub: a dictionary containing keys and values to substitute for
them.
returns: string % sub
The only diffe... |
is that it raises an exception with a more informative error
message than the % operator does.
"""
try:
finalCode = string % sub
except Exception as E:
# If unable | to render the string, render longer and longer
# initial substrings until we find the minimal initial substring
# that causes an error
i = 0
while i <= len(string):
try:
finalCode = string[0:i] % sub
except Exception as F:
if str(F... |
emsrc/pycornetto | lib/cornetto/argparse.py | Python | gpl-3.0 | 77,238 | 0.000531 | # -*- coding: utf-8 -*-
# Copyright � 2006 Steven J. Bethard <steven.bethard@gmail.com>.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted under the terms of the 3-clause BSD
# license. No warranty expressed or implied.
# For details, see the accompanying file ... | classes
# =============================
class _AttributeHolder(object):
"""Abstract base class that provides __repr__.
The __repr__ method returns a string in the format:
ClassName(attr=name, attr=name, ...)
The attributes are determined either by a class-l | evel attribute,
'_kwarg_names', or by inspecting the instance __dict__.
"""
def __repr__(self):
type_name = type(self).__name__
arg_strings = []
for arg in self._get_args():
arg_strings.append(repr(arg))
for name, value in self._get_kwargs():
... |
anhstudios/swganh | data/scripts/templates/object/mobile/shared_dressed_diax.py | Python | mit | 426 | 0.049296 | #### NOTICE: 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 = Creature()
result.template = "object/mobile/shared_dressed | _diax.iff"
result.attribute_template_id = 9
result.stfName("npc_name","diax")
|
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
suraj-jayakumar/lstm-rnn-ad | src/testdata/random_data_15min_ts/point_to_batch_data_conversion.py | Python | apache-2.0 | 762 | 0.018373 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 25 10:21:20 2016
@author: suraj
"""
import pickle
import numpy as np
X = pickle.load(open('x_att.p'))
y = pickle.load(open('y_att.p'))
batchX = []
batchy = []
def convertPointsToBatch(day_of_week,data1,data2):
for i in range(5):
batchX.extend(data1... | int batchX[ | 0]
print batchy[0]
pickle.dump(batchX,open('batch_x_att.p','wb'))
pickle.dump(batchy,open('batch_y_att.p','wb')) |
jscontreras/learning-gae | pgae-examples-master/2e/python/clock/clock4/prefs.py | Python | lgpl-3.0 | 541 | 0.003697 | import webapp2
import models
class PrefsPage | (webapp2.RequestHandler):
def post(self):
userprefs = models.get_userprefs()
try:
tz_offset = int(self.request.get('tz_offset'))
userprefs.tz_offset = tz_offset
userprefs.put()
except ValueError:
# User entered a value that wasn't an integer. ... | rue)
|
3v1n0/pywws | src/pywws/device_pyusb.py | Python | gpl-2.0 | 5,584 | 0.002328 | # pywws - Python software for USB Wireless Weather Stations
# http://github.com/jim-easterbrook/pywws
# Copyright (C) 2008-15 Jim Easterbrook jim@jim-easterbrook.me.uk
# 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 F... | device(idVendor, idProduct)
if not dev:
raise IOError("Weather station device not found")
self.devh = dev.open()
| if not self.devh:
raise IOError("Open device failed")
self.devh.reset()
## if platform.system() is 'Windows':
## self.devh.setConfiguration(1)
try:
self.devh.claimInterface(0)
except usb.USBError:
# claim interface failed, try detachi... |
bwesterb/germain | exact.py | Python | gpl-3.0 | 437 | 0.004577 | """ Generates a list of [b, N, n] where N is the amount of b-bit primes
and n | is the amount of b-bit safe primes. """
import gmpy
import json
for b in xrange(1,33):
N = 0
n = 0
p = gmpy.mpz(2**b)
while True:
p = gmpy.next_prime(p)
if p > 2**(b+ | 1):
break
if gmpy.is_prime(2*p + 1):
n += 1
N += 1
d = n/float(N)
print json.dumps([b, N, n])
|
appuio/ansible-role-openshift-zabbix-monitoring | vendor/openshift-tools/ansible/roles/lib_gcloud/build/ansible/gcloud_iam_sa_keys.py | Python | apache-2.0 | 2,395 | 0.00334 | # pylint: skip-file
# vim: expandtab:tabstop=4:shiftwidth=4
#pylint: disable=too-many-branches
def main():
''' ansible module for gcloud iam service-account keys'''
module = AnsibleModule(
argument_spec=dict(
# credentials
state=dict(default='present', type='str', choices=['pres... | dule.exit_json(changed=True, results=api_rval, state="prese | nt")
module.exit_json(failed=True,
changed=False,
results='Unknown state passed. %s' % state,
state="unknown")
# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
# import module snippets. This are required... |
macioosch/dynamo-hard-spheres-sim | to_csv_pretty.py | Python | gpl-3.0 | 3,184 | 0.005653 | #!/usr/bin/env python2
# encoding=utf-8
from __future__ import division, print_function
from math import ceil, floor, log10, pi
from sys import argv, stdout
from xml.dom import minidom
import bz2
import csv
# local imports
from my_helper_functions_bare import *
def pretty_mean_std(data):
return uncertain_number_... | ['Avg'].value))
data["pressures_collision"][-1].append(my_pressure(data["n_atoms"][-1],
data["collisions"][-1], data["times"][-1][-1]))
try:
data["msds_val"][-1].append(float(
xmldoc.getElementsByTagName('Species')[0].attributes['val'].value))
data["msds_diffusion"][-1].appen... | onCoeff'].value))
except:
data["msds_val"][-1].append(None)
data["msds_diffusion"][-1].append(None)
stdout_writer = csv.writer(stdout, delimiter='\t')
"""
stdout.write("### Data format: packings\tdensities\tcollisions\tn_atoms\t"
"pressures_virial\tpressures_collision\tmsds_val\tmsds_diffus... |
petertodd/python-opentimestamps | opentimestamps/core/notary.py | Python | lgpl-3.0 | 10,936 | 0.002195 | # Copyright (C) 2016 The OpenTimestamps developers
#
# This file is part of python-opentimestamps.
#
# It is subject to the license terms in the LICENSE file found in the top-level
# directory of this distribution.
#
# No part of python-opentimestamps including this file, may be copied,
# modified, propagated, or distr... | ized_attestation)
# If attestations want to have unspecified fields for future
# upgradabilit | y they should do so explicitly.
payload_ctx.assert_eof()
return r
class UnknownAttestation(TimeAttestation):
"""Placeholder for attestations that don't support"""
def __init__(self, tag, payload):
if tag.__class__ != bytes:
raise TypeError("tag must be bytes instance; got %... |
engla/kupfer | kupfer/textutils.py | Python | gpl-3.0 | 2,681 | 0.001617 | # encoding: utf-8
def _unicode_truncate(ustr, length, encoding="UTF-8"):
"Truncate @ustr to specific encoded byte length"
bstr = ustr.encode(encoding)[:length]
return bstr.decode(encoding, 'ignore')
def extract_title_body(text, maxtitlelen=60):
"""Prepare @text: Return a (title, body) tuple
@text... | length of title.
The default value yields a resulting title of approximately 60 ascii
characters, or 20 asian characters.
>>> extract_title_body("Short Text")
('Short Text', '' | )
>>> title, body = extract_title_body(u"執筆方針については、項目名の付け方、"
... "フォーマットや表記上の諸問題に関して多くの方針が存在している。")
>>> print(title)
執筆方針については、項目名の付け方、フォ
>>> print(body) # doctest: +ELLIPSIS
執筆方針については、項目名の付け方、フォ...して多くの方針が存在している。
"""
# if you don't make real tests, it's not not worth doing ... |
Goodideax/CS249 | new.py | Python | bsd-3-clause | 14,678 | 0.014784 | #! /usr/bin/env python
import re
import math
import collections
import numpy as np
import time
import operator
from scipy.io import mmread, mmwrite
from random import randint
from sklearn import cross_validation
from sklearn import linear_model
from sklearn.grid_search import GridSearchCV
from sklearn import preproces... | ef load_train_fs():
# In the validation process, the training data was randomly shuffled firstly.
# For the prediction process, there is no need to shuffle the dataset.
# Owing to out of memory problem, Gaussian process only use part of training data, th | e prediction of gaussian process
# may be a little different from the model,which the training data was shuffled.
train_fs = np.genfromtxt(open(dir + '/train_v2_1000.csv','rb'), delimiter=',', skip_header=1)
col_mean = stats.nanmean(train_fs, axis=0)
inds = np.where(np.isnan(train_fs))
train_fs[inds... |
gltn/stdm | stdm/ui/lookup_value_selector.py | Python | gpl-2.0 | 4,591 | 0 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : lookup value selector
Description : Enables the selection of lookup values from a
lookup entity.
Date : 09/February/2017
copyright :... | ""
QDialog.__init__(self, parent, Qt.WindowTitleHint |
Qt.WindowCloseButtonHint)
self.setupUi(self)
self.value_and_code = None
if profile is None:
self._profile = current_profile()
else:
self._profile = profile
self.lookup... | lf._profile.prefix, lookup_entity_name)
)
self.notice = NotificationBar(self.notice_bar)
self._view_model = QStandardItemModel()
self.value_list_box.setModel(self._view_model)
header_item = QStandardItem(lookup_entity_name)
self._view_model.setHorizontalHeaderItem(0, hea... |
trustedanalytics/spark-tk | python/sparktk/frame/ops/box_cox.py | Python | apache-2.0 | 2,662 | 0.003096 | # vim: set encoding=utf-8
# Copyright (c) 2016 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | See the License fo | r the specific language governing permissions and
# limitations under the License.
#
def box_cox(self, column_name, lambda_value=0.0, box_cox_column_name=None):
"""
Calculate the box-cox transformation for each row on a given column of the current frame
Parameters
----------
:param column_nam... |
asedunov/intellij-community | python/testData/inspections/PyRedeclarationInspection/localVariable.py | Python | apache-2.0 | 46 | 0.021739 | def test_local_variab | le():
x = 1
| x = 2 |
mbj4668/pyang | pyang/plugins/ietf.py | Python | isc | 7,093 | 0.001551 | """IETF usage guidelines plugin
See RFC 8407
"""
import optparse
import sys
import re
from pyang import plugin
from pyang import statements
from pyang import error
from pyang.error import err_add
from pyang.plugins import lint
def pyang_plugin_init():
plugin.register_plugin(IETFPlugin())
class IETFPlugin(lint.L... | optparse.make_option("--ietf-help",
dest="ietf_help",
action="store_true",
help="Print help on the IETF checks and exit"),
]
optparser.add_options(optlist)
def setup_ctx(self, ctx):
if c... | |
android-art-intel/Nougat | art-extension/tools/checker/common/archs.py | Python | apache-2.0 | 663 | 0 | # Copyright (C) 2015 The Android Open Source Project
#
# 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 applicabl | e law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the Lice | nse for the specific language governing permissions and
# limitations under the License.
archs_list = ['ARM', 'ARM64', 'MIPS', 'MIPS64', 'X86', 'X86_64']
|
cyyber/QRL | src/qrl/grpcProxy.py | Python | mit | 9,400 | 0.002766 | # coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
import argparse
import os
import simplejson as json
import grpc
from google.protobuf.json_format import MessageToJson
from qrl.core import config
from qrl.core.AddressS... | limit')
addrs_to = []
amounts = []
for tx in destinations:
addrs_to.append(bytes(hstr2bin(tx['address'][1:]))) # Skipping 'Q'
amounts.append(tx['amount'])
stub = get_public_stub()
xmss = get_unused_payment_xmss(stub)
if not xmss:
raise Exception('Payment Failed: No ... | nd')
tx = TransferTransaction.create(addrs_to=addrs_to,
amounts=amounts,
message_data=None,
fee=fee,
xmss_pk=xmss.pk,
master_addr=payme... |
jcrudy/glm-sklearn | glmsklearn/glm.py | Python | bsd-3-clause | 9,972 | 0.017048 |
import statsmodels.api
import statsmodels.genmod.families.family
import numpy as np
from sklearn.metrics import r2_score
class GLM(object):
'''
A scikit-learn style wrapper for statsmodels.api.GLM. The purpose of this class is to
make generalized linear models compatible with scikit-learn's Pipeline obj... | res
The training predictors. The X parameter can be a numpy array, a pandas DataFrame, a patsy
DesignMatrix, or a tuple of patsy DesignMatrix objects as output by patsy.dmatrices.
y : array-like, optional (default=None), shape = [m] where m is the number of sample... | ix, or can be left as None (default) if X was the output of a
call to patsy.dmatrices (in which case, X contains the response).
xlabels : iterable of strings, optional (default=None)
Convenient way to set the xlabels parameter while calling fit. Ignored if None (d... |
seertha/WSN_XBee | Software/RPI/Display_lcd/nodos_conectados.py | Python | mit | 1,363 | 0.02788 | #Prueba para mostrar los nodos conectados a la red
from base_datos import db
import time
from datetime import timedelta, datetime,date
dir_base="/media/CasaL/st/Documentos/proyectoXbee/WSN_XBee/basesTest/xbee_db02.db"
d=timedelta(minutes=-10)
#now=datetime.now()
#calculo=now+d
#print(calculo.strftime("%H:%M:%S"))
#hoy... | aHora)[0][0]
aux1=ultimoRegistro.split(" ")
horaReg=aux1[0].split(":")
fe | chaReg=aux1[1].split("/")
aux_ini=datetime(int(fechaReg[2]),int(fechaReg[1]),int(fechaReg[0]),int(horaReg[0]),int(horaReg[1]),int(horaReg[2]))
aux_final=aux_ini+d
hora_inicio=aux_ini.strftime("%H:%M:%S %d/%m/%Y")
hora_final=aux_final.strftime("%H:%M:%S %d/%m/%Y")
print (hora_final)
#print("Hora inicio: {} Hora final: {... |
gofed/gofed-ng | common/service/storageService.py | Python | gpl-3.0 | 1,413 | 0.001415 | #!/bin/python
# -*- coding: utf-8 -*-
# ####################################################################
# gofed-ng - Golang system
# Copyright (C) 2016 Fridolin Pokorny, fpokorny@redhat.com
#
# This program is free software; you can redistribute it and/or
# modify it under | the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that | it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free S... |
oblique-labs/pyVM | rpython/rlib/rmd5.py | Python | mit | 14,169 | 0.019409 | # -*- coding: iso-8859-1 -*-
"""
RPython implementation of MD5 checksums.
See also the pure Python implementation in lib_pypy/md5.py, which might
or might not be faster than this one on top of CPython.
This is an implementation of the MD5 hash function,
as specified by RFC 1321. It was implemented using Bruce Schneie... | unction).
"""
res = a + func(b, c, d)
res = res + x
res = res + ac
res = _rotateLeft(res, s)
res = res + b
return res
XX._annspecialcase_ = 'specialize:arg(0)' # performance hint
class RMD5(object):
"""RPython-level MD5 object.
"""
def __init__(self, initialdata=''):
... | lf.count = r_ulonglong(0) # total number of bytes
self.input = "" # pending unprocessed data, < 64 bytes
self.uintbuffer = [r_uint(0)] * 16
# Load magic initialization constants.
self.A = r_uint(0x67452301L)
self.B = r_uint(0xefcdab89L)
self.C = r_uint(0x98badcfeL)
... |
arkadoel/directORM | python/salida/directORM/forProveedores.py | Python | gpl-2.0 | 3,696 | 0.002976 |
import sqlite3
import directORM
class Proveedor:
def __init__(self):
self.idProveedor = -1
self.nombre = ''
self.email = ''
self.tlf_fijo = ''
self.tlf_movil = ''
self.tlf_fijo2 = ''
self.tlf_movil2 = ''
self.banco = ''
self.cuenta_bancaria ... | veedores:
INSERT = '''
| insert into Proveedores
( nombre, email, tlf_fijo, tlf_movil, tlf_fijo2, tlf_movil2, banco, cuenta_bancaria, direccion, foto_logo)
values (?,?,?,?,?,?,?,?,?,?)
'''
DELETE = 'delete from Proveedores where idProveedor = ?'
SELECT = 'select * from Proveedores'
UPDATE = '''
updat... |
hnikolov/pihdf | examples/hsd_inc/src/hsd_inc_beh.py | Python | mit | 340 | 0.002941 | def hsd_inc_b | eh(rxd, txd):
'''|
| Specify the behavior, describe data processing; there is no notion
| of clock. Access the in/out interfaces via get() and append()
| methods. The "hsd_inc_beh" function does not return values.
|________'''
if rxd.hasPacket():
data = rxd.get() + 1
txd.append(... | a)
|
miracl/amcl | version3/c/config64.py | Python | apache-2.0 | 19,998 | 0.069207 | import os
import subprocess
import sys
deltext=""
if sys.platform.startswith("linux") :
deltext="rm"
copytext="cp"
if sys.platform.startswith("darwin") :
deltext="rm"
copytext="cp"
if sys.platform.startswith("win") :
deltext="del"
copytext="copy"
def run_in_shell(cmd):
subprocess.check_call(cmd, shell=Tru... | xt+" config_big.h "+fnameh)
replace(fnameh,"XXX",bd)
replace(fnameh,"@NB@",nb)
replace(fnameh,"@BASE@",base)
fnameh="config_field_"+tf+".h"
run_in_shell(copytext+" config_field.h "+fnameh)
replace(fnameh,"XXX",bd)
replace(fnameh,"YYY",tf)
replace(fnameh,"@NBT@",nbt)
replace(fnameh,"@M8@",m8)
replace(fnameh,"... | =ib*(1+((8*inb-1)//ib))-inbt
if sh > 30 :
sh=30
replace(fnameh,"@SH@",str(sh))
fnameh="config_curve_"+tc+".h"
run_in_shell(copytext+" config_curve.h "+fnameh)
replace(fnameh,"XXX",bd)
replace(fnameh,"YYY",tf)
replace(fnameh,"ZZZ",tc)
replace(fnameh,"@CT@",ct)
replace(fnameh,"@PF@",pf)
replace(fnameh,"@ST@... |
GooogIe/VarasTG | plugins/btc.py | Python | gpl-3.0 | 751 | 0.050599 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Btc plugin for Varas
Author: Neon & A Sad Loner
Last modified: November 2016
"""
import urllib2
from plugin import Plugin
name = 'Bitcoin'
class Bitcoin(Plugin):
def __init__(self):
Plugin.__init__(self,"bitcoin","<wallet> Return current balance from a ... | "A Sad Loners",1.0)
def run(self,address):
#1btc = 100000000satoshi
print "https://blockchain.info/it/q/addressbalance/"+address
try:
api = urllib2.urlopen("https://blockchain.info/it/q/addressbalance/"+address)
except:
return "Unknown Error"
resp = api.read()
... | sp)
btc = satoshi/100000000
return "Balance: " + str(btc) |
erigones/esdc-ce | vms/middleware.py | Python | apache-2.0 | 1,676 | 0.00537 | from logging import getLogger
from vms.models import Dc, DummyDc
logger = getLogger(__name__)
class DcMiddleware(object):
"""
Attach dc attribute to each request.
"""
# noinspection PyMethodMayBeStatic
def process_request(self, request):
dc = getattr(request, 'dc', None)
if not ... | P_HOST'])
except (KeyError, Dc.DoesNotExist):
request.dc = DummyDc()
# Whenever we set a DC we have to set request.dc_user_permissions right after request.dc is available
request.dc_user_permis | sions = frozenset() # External users have no permissions
|
cheelee/ChannelWorm | channelworm/fitter/examples/EGL-19-2.py | Python | mit | 6,529 | 0.013019 | """
Example of using cwFitter to generate a HH model for EGL-19 Ca2+ ion channel
Based on experimental data from doi:10.1083/jcb.200203055
"""
import os.path
import sys
import time
import numpy as np
import matplotlib.pyplot as plt
sys.path.appe | nd('../../..')
from channelworm.fitter import *
if __name__ == '__main__':
userData = dict()
cwd=os.getcwd()
csv_path = os.path.dirname(cwd)+'/examples/egl-19-data/egl-19-IClamp-IV.csv'
ref = {'fig':'2B','doi':'10.1083/jcb.200203055'}
x_var = {'type':'Voltage','unit':'V','toSI':1}
y_var = {'t... | ','toSI':75e-12}
IV = {'ref':ref,'csv_path':csv_path,'x_var':x_var,'y_var':y_var}
userData['samples'] = {'IV':IV}
# csv_path_IC_100 = os.path.dirname(cwd)+'egl-19-data//egl-19-IClamp-100pA.csv'
# csv_path_IC_200 = os.path.dirname(cwd)+'egl-19-data//egl-19-IClamp-200pA.csv'
# csv_path_IC_300 = os.pa... |
hayderimran7/tempest | tempest/api/baremetal/admin/test_chassis.py | Python | apache-2.0 | 3,455 | 0 | # -*- coding: utf-8 -*-
# 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 ... | ['description'], descr)
@test.idempotent_id('c84644df-31c4-49db-a307-8942881f41c0')
def test_show_chassis(self):
_, chassis = self.client.show_chassis(self.chassis['uuid'])
self._assertExpected(self.chassis, chassis)
@test.idempotent_id('29c9cd3f-19b5-417b-9864-99512c3b33b3')
def test_... | self.client.list_chassis()
self.assertIn(self.chassis['uuid'],
[i['uuid'] for i in body['chassis']])
@test.idempotent_id('5ae649ad-22d1-4fe1-bbc6-97227d199fb3')
def test_delete_chassis(self):
_, body = self.create_chassis()
uuid = body['uuid']
self.delete_... |
huran2014/huran.github.io | wot_gateway/usr/lib/python2.7/urlparse.py | Python | gpl-2.0 | 14,414 | 0.002081 | """Parse (absolute and relative) URLs.
urlparse module is based upon the following RFC specifications.
RFC 3986 (STD66): "Uniform Resource Identifiers" by T. Berners-Lee, R. Fielding
and L. Masinter, January 2005.
RFC 2732 : "Format for Literal IPv6 Addresses in URL's by R.Hinden, B.Carpenter
and L.Masinter, Decemb... | mms', '', 'sftp']
uses_query = ['http', 'wais', ' | imap', 'https', 'shttp', 'mms',
'gopher', 'rtsp', 'rtspu', 'sip', 'sips', '']
uses_fragment = ['ftp', 'hdl', 'http', 'gopher', 'news',
'nntp', 'wais', 'https', 'shttp', 'snews',
'file', 'prospero', '']
# Characters valid in scheme names
scheme_chars = ('abcdefghijklmnopq... |
amsn/amsn2 | amsn2/plugins/core.py | Python | gpl-2.0 | 2,184 | 0.009615 | # plugins module for amsn2
"""
Plugins with amsn2 will be a subclass of the aMSNPlugin() class.
When this module is initially imported it should loa | d the plugins from the last session. Done in the init() proc.
Then the GUI should call plugins.loadPlugin(name) or plugins.unLoadPlugin(name) in order to deal with plugins.
"""
# init()
# Called when the plugins module is imported (only for the first time).
# Should find plugins and populate a list ready for getPlugin... | n_name)
# Called (by the GUI or from init()) to load a plugin. plugin_name as set in plugin's XML (or from getPlugins()).
# This loads the module for the plugin. The module is then responsible for calling plugins.registerPlugin(instance).
def loadPlugin(plugin_name):
"""
@type plugin_name: str
"""
pass... |
sam-m888/gprime | gprime/plug/menu/__init__.py | Python | gpl-2.0 | 1,579 | 0 | #
# gPrime - A web-based genealogy program
#
# Copyright (C) 2008 Brian G. Matherly
#
# 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; ei | ther version 2 of the License, or
# (at your ) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA... |
joaormatos/anaconda | mmfparser/data/chunkloaders/actions/__init__.py | Python | gpl-3.0 | 749 | 0.001335 | # Copyright (c) Mathias Kaerlev 2012.
# This file is part of Anaconda.
# Anaconda 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.
# ... | e hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNE | SS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Anaconda. If not, see <http://www.gnu.org/licenses/>.
from mmfparser.data.chunkloaders.actions.names import * |
bobbyphilip/learn_python | google-python-exercises/basic/wordcount.py | Python | apache-2.0 | 3,007 | 0.006651 | #!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
"""Wordcount exercise
Google's Python class
The main() below is already defined and comp... | ys
def parse_file(filename):
word_dict= {}
file = open(filename)
for f in file:
words = f.split()
for word in words:
word = word.lower()
| if word in word_dict:
value = word_dict.get(word)
word_dict[word] = value+1
else:
word_dict[word] = 1
file.close()
return word_dict
def print_words(filename):
word_dict = parse_file(filename)
keys = sorted(word_dict.keys())
for key in k... |
yezune/kicomav | Engine/plugins/macro.py | Python | gpl-2.0 | 19,013 | 0.017935 | # -*- coding:utf-8 -*-
"""
Copyright (C) 2013 Nurilab.
Author: Kei Choi(hanul93@gmail.com)
This program 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.
This program is distributed in the hope that it... | ·Î ¾Æ´Ô
if ord(data[9]) == 0x01 and ord(data[10]) == 0x01 :
# ¿¢¼¿ 97 or ¿öµå 97
mac_pos = struct.unpack('<L', data[0xB:0xB+4])[0] + 0x4F
mac_pos += (struct.unpack('<H', data[ma | c_pos:mac_pos+2])[0] * 16) + 2
mac_pos += struct.unpack('<L', data[mac_pos:mac_pos+4])[0] + 10
mac_pos += struct.unpack('<L', data[mac_pos:mac_pos+4])[0] + 81
mac_pos = struct.unpack('<L', data[mac_pos:mac_pos+4])[0] + 60
else :
# ¿¢¼¿ 2000 or ¿öµå 2000 ÀÌ»ó
... |
rebolinho/liveit.repository | script.video.F4mProxy/lib/f4mUtils/datefuncs.py | Python | gpl-2.0 | 2,355 | 0.005096 | # Author: Trevor Perrin
# See the LICENSE file for legal information regarding use of this file.
import os
#Functions for manipulating datetime objects
#CCYY-MM-DDThh:mm:ssZ
def parseDateClass(s):
year, month, day = s.split("-")
day, tail = day[:2], day[2:]
hour, minute, second = tail[1:].split(... | jarray
| def createDateClass(year, month, day, hour, minute, second):
c = java.util.Calendar.getInstance()
c.setTimeZone(java.util.TimeZone.getTimeZone("UTC"))
c.set(year, month-1, day, hour, minute, second)
return c
def printDateClass(d):
return "%04d-%02d-%02dT%02d:%02d:%02... |
mimepp/umspx | htdocs/umsp/plugins/eyetv/eyetv-controller.py | Python | gpl-3.0 | 1,293 | 0.037123 | #!/usr/bin/env python
#-*- coding: UTF-8 -*-
from BaseHTTPServer import BaseHTTPRe | questHandler, HTTPServer
import subprocess, time
last_ch = 0
class TvServerHandler(BaseHTTPRequestHandler):
def do_GET(self):
global last_ch
cmd = self.path.split('/')
if 'favicon.ico' in cmd:
return
ch = int(cmd[1])
if not ch or ch < 1:
ch = 1
if ch == last_ch... | I dummy eyetv:// --sout='#std{access=http,mux=ts,dst=<your ip>:8484}' --sout-keep --autocrop --intf dummy --eyetv-channel=%s" % ch
p = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,close_fds=True)
time.sleep(0.5)
self.send_response(301)
self.send_header("Locati... |
ddimensia/RaceCapture_App | autosportlabs/uix/track/racetrackview.py | Python | gpl-3.0 | 1,499 | 0.007338 | import kivy
kivy.require('1.9.1')
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.uix.scatter import Scatter
from kivy.app import Builder
from kivy.metrics import dp
from kivy.graphics import Color, Line
from autosportlabs.racecapture.geo.geopoint i... | ath(self, key):
self.ids.trackmap.remove_path(key)
def add_heat_va | lues(self, key, heat_values):
self.ids.trackmap.add_heat_values(key, heat_values)
def remove_heat_values(self, key):
self.ids.trackmap.remove_heat_values(key)
|
bx5974/sikuli | sikuli-script/src/test/python/test_hotkey.py | Python | mit | 1,110 | 0.034234 | import unittest
from sikuli import *
from java.awt.event import KeyEvent
from javax.swing | import JFrame
not_pressed = True
WAIT_TIME = 4
def pressed(event):
global not_pressed
not_pressed = False
print "hotkey pressed! %d %d" %(event.modifiers,event.keyCode)
class TestHotkey(unittest.TestCase):
def testAddHotkey(self):
self.assertTrue(Env.addHotkey(Key.F6, 0, pressed))
def testAddHo... | t_pressed
Env.addHotkey(Key.F6, 0, pressed)
self.assertTrue(not_pressed)
count = 0
while not_pressed and count < WAIT_TIME:
count += 1
wait(1)
keyDown(Key.F6)
keyUp(Key.F6)
self.assertFalse(not_pressed)
#f.dispose()
def testRemoveHotkey(self):... |
Capricoinofficial/Capricoin | contrib/bitrpc/bitrpc.py | Python | mit | 7,842 | 0.038128 | from jsonrpc import ServiceProxy
import sys
import string
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:22713")
else:
access = Se... | ons (optional): ")
incemp = raw_input("Include empty? (true/false, optional): ")
try:
print access.listreceivedbyaccount(mc, incemp)
except:
prin | t access.listreceivedbyaccount()
except:
print "\n---An error occurred---\n"
elif cmd == "listreceivedbyaddress":
try:
mc = raw_input("Minimum confirmations (optional): ")
incemp = raw_input("Include empty? (true/false, optional): ")
try:
print access.listreceivedbyaddress(mc, incemp)
except:
print a... |
NicovincX2/Python-3.5 | Physique/Physique quantique/Mécanique quantique/principe_de_superposition_lineaire.py | Python | gpl-3.0 | 1,519 | 0.003333 | # -*- coding: utf-8 -*-
import os
"""
Illustration d'un exercice de TD visant à montrer l'évolution t | emporelle de la
densité de probabilité pour la superposition équiprobable d'un état n=1 et
d'un état n quelconque (à fixer) pour le puits quantique infini.
Par souci de simplicité, on se débrouille pour que E_1/hbar = 1
"""
import numpy as np # Boîte à outils numériques
import matplotlib.pyplot as plt ... | ver (à fixer)
n = 2
# On met tous les paramètres à 1 (ou presque)
t0 = 0
dt = 0.1
L = 1
hbar = 1
h = hbar * 2 * np.pi
m = (2 * np.pi)**2
E1 = h**2 / (8 * m * L**2)
En = n * E1
x = np.linspace(0, L, 1000)
def psi1(x, t):
return np.sin(np.pi * x / L) * np.exp(1j * E1 * t / hbar)
def psin(x, t):
return np.si... |
gazpachoking/Flexget | flexget/components/managed_lists/lists/regexp_list/cli.py | Python | mit | 5,302 | 0.003584 | from __future__ import unicode_literals, division, absolute_import
import re
from argparse import ArgumentParser, ArgumentTypeError
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
from flexget import options
from flexget.event import event
from flexget.terminal import TerminalTable, Te... | f regexp list to operate on', default='regexps'
)
# Register subcommand
parser = options.register_command('regexp-list', do_cli, help='View and manage regexp lists')
# Set up our subparsers
subparsers = parser.add_subparsers(title='actions', metavar='<action>', dest='regexp_action') |
subparsers.add_parser('all', parents=[table_parser], help='Shows all existing regexp lists')
subparsers.add_parser(
'list', parents=[list_name_parser, table_parser], help='List regexp from a list'
)
subparsers.add_parser(
'add', parents=[list_name_parser, regexp_parser], help='Add a reg... |
luzeduardo/antonov225 | flyer/flyerapp/migrations/0008_auto_20150630_1859.py | Python | gpl-2.0 | 924 | 0.002165 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('flyerapp', '0007_auto_20150629_1135'),
]
operations = [
| migrations.AddField(
model_name='schedule',
name='logic_delete',
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name='flight',
name='pub_date',
field=models.DateTimeField(default=datetime.datetime(20... | te published'),
),
migrations.AlterField(
model_name='schedule',
name='pub_date',
field=models.DateTimeField(default=datetime.datetime(2015, 6, 30, 18, 59, 57, 180807), null=True, verbose_name=b'date published'),
),
]
|
hackupc/backend | applications/apps.py | Python | mit | 506 | 0.001976 | from __future__ import unicode_literals
from django.apps import AppConfig
class ApplicationsConfig(AppConfig):
name = 'applications'
def ready(self):
super(ApplicationsConfig, self).ready()
from applications.signals import create_draft_application, clean_draft_application, \
auto... | file_on_delete
create_draft_application
clean_draft_application
auto_delete_f | ile_on_change
auto_delete_file_on_delete
|
pyfa-org/eos | eos/eve_obj/custom/self_skillreq/__init__.py | Python | lgpl-3.0 | 3,165 | 0.000632 | # ==============================================================================
# Copyright (C) 2011 Diego Duclos
# Copyright (C) 2011-2018 Anton Vorobyov
#
# This file is part of Eos.
#
# Eos is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as publi... | os.const.eve import AttrId
from eos.const.eve import EffectId
from eos.eve_obj.effect import EffectFactory
from .modifier import make_drone_dmg_modifiers
from .modifier import make_missile_dmg_modifiers
from .modifier import make_missile_rof_modifiers
logger = getLogger(__name__)
def add_missile_rof_modifiers(effec... | effect.modifiers = make_missile_rof_modifiers()
effect.build_status = EffectBuildStatus.custom
def _add_missile_dmg_modifiers(effect, attr_id):
if effect.modifiers:
msg = f'missile self skillreq damage effect {effect.id} has modifiers, overwriting them'
logger.warning(msg)
effect.modifiers... |
andrefbsantos/Tuxemon | tuxemon/core/components/log.py | Python | gpl-3.0 | 1,644 | 0.000608 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Tuxemon
# Copyright (C) 2014, William Edwards <shadowapex@gmail.com>,
# Benjamin Bean <superman2k5@gmail.com>
#
# This file is part of Tuxemon.
#
# Tuxemon is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Pu... | ARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Tuxemon. If not, see <http://www.gnu.org/licenses/>.
#
# Contributor(s):
#
# Wi... | onfig = Config.Config()
loggers = {}
# Set up logging if the configuration has it enabled
if config.debug_logging == "1":
for logger_name in config.loggers:
# Enable logging
logger = logging.getLogger(logger_name)
logger.setLevel(int(config.debug_level))
log_hdlr = logging.StreamH... |
intuinno/vistalk | yelpvis/models.py | Python | mit | 881 | 0.026107 | from django.db import models
from django.core.urlresolvers import reverse
from jsonfield import JSONField
import collections
# Create your models here.
class YelpvisState(models.Model):
title=models.CharField(max_length=255)
slug=models.SlugField(unique=True,max_length=255)
description = models.CharField(max_lengt... | content=models.TextField()
published=models.BooleanField(default=True)
created=models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created']
def __unicode__(self):
return u'%s' % self.title
def get_absolute_url(self):
return reverse('blog:post', args=[self.slug])
class Y | elpvisCommentState(models.Model):
content=models.TextField()
pub_date = models.DateTimeField(auto_now_add=True)
vis_state = JSONField()
class Meta:
ordering = ['-pub_date']
def __unicode__(self):
return self.content |
fernandog/Medusa | tests/legacy/db_tests.py | Python | gpl-3.0 | 1,788 | 0.001119 | # coding=UTF-8
# Author: Dennis Lutter <lad1337@gmail.com>
#
# This file is part of Medusa.
#
# Medusa 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... | = ? AND location != ''", [0000])
class DBMultiTests(test.AppTestDBCase):
"""Perform multi-threaded test of the database."""
def setUp(self):
"""Unittest set up."""
super(DBMultiTests, self).setUp()
self.db = test.db.DBConnection()
def select(self):
"""Select from the data... | e database."""
for _ in range(4):
thread = threading.Thread(target=self.select)
thread.start()
|
dstrockis/outlook-autocategories | lib/unit_tests/test__helpers.py | Python | apache-2.0 | 6,951 | 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, ... | ne()
self.assertRaises(NotImplementedError, lambda: mixin.path)
def test_client_is_abstract(self):
mixin = self._make_one()
self.assertRaises(NotImplementedError, lambda: mixin.client)
def test_reload(self):
connection = _Connection({'foo': 'Foo'})
client = _Client(conn... | nges is not a set, so we can observe a change.
derived._changes = object()
derived.reload(client=client)
self.assertEqual(derived._properties, {'foo': 'Foo'})
kw = connection._requested
self.assertEqual(len(kw), 1)
self.assertEqual(kw[0]['method'], 'GET')
self.ass... |
DreamerBear/awesome-py3-webapp | www/biz/__init__.py | Python | gpl-3.0 | 181 | 0 | #!/usr/bin/env python | 3
# -*- coding: utf-8 -*-
# @Date : 2017/10/18 17:13
# @Author : xxc727xxc (xxc727xxc@foxmail.com)
# @Version : 1.0.0
i | f __name__ == '__main__':
pass
|
globocom/database-as-a-service | dbaas/physical/migrations/0025_auto__add_field_diskoffering_available_size_kb.py | Python | bsd-3-clause | 11,926 | 0.00763 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as 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 'DiskOffering.available_size_kb'
db.add_column(u'physical_... | ed.ForeignKey', [], {'to': u"orm['physical.Host']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}),
| 'hostname': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'monitor_url': ('django.db.models.fields.URLField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}),
... |
erwan-lemonnier/klue-microservice | pymacaron/resources.py | Python | bsd-2-clause | 1,638 | 0.003053 | from pymacaron.log import pymlogger
import multiprocessing
from math import ceil
from pymacaron.config import get_config
log = pymlogger(__name__)
# Calculate resources available on this container hardware.
# Used by pymacaron-async, pymacaron-gcp and pymacaron-docker
def get_gunicorn_worker_count(cpu_count=None):... | run on this container hardware"""
if cpu_count:
return cpu_count * 2 + 1
return multiprocessing.cpu_count() * 2 + 1
def get_celery_worker_count(cpu_count=None):
"""Return the number of celery workers to run on this container hardware"""
conf = get_config()
if hasattr(conf, 'worker_count')... | essing.cpu_count() * 2
# Minimum worker count == 2
if c < 2:
c == 2
return c
# Memory required, in Mb, by one gunicorn or celery worker:
GUNICORN_WORKER_MEM = 400
CELERY_WORKER_MEM = 200
def get_memory_limit(default_celery_worker_count=None, cpu_count=None):
"""Return the memory in Megabytes ... |
freedomboxtwh/Plinth | plinth/modules/help/help.py | Python | agpl-3.0 | 2,917 | 0 | #
# This file is part of Plinth.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribute... |
content = input_file.read()
except IOError:
raise Http404
return TemplateResponse(
request, 'help_manual.html',
{'title': _('{box_name} Manual').format(box_name=_(cfg.bo | x_name)),
'content': content})
def status_log(request):
"""Serve the last 100 lines of plinth's status log"""
num_lines = 100
with open(cfg.status_log_file, 'r') as log_file:
data = log_file.readlines()
data = ''.join(data[-num_lines:])
context = {
'num_lines': num_lines,... |
jwvhewitt/dmeternal | old_game/container.py | Python | gpl-2.0 | 8,515 | 0.00916 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2012 Anne Archibald <peridot.faceted@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation... | plementedError
def __radd__(self, other):
raise NotImplementedError
def __imul__(self,other):
raise NotImplementedError
def __m | ul__(self, other):
raise NotImplementedError
def __rmul__(self,other):
raise NotImplementedError
# only works if other is not also a Container
def __iadd__(self, other):
self.extend(other)
return self
def __setitem__(self, key, value):
# FIXME: check slices work... |
MediffRobotics/DeepRobotics | DeepLearnMaterials/tutorials/tensorflowTUT/tf5_example2/for_you_to_practice.py | Python | gpl-3.0 | 640 | 0.010938 | # View more python tutorial on my Youtube and Youku channel!!!
# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial
"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
... | .3
### create tensorflo | w structure start ###
### create tensorflow structure end ###
# Very important
for step in range(201):
pass
|
avicorp/firstLook | src/algorithms/check_input_fields.py | Python | apache-2.0 | 11,258 | 0.004264 | # ---Libraries---
# Standard library
import os
import sys
import math
# Third-party libraries
import cv2
import numpy as np
import scipy.ndimage as ndimage
# Private libraries
import compute_OBIFs
import color_BIFs
sys.path.append(os.path.abspath("../"))
import utils
template_png='algorithms/inputFields/template.pn... | [0] - template.shape[0] / 2), int(searchMap.shape[1] - template.shape[1] / 2)]
radios = [int(template.shape[0] / 2), int(template.shape[1] / 2)]
maxConv = threshold
maxCenterConv = [0, 0]
for centerConvX in range(fromIndex[0], toIndex[0]):
for centerConvY in range(fromIndex[1], toIndex[1]):
... | - radios[0]:centerConvX + radios[0] + template.shape[0]%2,
centerConvY - radios[1]:centerConvY + radios[1] + template.shape[1]%2] \
* template
conv = np.sum(convMatrix)
if maxConv < conv:
maxConv = conv
... |
wbinventor/openmc | docs/sphinxext/notebook_sphinxext.py | Python | mit | 3,717 | 0.001345 | import sys
import os.path
import re
import time
from docutils import io, nodes, statemachine, utils
try:
from docutils.utils.error_reporting import ErrorString # the new way
except ImportError:
from docutils.error_reporting import ErrorString # the old way
from docutils.parsers.rst import Directive, con... | ce, nb_node.line) = \
self.state_machine.get_source_and_line(self.lineno)
return [nb_node]
class notebook(nodes.raw):
| pass
def visit_notebook_node(self, node):
self.visit_raw(node)
def depart_notebook_node(self, node):
self.depart_raw(node)
def setup(app):
app.add_node(notebook,
html=(visit_notebook_node, depart_notebook_node))
app.add_directive('notebook', Notebook)
|
chriscallan/Euler | Probs_1_to_50/028_NumberSpiralDiagonals.py | Python | gpl-3.0 | 3,489 | 0.004013 | # Problem 28
# Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
#
# 21 22 23 24 25
# 20 7 8 9 10
# 19 6 1 2 11
# 18 5 4 3 12
# 17 16 15 14 13
#
# It can be verified that the sum of the numbers on the diagonals is 101.
#
# What is the sum of the n... | w += 1
if my_grid[candidate_row][candidate_col - 1] == 0:
current_direction = fill_directions.left
elif current_direction == fill_directions.left and my_grid[candidate_row][candidate_col - 1] == 0:
candidate_col -= 1
if my_grid[candidate_row - 1][candidate_col... | andidate_row -= 1
if my_grid[candidate_row][candidate_col + 1] == 0:
current_direction = fill_directions.right
else:
raise Exception("current_direction wasn't in the enum of possible directions: {0}".format(current_direction))
except IndexError as idxExc:
brea... |
openatv/enigma2 | lib/python/Plugins/Extensions/DVDBurn/Process.py | Python | gpl-2.0 | 37,027 | 0.02536 | from __future__ import print_function
from __future__ import absolute_import
from Components.Task import Task, Job, DiskspacePrecondition, Condition, ToolExistsPrecondition
from Components.Harddisk import harddiskmanager
from Screens.MessageBox import MessageBox
from .Project import iso639language
import Tools.Notifica... | ERROR: couldn't detect Audio PID (projectx too old?)")
def haveNewFile(self, file):
print("[DemuxTask] produced file:", file, self.currentPID)
self.generated_files.append(file)
if self.currentPID in self.relevantAudioPIDs:
self.mplex_audiofiles[self.currentPID] = file
elif file.endswith("m2v"):
self.mpl... | ress(self, progress):
#print "PROGRESS [%s]" % progress
MSG_CHECK = "check & synchronize audio file"
MSG_DONE = "done..."
if progress == "preparing collection(s)...":
self.prog_state = 0
elif progress[:len(MSG_CHECK)] == MSG_CHECK:
self.prog_state += 1
else:
try:
p = int(progress)
p = p - 1... |
magenta/magenta | magenta/models/improv_rnn/improv_rnn_create_dataset.py | Python | apache-2.0 | 2,205 | 0.004082 | # Copyright 2022 The Magenta 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | 'are populated with SequenceExample protos.')
flags.DEFINE_float(
'eval_ratio', 0.1,
'Fraction of input to set aside for eval set. Partition is randomly '
'selected.')
flag | s.DEFINE_string(
'log', 'INFO',
'The threshold for what messages will be logged DEBUG, INFO, WARN, ERROR, '
'or FATAL.')
def main(unused_argv):
tf.logging.set_verbosity(FLAGS.log)
config = improv_rnn_config_flags.config_from_flags()
pipeline_instance = improv_rnn_pipeline.get_pipeline(
config... |
ucldc/harvester | harvester/post_processing/run_transform_on_couchdb_docs.py | Python | bsd-3-clause | 3,271 | 0.002446 | '''This allows running a bit of code on couchdb docs.
code should take a json python object, modify it and hand back to the code
Not quite that slick yet, need way to pass in code or make this a decorator
'''
import importlib
from harvester.collection_registry_client import Collection
from harvester.couchdb_init import... | # get collection description
if cjson['@id'] in C_CACHE:
c = C_CACHE[cjson['@id']]
else:
c = Collection(url_api=cjson['@id'])
C_CACH | E[cjson['@id']] = c
doc['originalRecord']['collection'][0]['rights_status'] = c['rights_status']
doc['originalRecord']['collection'][0]['rights_statement'] = c['rights_statement']
doc['originalRecord']['collection'][0]['dcmi_type']=c['dcmi_type']
if 'collection' in doc['sourceResource']:
doc['so... |
anttttti/Wordbatch | wordbatch/pipelines/apply.py | Python | gpl-2.0 | 2,258 | 0.030558 | #!python
from __future__ import with_statement
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import pandas as pd
import wordbatch.batcher
def decorator_apply(func, batcher=None, cache=None, vectorize=None):
def wrapper_func(*args, **kwargs):
return Appl... | f= lru_cache(maxsize=args[4])(f)
#Applying per D | ataFrame row is very slow, use ApplyBatch instead
if isinstance(args[0], pd.DataFrame): return args[0].apply(lambda x: f(x, *f_args, **f_kwargs), axis=1)
return [f(row, *f_args, **f_kwargs) for row in args[0]]
class Apply(object):
#Applies a function to each row of a minibatch
def __init__(self, function, batcher... |
jszymon/pacal | tests/examples/makerep.py | Python | gpl-3.0 | 5,081 | 0.011415 | import os
#os.system("python D:\prog\python_packages\pyreport-0.3.4c\pyreport\pyreport.py -e -l -s --type pdf D:\m_\\ecPro\pacal\\trunk\pacal\\examples\\functions.py")
#os.system("python D:\prog\python_packages\pyreport-0.3.4c\pyreport\pyreport.py -e -l -s --type pdf D:\m_\\ecPro\pacal\\trunk\pacal\\examples\\how_to_... | xamples\\dependent\\depvars_demo.py")
#os.system("D:\\prog\\Python27\\python D:\prog\python_packages\pyreport-0.3.4c\pyreport\pyreport.py -e -l --type html D:\\m_\\ecPro\\pacal\\trunk\\pacal\\examples\\dependent\\two_variables\\order_stats.py")
#os.system("D:\\prog\\Python27\\python D:\prog\python_packages\pyreport... | hon_packages\pyreport-0.3.4c\pyreport\pyreport.py -e -l --type html D:\\m_\\ecPro\\pacal\\trunk\\pacal\\examples\\dependent\\two_variables\\resistors.py")
#os.system("D:\\prog\\Python27\\python D:\prog\python_packages\pyreport-0.3.4c\pyreport\pyreport.py -e -l --type html D:\\m_\\ecPro\\pacal\\trunk\\pacal\\examples\\... |
tombstone/models | research/object_detection/models/ssd_mobilenet_v1_fpn_feature_extractor_tf1_test.py | Python | apache-2.0 | 8,728 | 0.001948 | # Copyright 2018 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... | p_shape = [(2, 40, 40, 256), (2, 20, 20, 256),
(2, 10, 10, 256), (2, 5, 5, 256),
(2, 3, 3, 256)]
self.check_extract_features_returns_correct_shape(
2, image_height, image_width, depth_multiplier, pad_to_multiple,
expected_feature_ma... | tract_features_returns_correct_shape(
2, image_height, image_width, depth_multiplier, pad_to_multiple,
expected_feature_map_shape, use_explicit_padding=True,
use_keras=False)
def test_extract_features_returns_correct_shapes_enforcing_min_depth(
self):
image_height = 256
image_wi... |
soasme/rio | rio/blueprints/api_1.py | Python | mit | 139 | 0 | # -*- coding: utf-8 -*-
"""
rio.blueprints.api_1
~~~~~~~~ | ~~~~~~~~~~~~~
"""
from | flask import Blueprint
bp = Blueprint('api_1', __name__)
|
greven/vagrant-django | project_name/settings/dev.py | Python | bsd-3-clause | 233 | 0.012876 | from .base import *
DEBUG = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
try:
from .local import *
except ImportError:
pass
MIDDLEWARE_CLASSES += [
| 'de | bug_toolbar.middleware.DebugToolbarMiddleware',
]
|
jordanemedlock/psychtruths | temboo/core/Library/Utilities/Encoding/Base64Encode.py | Python | apache-2.0 | 3,302 | 0.00424 | # -*- coding: utf-8 -*-
###############################################################################
#
# Base64Encode
# Returns the specified text or file as a Base64 encoded string.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");... | riate for specifying the inputs to the Base64Encode
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
def set_Text(self, value):
"""
| Set the value of the Text input for this Choreo. ((conditional, string) The text that should be Base64 encoded. Required unless providing a value for the URL input.)
"""
super(Base64EncodeInputSet, self)._set_input('Text', value)
def set_URL(self, value):
"""
Set the value of the UR... |
marhar/cx_OracleTools | cx_PyOracleLib/cx_OracleObject/Statements.py | Python | bsd-3-clause | 5,193 | 0.000193 | """Define statements for retrieving the data for each of the types."""
CONSTRAINTS = """
select
o.owner,
o.constraint_name,
o.constraint_type,
o.table_name,
o.search_condition,
o.r_owner,
o.r_constraint_name,
o.delete_rule,
... | from %(p_ViewPrefix)s_tab_partitions o
%(p_WhereClause)s
order by o.partition_position"""
TRIGGERS = """
select
o.owner,
o.trigger_name,
o.table_name,
o.description, |
o.when_clause,
o.action_type,
o.trigger_body
from %(p_ViewPrefix)s_triggers o
%(p_WhereClause)s
order by o.owner, o.trigger_name"""
USERS = """
select
o.username,
o.default_tablespace,
o.temporary_tablespace
from dba_u... |
heibanke/python_do_something | Code/Chapter5/base_classic_new_class.py | Python | apache-2.0 | 596 | 0.028523 | #!/usr/bin/python
# -*- coding: utf-8 -*-
class A:
#classic class
"""this is class A"""
pass
__slots__=('x','y')
def test(self):
# classic class test
"""this is A.test()"""
print "A class"
class B(object):
#ne | w class
"""this is class B"""
__slots__=('x','y')
pass
def test(self):
# new class test
"""this is B.test()"""
print "B class | "
if __name__ == '__main__':
a=A()
b=B()
print dir(a)
print dir(b)
#a.x=1
#b.x=1
#help(a)
#help(b) |
ukBaz/python-bluezero | bluezero/peripheral.py | Python | mit | 6,857 | 0 | """Classes required to create a Bluetooth Peripheral."""
# python-bluezero imports
from bluezero import adapter
from bluezero import advertisement
from bluezero import async_tools
from bluezero import localGATT
from bluezero import GATT
from bluezero import tools
logger = tools.create_module_logger(__name__)
class... | lf.characteristics = []
self.descriptors = []
self.primary_services = []
self.dongle = adapter.Adapter(adapter_address)
self.local_name = local_name
self.appearance = appearance
self.advert = advertisement.Advertisement(1, 'peripheral')
self.ad_manager = advertise... | vertisingManager(adapter_address)
self.mainloop = async_tools.EventLoop()
def add_service(self, srv_id, uuid, primary):
"""
Add the service information required
:param srv_id: integer between 0 & 9999 as unique reference
:param uuid: The Bluetooth uuid number for this servi... |
axelleonhart/TrainingDjango | materiales/apps/clientes/forms.py | Python | lgpl-3.0 | 2,527 | 0.002777 | from django import forms
from apps.clientes.models import Cliente
from apps.clientes.choices import SEXO_CHOICES
import re
class ClienteForm(forms.ModelForm):
"""
Se declaran los campos y atributos que se mostraran en el formulario
"""
sexo = forms.ChoiceField(choices=SEXO_CHOICES, required=... | 'direccion': 'Dirección',
'email': 'Email',
'fecha_nac': 'Fecha de Nacimiento',
}
widgets = {
'nombre': forms.TextInput(attrs={'class': 'form-control'}),
'direccion': forms.TextInput(attrs={'class': 'form-control'}),
'email': forms.E... | ': 'form-control'}),
}
def clean_nombre(self):
"""
Valida que el nombre no sea menor a 3 caracteres
"""
nombre_lim = self.cleaned_data
nombre = nombre_lim.get('nombre')
if len(nombre) < 5:
raise forms.ValidationError(
... |
lejenome/my_scripts | scan_wifi.py | Python | gpl-2.0 | 2,384 | 0.001678 | #!/bin/python3
import sys
import os
import tempfile
import pprint
import logging
from logging import debug, info, warning, error
def process_info( | line):
line = line.strip()
arr = line.split(':')
if len(arr) < | 2:
return None, None
key = arr[0]
val = None
if key == "freq":
val = "{}Hz".format(arr[1].strip())
elif key == "signal":
val = "{}%".format(100 + int(float(arr[1].split()[0])))
elif key == "SSID":
val = arr[1].strip()
elif key == 'WPA':
val = True
eli... |
Noirello/PyLDAP | src/bonsai/active_directory/acl.py | Python | mit | 13,344 | 0.000749 | import struct
import uuid
from enum import IntEnum
from typing import List, Optional, Set
from .sid import SID
class ACEFlag(IntEnum):
""" ACE type-specific control flags. """
OBJECT_INHERIT = 0x01
CONTAINER_INHERIT = 0x02
NO_PROPAGATE_INHERIT = 0x04
INHERIT_ONLY = 0x08
INHERITED = 0x10
... | HERIT_ONLY": "IO",
"INHERITED": "ID",
"SUCCESSFUL_ACCESS": "SA",
"FAILED_ACCESS": "FA",
}
return short_names[self.name]
class ACEType(IntEnum):
""" Type of the ACE. """
ACCE | SS_ALLOWED = 0
ACCESS_DENIED = 1
SYSTEM_AUDIT = 2
SYSTEM_ALARM = 3
ACCESS_ALLOWED_COMPOUND = 4
ACCESS_ALLOWED_OBJECT = 5
ACCESS_DENIED_OBJECT = 6
SYSTEM_AUDIT_OBJECT = 7
SYSTEM_ALARM_OBJECT = 8
ACCESS_ALLOWED_CALLBACK = 9
ACCESS_DENIED_CALLBACK = 10
ACCESS_ALLOWED_CALLBACK_OB... |
jun-zhang/device-manager | src/lib/ydevicemanager/devices.py | Python | gpl-2.0 | 8,950 | 0.01676 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# StartOS Device Manager(ydm).
# Copyright (C) 2011 ivali, Inc.
# hechao <hechao@ivali.com>, 2011.
__author__="hechao"
__date__ ="$2011-12-20 16:36:20$"
import gc
from xml.parsers import expat
from hwclass import *
class Device:
def __init__(self, dev_xml):
... | ription, self.product, self.vendor, self.version, self.serial)
self.dev_type.setdefault((2, "motherboard"), []).append(motherboard)
elif self.attr["id"] == "firmware" and self.attr["class"] == "memory":
bio | s = Bios(self.description, self.product, self.vendor, self.version, \
self.date, self.size, self.capability)
self.dev_type.setdefault((2, "motherboard"), []).append(bios)
elif self.attr["id"].split(":")[0] == "memory" and self.attr["class"] == "memory":
memory = Memory(sel... |
endlessm/chromium-browser | components/policy/tools/template_writers/writers/android_policy_writer_unittest.py | Python | bsd-3-clause | 3,381 | 0.001479 | #!/usr/bin/env python
# Copyright (c) 2015 The | Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''Unit tests for writers.android_policy_writer'''
import os
import sys
if __name__ == '__main__':
sys.path.append(os.path.join(os.path.dirname(__file__), '../../../..'))
imp... | AndroidPolicyWriterUnittest(writer_unittest_common.WriterUnittestCommon):
'''Unit tests to test assumptions in Android Policy Writer'''
def testPolicyWithoutItems(self):
# Test an example policy without items.
policy = {
'name': '_policy_name',
'caption': '_policy_caption',
'desc': ... |
dirtchild/weatherPi | weatherSensors/windDirection.py | Python | gpl-3.0 | 2,252 | 0.030195 | #!/usr/bin/env python
# reads data from wind direction thingy (see README)
# labels follow those set out in the Wunderground PWS API:
# http://wiki.wunderground.com/index.php/PWS_-_Upload_Protocol
#
# SOURCES:
# RETURNS: two objects for humidity and temperature
# CREATED: 2017-08-02
# ORIGINAL SOURCE: https://github.c... | ig import *
def getReading():
# Choose a gain of 1 for reading voltages from 0 to 4.09V.
# Or pick a different gain to change the range of voltages that are read:
# - 2/3 = +/-6.144V
# - 1 = +/-4.096V
# - 2 = +/-2.048V
# - 4 = +/-1.024V
# - 8 = +/-0.512V
# - 16 = +/-0.256V
# See table 3 in the ... | DS1115 ADC (16-bit) instance and do stuff with it
adc = Adafruit_ADS1x15.ADS1115()
adc.start_adc(CHANNEL, gain=GAIN)
start = time.time()
value = 0
totalVoltage = 0
cnt = 0
#DEBUG
#print("[PRE]adc.get_last_result()[",adc.get_last_result(),"]")
while (time.time() - start) <= 5.0:
# will sometimes give negative... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.