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 |
|---|---|---|---|---|---|---|---|---|
XavierBerger/pcd8544 | examples/dimmer.py | Python | gpl-3.0 | 568 | 0.038732 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import pcd8544.lcd as lcd
import time, os, sys
if not os.geteuid() == 0:
sys.exit('Script must be run as root')
ON, OFF = [1 | , 0]
try:
lcd.init()
lcd.cls()
if ( lcd.LED != 1 ):
sys.exit('LED pin should be GPIO1 (12)')
# Backlight PWM testing -- off -> 25% -> off
for i in range(0,1023,16):
lcd.set_brightness(i)
time.sleep(0.025)
for i in range(1023,0,-16):
| lcd.set_brightness(i)
time.sleep(0.025)
except KeyboardInterrupt:
pass
finally:
lcd.cls()
lcd.backlight(OFF)
|
enthought/glfwpy | examples/03_instanced_drawing.py | Python | bsd-3-clause | 4,686 | 0.002134 | from glfwpy.glfw import *
import sys
import numpy as np
from OpenGL.GL import *
from OpenGL.arrays import ArrayDatatype
import ctypes
vertex = """
#version 330
in vec3 vin_position;
in vec3 vin_color;
uniform vec3 vu_displacement[2];
out vec3 vout_color;
void main(void)
{
vout_color | = vin_color;
gl_Position = vec4(vin_position + vu_displacement[gl_InstanceID], 1.0);
}
"""
fragment = """
#version 330
in vec3 vout_color;
out vec4 fout_color;
void main(void)
{
fout_color = vec4(vout_color, 1.0);
}
"""
vertex_data = np.array([0.75, 0.75, 0.0,
0.75, -0.75, 0.0,
... | array([1, 0, 0,
0, 1, 0,
0, 0, 1], dtype=np.float32)
displacement_data = np.array([-0.1, 0, 0,
0.2, 0, 0.0], dtype=np.float32)
class ShaderProgram(object):
def __init__(self, vertex, fragment, geometry=None):
self.program_id... |
sergak01/Vk_bot | interface/search.py | Python | gpl-3.0 | 4,870 | 0.010625 | # -*- coding: utf-8 -*-
import settings
import random
import vk_api
from BotException import BotException
class Interface:
vk = None
vk_service = None
dynamic_settings = dict()
def __init__(self, vk, vk_service, dynamic_settings):
self.vk = vk
self.dynamic_settings = dynamic_settings
... | ")
if answer_count > 0:
answer = self.vk_service.method(
'wall.search',
{
'owner_id':"-" + str(self.vk.method(
"groups.getById",
{'v': "5.65"})[0].get("id") |
),
'query':str(query),
'owners_only':1,
'count':1,
'offset':random.randint(1, answer_count)
}
)
else:
answer = self.vk_service.method(
... |
francois-vincent/navitia | source/jormungandr/jormungandr/test_settings.py | Python | agpl-3.0 | 964 | 0 | # encoding: utf-8
import logging
# emplacement ou charger les fichier de configuration par instances
INSTANCES_DIR = '/etc/jormungandr.d'
# Start the thread at startup, True | in production, False for test environments
START_MONITORING_THREAD = False
| # chaine de connnection à postgresql pour la base jormungandr
SQLALCHEMY_DATABASE_URI = 'postgresql://navitia:navitia@localhost/jormun_test'
# désactivation de l'authentification
PUBLIC = True
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
# indice de la base de données redis utilisé, entier de 0 à 15 par défaut
REDIS_... |
nicko96/Chrome-Infra | run.py | Python | bsd-3-clause | 872 | 0.00344 | #!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of thi | s source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper for `python -m` to make running tools simpler.
A tool is defined as a python module with a __main__.py file. This latter file
is run by the present script.
In particular, allows gclient to change directories when run... |
import os
import sys
RUNPY_PATH = os.path.abspath(__file__)
ROOT_PATH = os.path.dirname(RUNPY_PATH)
ENV_PATH = os.path.join(ROOT_PATH, 'ENV')
# Do not want to mess with sys.path, load the module directly.
run_helper = imp.load_source(
'run_helper', os.path.join(ROOT_PATH, 'bootstrap', 'run_helper.py'))
sys.exit... |
Avira/pootle | pootle/apps/pootle_language/models.py | Python | gpl-3.0 | 6,196 | 0.003228 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import locale
from col... | e)
################## | ########## Methods ######################################
@property
def direction(self):
"""Return the language direction."""
return language_dir(self.code)
def __unicode__(self):
return u"%s - %s" % (self.name, self.code)
def __init__(self, *args, **kwargs):
super(Lan... |
sixtyfive/pcsc-ctapi-wrapper | PCSC/UnitaryTests/FEATURE_GET_TLV_PROPERTIES.py | Python | lgpl-2.1 | 1,604 | 0.000623 | #! /usr/bin/env python
"""
# FEATURE_GET_TLV_PROPERTIES.py: Unitary test for
# FEATURE_GET_TLV_PROPERTIES
# Copyright (C) 2012,2016 Ludovic Rousseau
"""
# 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 Fre... | 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, see <http://www.gnu.org/licenses/>.
# You have t... | ION_CCID_EXCHANGE_AUTHORIZED bit in the ifdDriverOptions
# option of the CCID driver Info.plist file
from smartcard.System import readers
from smartcard.pcsc.PCSCPart10 import getTlvProperties, SCARD_SHARE_DIRECT
# for each reader
for reader in readers():
print
print "Reader:", reader
card_connection = r... |
pcmoritz/ray-1 | python/ray/tune/examples/pbt_memnn_example.py | Python | apache-2.0 | 10,874 | 0 | """Example training a memory neural net on the bAbI dataset.
References Keras and is based off of https://keras.io/examples/babi_memnn/.
"""
from __future__ import print_function
from tensorflow.keras.models import Sequential, Model, load_model
from tensorflow.keras.layers import Embedding
from tensorflow.keras.laye... | ""Helper method for creating the model"""
| vocab = set()
for story, q, answer in self.train_stories + self.test_stories:
vocab |= set(story + q + [answer])
vocab = sorted(vocab)
# Reserve 0 for masking via pad_sequences
vocab_size = len(vocab) + 1
story_maxlen = max(
len(x) for x, _, _ in self... |
MiniSEC/GRR_clone | lib/aff4_objects/client_stats.py | Python | apache-2.0 | 482 | 0.004149 | #!/usr/bin/env python
# Copyright 20 | 12 Google Inc. All Rights Reserved.
"""AFF4 object representing client stats."""
from grr.lib import aff4
from grr.lib import rdfvalue
from grr.lib.aff4_objects import standard
class ClientStats(standard.VFSDirectory):
"""A container for all client statistics."""
class SchemaCls(standard.VFSDire | ctory.SchemaCls):
STATS = aff4.Attribute("aff4:stats", rdfvalue.ClientStats,
"Client Stats.", "Client stats")
|
hrantzsch/signature-verification | tools/plot_clf.py | Python | gpl-3.0 | 5,362 | 0.000746 | import argparse
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_palette("colorblind")
sns.set_color_codes("colorblind")
def parse(logfile):
loss_train = []
loss_test = []
section_loss = []
acc_train = []
acc_test = []
section_acc = []
mean_diff_train = []
mean_diff_test =... | x, list(map(avg, max_diff_test)), 'g.-')
# axarr[3].set_title("max_diff")
# axarr[1].set_y | lim([0.7, 1.0])
plt.show()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('logfile')
# parser.add_argument('--style', default='avg',
# help="'avg' for average, or 'all'")
args = parser.parse_args()
plot_avg(args.logfile)
# def plot_t... |
mavarick/spider-python | webspider/utils/var2str.py | Python | gpl-2.0 | 6,752 | 0.024629 | # -*- coding: utf-8 -*-
"""
translate variance and its formated character which have regularities
for example:
raw input:
v={'aa': 12345, 'bbbb': [1, 2, 3, 4, {'flag': 'vvvv||||xxxxx'}, set(['y', 'x', 'z'])]}
after `var2str.var2str(v)`
v_str=<aa::12345##bbbb::<1||2||3||4||<flag::vvvv|xxxxx>||<y|||x|||z... | ator
"tuple_sep": "||" # tuple seperator
}
sep_nest = ("<", ">") # better not repeated char, e.x. ("<-", "->")
# internal operations
sep_values = sep_dict.values()
def erase_sep(s):
for v in sep_values:
s = s.replace(v, "")
for v in sep_nest:
s=s.replace(v, "")
return s
_s=sep_nest[0]
_e=... | ect):
@staticmethod
def var2str(var):
if not var: return ""
if type(var) == types.DictType:
result = []
for key,value in var.items():
v_str = var2str.var2str(value)
k_str = erase_sep("{0}".format(key))
result.append("{key}{sep}{value}".format(
... |
liyazhe/AML-Project2 | tests/test_predictor.py | Python | bsd-3-clause | 2,395 | 0.000418 | import os
from unittest import TestCase
from samr import corpus
from samr.predictor import PhraseSentimentPredictor
from samr.data import Datapoint
TESTDATA_PATH = os.path.join(os.path.dirname(__file__), "data")
class TestPhraseSentimentPredictor(TestCase):
def setUp(self):
self.__original_path = corpu... | qual((N - wrong) / N, score)
def test_simple_duplicates(self):
dupe = Datapoint(phraseid="a", sentenceid="b", phrase="b a", sentiment="1")
# Train has a lot of "2" sentiments
train = [Datapoint(phraseid=str(i),
sentenceid=str(i),
phrase=... | 2") for i in range(10)]
train.append(dupe)
test = [Datapoint(*dupe)]
predictor = PhraseSentimentPredictor(duplicates=True)
predictor.fit(train)
predicted = predictor.predict(test)[0]
self.assertEqual(predicted, "1")
|
mlvfx/vfxAssetBox | assetbox/base/plugins/actions.py | Python | cc0-1.0 | 2,772 | 0.001082 | """
Base actions to be use as a template, and to store generic actions.
"""
import os
from assetbox.base.constants import ActionType
from PySide import QtGui
def filename_input(title='Name Input', outputtext='Text: '):
"""
Decorator to add a file dialog input.
Args:
title (str): title of the file... | return func_wrapper
return dialog_decorate
class BaseAction(object):
"""Base Action template, a skeleton for an action."""
name = 'BaseAction'
filetype = 'abc'
actiontype = ActionType.Menu
def __init__(self):
pass
def valid_filetype(self, path, *args):
"""Check the asset... | )
return ext.replace('.', '') == self.filetype
def execute(self):
"""Run the command."""
raise NotImplementedError
class Delete(BaseAction):
"""Delete command that mimics the operating systems delete."""
name = 'Delete'
filetype = 'abc'
@confirm_dialog('Confirm Deletion... |
mcaleavya/bcc | examples/tracing/bitehist.py | Python | apache-2.0 | 1,187 | 0.005055 | #!/usr/bin/python
#
# bitehist.py Block I/O size histogram.
# For Linux, uses BCC, eBPF. Embedded C.
#
# Written as a basic example of using histograms to show a distribution.
#
# A Ctrl-C will print the gathered histogram then exit.
#
# Copyright (c) 2015 Brendan Gregg.
# Licensed under the Apache License, Version 2.... | ("~~~~~~~~~~~~~~")
b["dist"].print_log2_hist("kbytes")
print("\nlinear histogram")
print("~~~~~ | ~~~~~~~~~~~")
b["dist_linear"].print_linear_hist("kbytes")
|
ChristosChristofidis/h2o-3 | h2o-py/tests/testdir_algos/glm/pyunit_link_functions_tweedie_basicGLM.py | Python | apache-2.0 | 1,103 | 0.017226 | import sys
sys.path.insert(1, "../../../")
import h2o
def link_functions_tweedie_basic(ip,port):
# Connect to h2o
h2o.init(ip,port)
print "Read in prostate data."
hdf = h2o.upload_file(h2o.locate("smalldata/prostate/prostate_complete.csv.zip"))
print "Testing for family: TWEEDIE"
print "Set v... | link function tweedie (using precomputed values from R)"
deviance_h2o_tweedie = model_h2o_tweedie.residual_deviance() / model_h2o_tweedie.null_deviance()
assert 0.721452 - deviance_h2o_tweedie <= 0.01, "h2o's residual/null deviance is more than 0.01 lower than R's. h2o: " \
| "{0}, r: {1}".format(deviance_h2o_tweedie, 0.721452)
if __name__ == "__main__":
h2o.run_test(sys.argv, link_functions_tweedie_basic)
|
Naeka/vosae-app | www/organizer/models/embedded/reminder.py | Python | agpl-3.0 | 830 | 0.001205 | # -*- coding:Utf-8 -*-
from mongoengine import EmbeddedDocument, fields
__all__ = (
'ReminderEntry',
'ReminderSettings',
)
class ReminderEntry(EmbeddedDocument):
"""
Per-event reminders settings
"""
METHODS = (
'EMAIL',
'POPUP'
)
method = fields.StringField(choices... | efault = fields.BooleanField(default=True)
overrides = fields.ListField(fields.EmbeddedDocumentField("ReminderEntry"))
class NextReminder(EmbeddedDocument):
at = fields.DateTimeField(required=Tru | e)
threshold = fields.IntField(min_value=0, max_value=21600, required=True)
|
lmregus/Portfolio | python/design_patterns/env/lib/python3.7/site-packages/sphinx/domains/c.py | Python | mit | 12,525 | 0.00008 | """
sphinx.domains.c
~~~~~~~~~~~~~~~~
The C language domain.
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
import string
from docutils import nodes
from sphinx import addnodes
from sphinx.directives import ObjectDescriptio... | , ctype):
# type: (nodes.Element, str) -> None
# add cross-ref nodes for all words
for part in [_f for _f in wsplit_re.split(ctype) if _f]:
tnode = nodes.Text(part, part)
if part[0] in string.ascii_letters + '_' and \
part not in self.sto | pwords:
pnode = addnodes.pending_xref(
'', refdomain='c', reftype='type', reftarget=part,
modname=None, classname=None)
pnode += tnode
node += pnode
else:
node += tnode
def _parse_arglist(self, argli... |
DataONEorg/d1_python | gmn/src/d1_gmn/tests/test_scimeta.py | Python | apache-2.0 | 7,205 | 0.002637 | #!/usr/bin/env python
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (t... | ense.
import io
import pytest
import responses
import d1_common.types.exceptions
import django.test
import d1_gm | n.tests.gmn_test_case
import d1_test.d1_test_case
import d1_test.instance_generator.identifier
import d1_test.instance_generator.system_metadata
@d1_test.d1_test_case.reproducible_random_decorator("TestSciMeta")
class TestSciMeta(d1_gmn.tests.gmn_test_case.GMNTestCase):
def _create_and_check_scimeta(self, client... |
dart-lang/sdk | runtime/tools/bin_to_assembly.py | Python | bsd-3-clause | 5,566 | 0.000719 | #!/usr/bin/env python3
#
# Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
# Generates an assembly source file the defines a symbol with the bytes from
# a ... | tring")
parser.add_option("--executable", action="store_true", default=False)
parser.add_option("--target_os", action="store", type="string | ")
parser.add_option("--size_symbol_name", action="store", type="string")
parser.add_option("--target_arch", action="store", type="string")
parser.add_option("--incbin", action="store_true", default=False)
(options, args) = parser.parse_args()
if not options.output:
sys.stderr.write("--outp... |
Geotexan/calculinn | prototype/muro_geotexan.py | Python | gpl-3.0 | 10,868 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Prototipo de cálculo y recomendación para la aplicación de muros.
"""
from __future__ import print_function
import sys
import argparse
import csv
import re
def main():
"""
Abre los ficheros fuente de cálculo de parámetros y de recomendación de
producto p... | cabará en JavaScript.
"""
res = None
for fila in tabla:
aciertos = []
espesor, angulo, altura, inclinacion, densidad, sobrecarga = fila[:6]
for valor, referencia in ((e, espesor),
(a, angulo),
(h, altura),
... | ,
(d, densidad),
(s, sobrecarga)):
if referencia.isdigit(): # OJO: Solo vale para enteros.
referencia = int(referencia)
resultado = comparar(valor, referencia)
aciertos.append(resultado)
if... |
timkrentz/SunTracker | IMU/VTK-6.2.0/Common/DataModel/Testing/Python/TestTemplates.py | Python | mit | 4,490 | 0.000445 | #!/usr/bin/env python
"""Test template support in VTK-Python
VTK-python decides which template specializations
to wrap according to which ones are used in typedefs
and which ones appear as superclasses of other classes.
In addition, the wrappers are hard-coded to wrap the
vtkDenseArray and vtkSparseArray classe... | a.SetValue(i, value)
result = a.GetValue(i)
self.assertEqual(value, result)
def testArray(self):
"""Test array CreateArray"""
o = vtk.vtkArray.CreateArray(vtk.vtkArray.DENSE, vtk.VTK_DOUBLE)
self.assertEqual(o.__class__, vtk.vtkDenseArray[float... | "
# make sure Rect inherits operators
r = vtk.vtkRectf(0, 0, 2, 2)
self.assertEqual(r[2], 2.0)
c = vtk.vtkColor4ub(0, 0, 0)
self.assertEqual(list(c), [0, 0, 0, 255])
e = vtk.vtkVector['float32', 3]([0.0, 1.0, 2.0])
self.assertEqual(list(e), [0.0, 1.0, 2.0])... |
indrajitr/ansible | lib/ansible/modules/fetch.py | Python | gpl-3.0 | 3,790 | 0.00343 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# This is a virtual module that is entirely implemented as an action plugin and runs on the controller
from __future__ import absolute_import, ... | dule: slurp
author:
- Ansible Core Team
- Michael DeHaan
'''
EXAMPLES = r'''
- name: Store | file into /tmp/fetched/host.example.com/tmp/somefile
fetch:
src: /tmp/somefile
dest: /tmp/fetched
- name: Specifying a path directly
fetch:
src: /tmp/somefile
dest: /tmp/prefix-{{ inventory_hostname }}
flat: yes
- name: Specifying a destination path
fetch:
src: /tmp/uniquefile
dest:... |
shubhamdhama/zulip | tools/lib/test_script.py | Python | apache-2.0 | 3,557 | 0.00253 | import glob
import os
import subprocess
import sys
from distutils.version import LooseVersion
from typing import Iterable, List, Optional, Tuple
from scripts.lib.zulip_tools import get_dev_uuid_var_path
from version import PROVISION_VERSION
ZULIP_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(... | eople that provision--we're all good!
if version == PROVISION_VERSION:
return True, None
# We may be more provisioned than the branch we just moved to. As
# long as the major version hasn't changed, then we should be ok.
if LooseVersion(version) > LooseVersion | (PROVISION_VERSION):
if get_major_version(version) == get_major_version(PROVISION_VERSION):
return True, None
else:
return False, preamble(version) + NEED_TO_DOWNGRADE
return False, preamble(version) + NEED_TO_UPGRADE
def assert_provisioning_status_ok(force: bool) -> None:... |
ionelmc/python-nameless | ci/appveyor-download.py | Python | bsd-2-clause | 3,820 | 0.002094 | #!/usr/bin/env python
"""
Use the AppVeyor API to download Windows artifacts.
Taken from: https://bitbucket.org/ned/coveragepy/src/tip/ci/download_appveyor.py
# Licensed under the Apache Lic | ense: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
"""
from __future__ import unicode_literals
import argparse
import os
import zipfile
import requests
def make_auth_headers():
"""Make the authentication headers needed to use the Appveyor | API."""
path = os.path.expanduser("~/.appveyor.token")
if not os.path.exists(path):
raise RuntimeError(
"Please create a file named `.appveyor.token` in your home directory. "
"You can get the token from https://ci.appveyor.com/api-token"
)
with open(path) as f:
... |
vipins/ccccms | env/Lib/site-packages/cms/models/__init__.py | Python | bsd-3-clause | 3,419 | 0.006727 | # -*- coding: utf-8 -*-
from django.conf import settings as d_settings
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import get_resolver, get_script_prefix, \
NoReverseMatch
from django.utils.encoding import iri_to_uri
from moderatormodels import *
from pagemodel import *
fro... | url = ''
i18n = 'cms.middleware.multilingual.MultilingualURLMiddleware' in settings.MIDDLEWA | RE_CLASSES
lang = None
if isinstance(viewname, basestring) and viewname.split(":")[0] in dict(settings.LANGUAGES).keys():
lang = viewname.split(":")[0]
try:
url = django.core.urlresolvers.old_reverse(viewname, urlconf=urlconf, args=args, kwargs=kwargs, prefix=prefix, ... |
RackSec/ansible | lib/ansible/modules/network/avi/avi_sslkeyandcertificate.py | Python | gpl-3.0 | 5,751 | 0.001217 | #!/usr/bin/python
#
# Created on Aug 25, 2016
# @author: Gaurav Rastogi ([email protected])
# Eric Anderson ([email protected])
# module_check: supported
# Avi Version: 17.1.1
#
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the te... | - Private key.
key_params:
description:
- Sslkeyparams settings for sslkeyandcertificate.
name:
description:
- Name of the object.
required: true
status:
description:
- Enum options - ssl_c | ertificate_finished, ssl_certificate_pending.
- Default value when not specified in API or module is interpreted by Avi Controller as SSL_CERTIFICATE_FINISHED.
tenant_ref:
description:
- It is a reference to an object of type tenant.
type:
description:
- Enum ... |
caleb531/cache-simulator | cachesimulator/word_addr.py | Python | mit | 316 | 0 | #!/usr/bin/env python3
class WordAddress(int):
# Retrieves all consecutive words for the given word address (including
# itself)
de | f get_consecutive_words(self, num_words_per_block):
offset = self % num_words_per_block
return [(self - offset + i) for i i | n range(num_words_per_block)]
|
MichaelYusko/PyGiphy | setup.py | Python | mit | 871 | 0 | from distutils.core import setup
import pygiphy
VERSION = pygiphy.__version__
AUTHOR = pygiphy.__author__
setup_kwargs = {
'name': 'pygiphy',
| 'version': VERSION,
'url': 'https://github.com/MichaelYusko/PyGiphy',
'license': 'MIT',
'author': AUTHOR,
'author_email': '[email protected]',
'description': 'Python interface for the Giphy API',
'packages': ['pygiphy'],
'classifiers': [
'Development Status :: 2 - Pre-Alpha',
... | g Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'License :: OSI Approved :: MIT License'
],
}
requirements = ['requests>=2.13.0']
setup_kwargs['install_requires'] = requirements
setup(**setup_kwargs)
print(u"\n\n\t\t "
"PyGiphy version {} installation succeeded.\n... |
openpolis/op-accesso | project/accesso/users/views.py | Python | bsd-3-clause | 819 | 0.001221 | from django.contrib.auth import get_user_model
from django.views.generic import DetailView
from rest_framework import viewsets
from rest_framework import permissions
from rest_framework.decorators import detail_route, list_route
from rest_framework.response import Response
from .serializers import UserSerializer
clas... | et_user_model()
def get_object(self, | queryset=None):
return self.request.user
# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticated, ]
model = get_user_model()
serializer_class = UserSerializer
@list_route(methods=['get', ])
def me(self, request):
... |
oasisvali/pythonchallenge | ch3.py | Python | apache-2.0 | 390 | 0.020513 | import re
filename = "equality.html"
f = open(filename,'r')
dump = f.read()
results = re.findall(r'<!--(.*?)-->',dump,re.DOTALL)
print results[1]
chrlist = re.findall(r'[a-z][A-Z]{3}([a-z])[A-Z]{3}[a-z]',results[1])
chrdict = {} |
for charac in chrlist:
if charac in chrdict:
chrdict[charac] +=1
else:
| chrdict[charac] = 1
print ''.join(chrdict.keys()+['i','l'])
f.close()
|
jgliss/pyplis | scripts/ex03_plume_background.py | Python | gpl-3.0 | 11,609 | 0 | # -*- coding: utf-8 -*-
#
# Pyplis is a Python library for the analysis of UV SO2 camera data
# Copyright (C) 2017 Jonas Gliß ([email protected])
#
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License a
# published by the Free Software Foundati... | ume.meta["texp"],
dark, offset)
# Model dark image for tExp of background image
dark_bg = pyplis.image.model_dark_image(bg.meta["texp"],
dark, offset)
plume.subtract_dark_image(dark_plume)
| bg.subtract_dark_image(dark_bg)
# Blur the images (sigma = 1)
plume.add_gaussian_blurring(1)
bg.add_gaussian_blurring(1)
# Create vignetting correction mask from background image
vign = bg.img / bg.img.max() # NOTE: potentially includes y & x gradients
plume_vigncorr = pyplis.Img(plume.img / v... |
jaeilepp/mne-python | mne/channels/tests/test_montage.py | Python | bsd-3-clause | 22,545 | 0 | # Author: Teon Brooks <[email protected]>
#
# License: BSD (3-clause)
import os.path as op
import warnings
from nose.tools import assert_equal, assert_true, assert_raises
import numpy as np
from scipy.io import savemat
from numpy.testing import (assert_array_equal, assert_almost_equal,
... | with open(fname, 'w') as fid:
fid.write(text)
montage = read_montage(fname)
if kind in ('sfp', 'txt'):
assert_true('very_very_very_long_name' in montage.ch_names)
assert_equal(len(montage.ch_names), 4)
assert_equal(len(montage.ch_names), len(montage.pos))
... | type = [('label', 'S4'), ('theta', 'f8'), ('phi', 'f8'),
('radius', 'f8'), ('x', 'f8'), ('y', 'f8'), ('z', 'f8'),
('off_sph', 'f8')]
try:
table = np.loadtxt(fname, skip_header=2, dtype=dtype)
except TypeError:
table = np.l... |
OBIGOGIT/etch | binding-python/runtime/src/main/python/etch/binding/util/StrStrHashMapSerializer.py | Python | apache-2.0 | 2,642 | 0.006435 | """
# 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... | d them
@param typ
@param class2type
"""
field = typ.getField(cls.FIELD_NAME)
class2type.put( StrStrHashMap , typ )
| typ.setComponentType( StrStrHashMap )
typ.setImportExportHelper( StrStrHashMapSerializer(typ, field))
typ.putValidator(field, Validator_object.get(1))
typ.lock()
def __init__(self, typ, field):
self.__type = typ
self.__field = field
def importHe... |
faunalia/processing_addons | ogr2ogrdifference.py | Python | agpl-3.0 | 6,648 | 0.003008 | # -*- coding: utf-8 -*-
"""
***************************************************************************
clipbypolygon.py
---------------------
Date : November 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
***********************... | :
fieldstring = ""
if multi:
sqlstring = "-sql \"SELECT (ST_Multi(ST_Differe | nce(g1." + geomColumnA + ",ST_Union(g2." + geomColumnB + "))))::geometry(MultiPolygon) AS geom, g1. " + fieldA + " AS id_input" + fieldstring + " FROM " + layernameA + " AS g1, " + layernameB + " AS g2 GROUP BY g1." + geomColumnA + ",g1." + fieldA + "\""" -nln " + table + " -lco SCHEMA=" + schema + " -lco FID=gid -nlt ... |
ella/mypage | mypage/widgets/forms.py | Python | bsd-3-clause | 384 | 0.005208 | from django import forms
class BaseDisplayForm(forms.Form):
pass
class BaseConfig | Form(forms.Form):
pass
class FieldChoice(object):
def __init__(self, choice, is_checked):
self.choice = choice
self.is_checked = is_checked
@property
def name(self):
| return self.choice[1]
@property
def value(self):
return self.choice[0]
|
ianmilliken/rwf | backend/apps/farmwork/forms.py | Python | apache-2.0 | 1,542 | 0.001297 | #
# farmwork/forms.py
#
from django import forms
from django.utils.text import slugify
from .models import Farmwork
# ========================================================
# FARMWORK FORM
# ========================================================
class FarmworkForm(forms.ModelForm):
def __init__(self, *args... | pay',
'job | _pay_type',
'job_start_date',
'job_duration',
'job_duration_type',
'job_description',
'con_first_name',
'con_surname',
'con_number',
'con_email',
'con_description',
'acc_variety',
'acc_pri... |
hoffmabc/OpenBazaar | features/steps/ws.py | Python | mit | 2,130 | 0 | import logging
from behave import given, then, when
from node.openbazaar_daemon import MarketApplication
from test_util import (
get_db_path,
ip_address,
node_uri,
node_to_ws_port,
set_store_description,
storeDescription,
ws_connect,
ws_receive_myself,
ws_send
)
@given('there is ... | es):
create_connected_nodes(context, int(num_nodes))
@given('{num_nodes} nodes')
def step_impl(context, num_nodes):
create_nodes(context, int(num_nodes))
@when('node {i} connects to node {j}')
def step_impl(context, i, j):
ws_send(int(i), 'connect', {'uri': node_uri(int(j))})
@then('node {i} is conn | ected to node {j}')
def step_impl(context, i, j):
i = int(i)
j = int(j)
response = ws_receive_myself(i)['result']
assert response['type'] == 'myself'
assert(node_uri(j) in [x['uri'] for x in response['peers']])
@then('node {i} can query page of node {j}')
def step_impl(context, i, j):
guid_j ... |
insequent/quark | quark/tests/functional/plugin_modules/test_subnets.py | Python | apache-2.0 | 12,282 | 0 | # Copyright 2013 Openstack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | KIND, either express or implied. See the
# License for# the specific language governing permissions and limitations
# under the License.
import mock
import netaddr
from neutron.common import exceptions
from oslo.config import cfg
impor | t contextlib
from quark.db import api as db_api
import quark.ipam
# import below necessary if file run by itself
from quark import plugin # noqa
import quark.plugin_modules.ip_policies as policy_api
import quark.plugin_modules.networks as network_api
import quark.plugin_modules.subnets as subnet_api
from quark.tests.... |
heibanke/python_do_something | Code/Chapter4/homework4-2_ex.py | Python | apache-2.0 | 2,080 | 0.025784 | #!/usr/bin/env python
# coding: utf-8
#copyRight by heibanke
import csv
import re
import pprint
def readData():
csvfile = open('beijing_jt.csv','r')
reader = csv.reader(csvfile)
reader.next()
result={}
while True:
try:
jt_info = reader.next()
ex... | mp in stations:
#print tmp[0],tmp[1].strip()
station_list.append(tmp[1].strip())
result[jt_info[1]]=station_list
csvfile.close()
return result
def find_station(s,stations):
line_list=[]
for k,v in stations.iteritems():
if unicode(s,'utf-... | nt unicode(l[0],'utf-8'),unicode(l[1],'utf-8'),u"中转站:",l[2]
if __name__=="__main__":
stations=readData()
print u"请输入你想查询的起始站名:"
start_station = raw_input()
start_lines=find_station(start_station,stations)
print u"请输入你想查询的终点站名:"
end_station = raw_input()
end_lines=find_station(e... |
cruor99/KivyMD | kivymd/spinner.py | Python | mit | 4,907 | 0.000408 | # -*- coding: utf-8 -*-
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ListProperty, BooleanProperty
from kivy.animation import Animation
from kivymd.theming import ThemableBehavior
Builder.load_string('''
<MDSpinner>:
canvas.before:
PushMatri... | .determinate_time,
t='in_out_quad')
_angle_start_anim.bind(on_complete=lambda *x: \
self._alpha_anim_out.start(self | ))
_angle_start_anim.start(self)
def _start_loop(self, *args):
if self._alpha == 0:
_rot_anim = Animation(_rotation_angle=0,
duration=2,
t='linear')
_rot_anim.start(self)
self._alpha = 1
se... |
AssembleSoftware/IoTPy | IoTPy/agent_types/actuators_simple.py | Python | bsd-3-clause | 930 | 0.004301 | def print_from_queue(q): |
"""
prints values read from queue q to
standard out.
"""
while True:
v = q.get()
if v is None:
# exit loop
return
else:
print (str(v))
class queue_to_file(object):
"""
self.actuate(a) puts values from a queue q
into the file ... | ilename = filename
self.timeout = timeout
def actuate(self, q):
with open(self.filename, 'w') as the_file:
while True:
try:
v = q.get(timeout=self.timeout)
except:
# No more input for this actuator
... |
philanthropy-u/edx-platform | openedx/features/course_duration_limits/migrations/0001_initial.py | Python | agpl-3.0 | 1,719 | 0.004654 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-11-08 19:43
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('cours... | .PROTECT, to=settings.AUTH_USER_MODEL, verbose_name='Changed by')),
('course', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='course_overviews.CourseOverview')),
('site', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.del... | 'abstract': False,
},
),
]
|
tejoesperanto/pasportaservo | hosting/forms/visibility.py | Python | agpl-3.0 | 11,039 | 0.002446 | from django import forms
from django.db.models import (
BinaryField, BooleanField, Case, CharField, Q, Value, When,
)
from django.utils.functional import cached_property
from django.utils.html import format_html
from django.utils.translation import ugettext_lazy as _
from ..models import (
Place, VisibilitySet... | :
return value_without_invalid_marker(self.data)
def clean_visible_in_book(self):
"""
The in_book venue is manipulated manually in form init, so that the
checkbox appears as "off" when place is not offered for accommodation,
independently of its actual value.
The... | ;
otherwise the database will be updated with the "off" value.
"""
venue = next(self.venues('in_book'))
if venue.field.disabled:
return self.obj.visibility[venue.venue_name]
else:
return self.cleaned_data['visible_in_book']
def save(self, commit=True)... |
acdha/django-modeltranslation | modeltranslation/utils.py | Python | bsd-3-clause | 4,065 | 0.001968 | # -*- coding: utf-8 -*-
from contextlib import contextmanager
from django.utils.encoding import force_unicode
from django.utils.translation import get_language as _get_language
from django.utils.functional import lazy
from modeltranslation import settings
def get_language():
"""
Return an active language co... | ce('-', '_' | )))
def _build_localized_verbose_name(verbose_name, lang):
return u'%s [%s]' % (force_unicode(verbose_name), lang)
build_localized_verbose_name = lazy(_build_localized_verbose_name, unicode)
def _join_css_class(bits, offset):
if '-'.join(bits[-offset:]) in settings.AVAILABLE_LANGUAGES + ['en-us']:
r... |
AlienCowEatCake/ImageViewer | src/ThirdParty/Exiv2/exiv2-0.27.5-Source/tests/tiff_test/test_tag_compare.py | Python | gpl-3.0 | 6,645 | 0.003612 | # -*- coding: utf-8 -*-
import system_tests
class OutputTagExtract(metaclass=system_tests.CaseMeta):
"""
Test whether exiv2 -pa $file and exiv2 -pS $file produces the same output.
"""
def parse_pa(self, stdout):
"""
Parse the output of exiv2 -pa $file, which looks like this:
... | Short 1 RGB
Exif.Image.DocumentName Ascii 24 /home/ahuggel/mini9.tif
Exif.Image.ImageDescription Ascii 18 Created with GIMP
Exif.Image.StripOffsets Long 1 8
Exif.Image.Orientation Short 1 top, left
Exif.Im... | hort 1 3
Exif.Image.RowsPerStrip Short 1 64
Exif.Image.StripByteCounts Long 1 243
Exif.Image.XResolution Rational 1 72
Exif.Image.YResolution Rational 1 72
Exif.Image.PlanarConfiguration Short ... |
GigaSpaces-ProfessionalServices/cloudify-openstack-plugin | nova_plugin/userdata.py | Python | apache-2.0 | 1,696 | 0.00059 | #########
# Copyright (c) 2015 GigaSpaces Technologies 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... | ype not in userdata_handlers:
raise exceptions.NonRecoverableError(
"Invalid type '{0}' for server userdata)".format(ud_type))
existing_userdata = userdata_handlers[ud_type](existing_userdata)
if not existing_userdata:
final_userdata = install_agent_userdata
elif not... | serdata, install_agent_userdata])
server['userdata'] = final_userdata
userdata_handlers = {
'http': lambda params: requests.get(params['url']).text
}
|
milisarge/toxfs | webserver.py | Python | gpl-3.0 | 3,418 | 0.043924 | # -*- coding: utf-8 -*-
from flask import Flask
from flask import Flask,jsonify, request, Response, session,g,redirect, url_for,abort, render_template, flash
from islem import *
from bot import *
import sys
import time
import datetime
reload(sys)
sys.setdefaultencoding("utf-8")
app = Flask(__name__)
toxbot = tox_fac... | anasayfa</a>
</html>'''
dosya_bek_son = datetime.datetime.now()
krono=dosya_bek_son-dosya_bek_bas
if krono.total_seconds() > 6 :
break
else:
print "dlist sonucu bekleniyor.",krono.total_seconds()
if 'fno' in request.args and 'dosya' in request.args:
islem.fno = request.args.get('fno')
d... |
islem.dosyala(komut_dosyasi)
cevap_geldi=False
while not cevap_geldi:
time.sleep(0.5)
#md5sum kontrol
if os.path.exists(karsi_dosyalar):
cevap=open(karsi_dosyalar,"r").read()
if cevap =="dosya_inme_tamam":
cevap_geldi=True
os.remove(karsi_dosyalar)
return "dosya geldi statikte"
e... |
IfcOpenShell/IfcOpenShell | test/run.py | Python | lgpl-3.0 | 14,053 | 0.00861 | ###############################################################################
# #
# This file is part of IfcOpenShell. #
# #
... | if not os.path.exists(os.path.join("input",fn)): zf.extract(fn,"input")
zf.close()
else: self.fn = [self.fn]
for fn in self.fn:
print ("[Notice] Rendering:",fn)
succes = subprocess.call(['blender','-b','-P','bpy.py','render',os.path.join("input",fn)]) == ... | lsruher Institut fuer Technologie
TestFile("http://iai-typo3.iai.fzk.de/www-extern-kit/fileadmin/download/download-vrsys/ADT-FZK-Haus-2005-2006.zip")
TestFile("http://iai-typo3.iai.fzk.de/www-extern-kit/fileadmin/download/download-vrsys/Nem-FZK-Haus-2x3.zip")
TestFile("http://iai-typo3.iai.fzk.de/www-extern-kit/fileadm... |
ymap/aioredis | aioredis/commands/generic.py | Python | mit | 11,140 | 0 | from aioredis.util import wait_convert, wait_ok, _NOTSET, _ScanIter
class GenericCommandsMixin:
"""Generic commands mixin.
For commands details see: http://redis.io/commands/#generic
"""
def delete(self, key, *keys):
"""Delete a key."""
fut = self.execute(b'DEL', key, *keys)
... | n self.execute(b'DUMP', key)
def exists(self, key, *keys):
"""Check if key(s) exists.
.. versionchanged:: v0.2.9
Accept multiple keys; **return** type **changed** from bool to int.
"""
return self.execute(b'EXISTS', key, *keys)
def expire(self, key, timeout):
... | ed to int and passed to `pexpire` method.
Otherwise raises TypeError if timeout argument is not int.
"""
if isinstance(timeout, float):
return self.pexpire(key, int(timeout * 1000))
if not isinstance(timeout, int):
raise TypeError(
"timeout argume... |
polyaxon/polyaxon | platform/coreapi/polyaxon/apis/apps.py | Python | apache-2.0 | 1,334 | 0 | #!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, 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 ... | sort: skip_file
from django.apps import AppConfig
class APIsConfig(AppConfig):
name = "apis"
verbose_name = "APIs"
def ready(self):
from polycommon import conf
from polycommon import auditor
from coredb import executor, operations
from polycommon import query
con... | tup()
executor.validate_and_setup()
auditor.validate_and_setup()
import coredb.signals.runs # noqa
import polycommon.options.conf_subscriptions # noqa
from polycommon.events import auditor_subscriptions # noqa
from coredb.administration import register # noqa
|
USGSDenverPychron/pychron | pychron/processing/permutator/view.py | Python | apache-2.0 | 2,784 | 0 | # =============================== | ================================================
# Copyright 201 | 4 Jake Ross
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distribute... |
GNOME/gnome-schedule | src/data.py | Python | gpl-2.0 | 3,607 | 0.013862 | # data.py: Contains the backend to the gconf database
# Copyright (C) 2004, 2005 Philip Van Hoof <me at pvanhoof dot be>
# Copyright (C) 2004 - 2009 Gaute Hope <eg at gaute dot vetsj dot com>
# Copyright (C) 2004, 2005 Kristof Vansant <de_lupus at pandora dot be>
#
# This program is free software; you can redistribut... | sion 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 Library General Public Lice | nse 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.
#pygtk modules
import gconf
#python modules
import os
#gnome-schedule
import conf... |
assisi/assisipy-examples | remote_sensors/spoke.py | Python | lgpl-3.0 | 3,590 | 0.0039 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
for all "spoke" CASUs, they emit when reading one specific directional
IR sensor.
set the direction that is sensed by the -d flag, from NESW
this is borrowed from `examples/targeted_messaging`, with server setup
that happens behind the scenes (i.e. from RTC files!)
... | 2 or self.__casu.get_range(casu.IR_BR) < 2)):
self.__casu.set_diagnostic_led_rgb(1, 0, 0, casu.DLED_TOP)
self.old_state = self.state
self.state = 'Red On'
# South => blue
elif self._ctr_dir == 'S' and self.__casu.get_... | |
gersakbogdan/fsnd-conference | settings.py | Python | apache-2.0 | 494 | 0.002024 | #!/usr/bin/env python
"""settings.py
Udacity conference server-side Python App Engine | app user settings
$Id$
created/forked from conference.py by wesc on 2014 may 24
"""
# Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = '54751868361-i018plbnbgq80kdro99rqk3qt12d07pk.apps.googleusercontent.com'
ANDROID_CLIENT_ID = 'replace with Android cl... | _AUDIENCE = WEB_CLIENT_ID
|
cgstudiomap/cgstudiomap | main/local_modules/frontend_shop/__openerp__.py | Python | agpl-3.0 | 1,388 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) cgstudiomap <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms... | ',
'license': 'AGPL-3',
'category': 'Web',
'summary': 'Shop Modules',
'depends': [
'website',
'website_m | enu_by_user_status',
],
'data': [
'templates/template_shop.xml',
'data/website_menus.xml',
],
'installable': True,
}
|
JetChars/vim | vim/bundle/python-mode/pymode/libs3/rope/base/stdmods.py | Python | apache-2.0 | 1,296 | 0.003086 | import os
import sys
from rope.base import utils
def _stdlib_path():
import inspect
return os.path.dirname(inspect.getsourcefile(inspect))
@utils.cached(1)
def standard_modules():
return python_modules() | dynload_modules()
@utils.cached(1)
def python_modules():
result = set()
lib_path = _stdli... | ath):
for name in os.listdir(lib_path):
path = os.path.join(lib_path, name)
if os.path.isdir(path):
if '-' not in name:
result.add(name)
else:
if name.endswith('.py'):
result.add(name[:-3])
return res... | = os.path.join(_stdlib_path(), 'lib-dynload')
if os.path.exists(dynload_path):
for name in os.listdir(dynload_path):
path = os.path.join(dynload_path, name)
if os.path.isfile(path):
if name.endswith('.so') or name.endswith('.dll'):
if "cpython" in... |
geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/third_party/WebKit/Tools/Scripts/webkitpy/common/net/git_cl_unittest.py | Python | gpl-3.0 | 3,618 | 0.000553 | # Copyright 2016 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.
import unittest
from webkitpy.common.net.git_cl import GitCL
from webkitpy.common.system.executive_mock import MockExecutive2
from webkitpy.common.host_mock... | f test_run(self):
host = MockHost()
host.executive = MockExecutive2(output='mock-output')
git_cl = GitCL(host)
output = git_cl.run(['command'])
| self.assertEqual(output, 'mock-output')
self.assertEqual(host.executive.calls, [['git', 'cl', 'command']])
def test_run_with_auth(self):
host = MockHost()
host.executive = MockExecutive2(output='mock-output')
git_cl = GitCL(host, auth_refresh_token_json='token.json')
git_cl.... |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.4/Lib/test/test_optparse.py | Python | mit | 57,004 | 0.001281 | #!/usr/bin/python
#
# Test suite for Optik. Supplied by Johannes Gijsbers
# ([email protected]) -- translated from the original Optik
# test suite to this PyUnit-based version.
#
# $Id: test_optparse.py,v 1.10 2004/10/27 02:43:25 tim_one Exp $
#
import sys
import os
import copy
import unittest
from cStringIO im... | expected_help:
raise self.failureException(
'help text failure; expected:\n"' +
expected_help + '"; got:\n"' +
actual_help + '"\n')
# -- Test make_option() aka Option ---- | ---------------------------------
# It's not necessary to test correct options here. All the tests in the
# parser.parse_args() section deal with those, because they're needed
# there.
class TestOptionChecks(BaseTest):
def setUp(self):
self.parser = OptionParser(usage=SUPPRESS_USAGE)
def assertOptio... |
pelson/conda-build-all | conda_build_all/tests/unit/test_artefact_destination.py | Python | bsd-3-clause | 5,716 | 0.002274 | from argparse import Namespace
from contextlib import contextmanager
import logging
import mock
import os
import sys
import unittest
from conda_build_all.tests.unit.dummy_index import DummyIndex, DummyPackage
from conda_build_all.artefact_destination import (ArtefactDestination,
... | _exists = mock.patch('conda_build_all.inspect_binstar.distribution_exists', return_value=on_owner)
d | ist_exists_on_channel = mock.patch('conda_build_all.inspect_binstar.distribution_exists_on_channel', return_value=on_channel)
with dist_exists:
with dist_exists_on_channel:
yield
def test_not_already_available_not_just_built(self):
client, owner, channel = [mock.sentinel... |
gloryofrobots/obin | arza/misc/strutil.py | Python | gpl-2.0 | 5,908 | 0.001523 | from arza.misc.platform import (runicode, rarithmetic, rstring)
from arza.runtime import error
from arza.types import api, space
def get_line(string, line_no):
index = -1
for _ in range(line_no - 1):
index = string.index('\n', index + 1)
try:
last_index = string.index('\n', index + 1)
... | builder.append(u'\t')
elif ch == 'n':
builder.append(u'\n')
elif ch == 'r':
builder.append(u'\r')
elif ch == 'v':
builder.append(u'\v')
elif ch == 'a':
builder.append(u'\a')
elif '0' <= ch <= '7':
x = ord(ch) - ord('0')... | = (x << 3) + ord(ch) - ord('0')
if pos < size:
ch = s[pos]
if '0' <= ch <= '7':
pos += 1
x = (x << 3) + ord(ch) - ord('0')
builder.append(unichr(x))
# hex escapes
# \xX... |
WoLpH/zfs-utils-osx | zfs_utils_osx/zpool.py | Python | bsd-3-clause | 3,142 | 0.000318 | import sys
import subprocess
import textwrap
import decimal
from . import constants
from . import utils
from . import argparse_utils
def zpool_command(args):
context = vars(args)
effective_image_count = constants.ZPOOL_TYPES[args.type](args.count)
context['image_size'] = args.size / effective_image_count
... | ext['postfix'] %= context
context['i'] = 0
context['name'] = constants.IMAGE_NAME % context
context['extra_args'] = ''
print textwrap.fill(constants.ZPOOL_CREATE_MESSAGE % context)
devices = []
for i in range(args.count):
context['i'] = i
context['name'] = constants.IMAGE_NAME %... | if args.overwrite:
arg = '-ov'
else:
arg = ''
utils.execute(context, constants.ZPOOL_CREATE_IMAGE_COMMAND, arg)
except subprocess.CalledProcessError:
print 'Unable to create a new image'
sys.exit(1)
try:
... |
0--key/lib | portfolio/Python/scrapy/tigerchef/tigerchefspider.py | Python | apache-2.0 | 2,126 | 0.006585 | from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, HtmlResponse
from scrapy.utils.respo | nse import get_base_url
from scrapy.utils.url import urljoin_rfc
from product_spiders.items import Product, ProductLoader
class TigerChefSpider(BaseSpider):
name = 'tigerchef.com'
allowed_domains = ['tigerchef.com']
start_urls = ('http://www.tigerchef.com',)
def parse(self, respon | se):
hxs = HtmlXPathSelector(response)
#categories = hxs.select('//div[@class="sidebar_nav"]//li/a/@href').extract()
categories = hxs.select('//div[@class="navigation"]/ul/li/a/@href').extract()
categories += hxs.select('//ul[@class="cl_subs"]//a/@href').extract()
loaded = Fals... |
chris-barry/i2py | i2py/control/pyjsonrpc/rpcjson.py | Python | mit | 1,916 | 0.017745 | #!/usr/bin/env python
# coding: utf-8
import json as _json
JsonParseError = ValueError
# Default-Parameters for the *dumps*-function
dumps_skipkeys = False
dumps_ensure_ascii = True
dumps_check_circular = True
dumps_allow_nan = True
dumps_cls = None
dumps_indent = None
dumps_separators = None
dumps_encoding = "utf-8... | j):
"""
Replacement function for *json.dumps*
Uses the predefined default settings.
"""
return _json.dumps(
obj,
skipkeys = dumps_skipkeys,
ensure_ascii = dumps_ensure_ascii,
check_ci | rcular = dumps_check_circular,
allow_nan = dumps_allow_nan,
cls = dumps_cls,
indent = dumps_indent,
separators = dumps_separators,
encoding = dumps_encoding,
default = dumps_default,
sort_keys = dumps_sort_keys
)
def loads(s):
"""
Replacement functio... |
lnls-fac/sirius | pymodels/TS_V03_03/__init__.py | Python | mit | 474 | 0.00211 |
from .lattice import default_optics_mode
from .lattice import energy
from .accelerator import default_vchamber_on
from .accelerator import default_radiation_on
from .accelerator import accelerator_data
from .accelerator import create_accelerator
from .families import get_family_data
from .families import family_mapp... | a['lattice_version']
| |
n3wb13/OpenNfrGui-5.0-1 | lib/python/Plugins/Extensions/NFR4XBoot/ubi_reader/ubifs/__init__.py | Python | gpl-2.0 | 2,189 | 0.000914 | import re
import struct
from ubifs.defines import *
from ubifs import nodes
from ubifs.nodes imp | ort extract
from ubifs.log import log
class ubifs:
def __init__(self, ubifs_file):
self.log = log()
self._file = ubifs_file
self._sb_node = extract.sb_node(self, UBIFS_COMMON_HDR_SZ)
self._min_io_size = self._sb_node.min_io_size
self._leb_size = self._sb_node.leb_... | return self._file
file = property(_get_file)
def _get_superblock(self):
return self._sb_node
superblock_node = property(_get_superblock)
def _get_master_node(self):
return self._mst_node
master_node = property(_get_master_node)
def _get_master_node2(se... |
tballas/IRC2LCD | Python/IRC2LCD.py | Python | mit | 2,965 | 0.030691 | #! /usr/bin/env python
#
# IRC2LCD
# Tim Ballas
#
"""IRC bot to display mentions on an LCD through a Parallax Propeller.
Usage: IRCbot2LCD.py <server[:port]> <channel> <nicknameToMonitor> <COMport> <optional bot nickname>
"""
#
# Modified from:
# Example program using irc.bot.
# Joel Rosdahl <[email protected]>
#
imp... | ):
c.join(self.channel)
def on_pubmsg(self, c, e):
pubmsgTemp = e.arguments[0] # e.arguments[0] is the public message we are proce | ssing, loaded into "pubmsgTemp"
pattern = re.compile(r'(.*{0}([|_][a-z0-9]+)?(\s|$).*|.*{1}([|_][a-z0-9]+)?:.*)'.format(MonitorNick,MonitorNick)) # Compile Regular Expression to check if the public message has our MonitorNick in it
result = re.search(pattern, pubmsgTemp) # Execute Regular Expression
if result: # ... |
newhouseb/MatTex | mattex.py | Python | mit | 582 | 0.012027 | #!/usr/bin/env python
import sys, re
output = open(sys.argv[1] | )
output = output.read()
output = re.split('thisisalinebreak =',output)
f = open(sys.argv[2])
i = 1
matlab = False
for line in f:
if line == "<?ml\n":
matlab = True
j = 0
for oline in output[i].split('\n'):
if (j > 2) & (re.match('^(\s+[^\s]+|[^=]+)$',oline) != None):
... | matlab:
print line,
|
tsheasha/fullerite | src/diamond/collectors/vmstat/vmstat.py | Python | apache-2.0 | 1,796 | 0.001114 | # coding=utf-8
"""
Uses /proc/vmstat to collect data on virtual memory manager
#### Dependencies
* /proc/vmstat
"""
import diamond.collector
import os
import re
class VMStatCollector(diamond.collector.Collector):
PROC = '/proc/vmstat'
MAX_VALUES = {
'pgpgin': diamond.collector.MAX_COUNTER,
... | default_config(self):
"""
Returns the default collector settings
"""
config = super(VMStatCollector, self).get_default_config()
config.update({
'path': 'vmstat'
})
return config
def collect(self):
if not os.acce | ss(self.PROC, os.R_OK):
return None
results = {}
# open file
file = open(self.PROC)
exp = '^(pgpgin|pgpgout|pswpin|pswpout|pgmajfault)\s(\d+)'
reg = re.compile(exp)
# Build regex
for line in file:
match = reg.match(line)
if mat... |
xcgd/auth_saml | model/auth_saml.py | Python | agpl-3.0 | 2,907 | 0 | # -*- encoding: utf-8 -*-
from openerp.osv import fields
from openerp.osv import osv
import lasso
import simplejson
class auth_saml_provider(osv.osv):
"""Class defining the configuration values of an Saml2 provider"""
_name = 'auth.saml.provider'
_description = 'SAML2 provider'
_order = 'name'
| def _get_lasso_for_provider(self, | cr, uid, provider_id, context=None):
"""internal helper to get a configured lasso.Login object for the
given provider id"""
provider = self.browse(cr, uid, provider_id, context=context)
# TODO: we should cache those results somewhere because it is
# really costly to always recre... |
aligoren/pyalgo | move_to_front_algo.py | Python | mit | 857 | 0.003501 | from __future__ import print_function
from string import ascii_lowercase
SYMBOLTABLE = list(ascii_lowercase)
def move2front_encode(strng, symboltable):
sequence, pad = [], symboltable[::]
for char in strng:
indx = p | ad.index(char)
sequence.append(indx)
pad = [pad.pop(indx)] + pad
return sequence
def move2front_decode(sequence, symboltable):
chars, pad = [], symboltable[::]
for indx in sequence:
char = pad[indx]
chars.append(char)
pad = [pad.pop(indx)] + pad
return ''.join(ch... | print('%14r encodes to %r' % (s, encode), end=', ')
decode = move2front_decode(encode, SYMBOLTABLE)
print('which decodes back to %r' % decode)
|
magomez96/AdamTestBot | src/Community/utils.py | Python | mit | 2,356 | 0.003396 | import csv
import os
from pydblite import Base
def convertcsv2db(csvpath, dbpath): #Converts a CSV file to a PyDBLite database
db = Base(dbpath)
try:
csvfile = open(csvpath, 'rb')
except csv.Error:
print("Could not open CSV file at " + csvpath + "\n")
reader = csv.reader(csvfile)
he... | if db(userID=recName):
rec = db(userID=recName).pop()
if not rec['liked']:
| db.update(rec, liked=row['liked'])
else:
tmpLiked = rec['liked']
tmpLiked += " " + row['liked']
db.update(rec, liked=tmpLiked)
if not rec['history']:
db.update(rec, histor... |
chongdashu/puzzlescript-analyze | python/simulator.py | Python | mit | 248 | 0.032258 | __author__ = 'Chong-U L | im, [email protected]'
import uinput
def Simulator():
def __init__(self):
pass
def test1(self):
device = uinput.Device([uinput.KEY_E, uinput.KEY_H, uinput.KEY_L, uinput.KEY_O])
device.emit_click(ui | nput.KEY_H)
|
socialplanning/WSSEAuth | wsseauth/tests/test_w3dtf.py | Python | gpl-3.0 | 497 | 0.022133 | from datetime import *
from wsseauth import parse_w3dtf
def test_w3dtf():
| d1 = '2007-07-16T15:46:07.507379Z'
d2 = '2007-07-16T05:16:07.507379+10:30'
expected = datetime(2007, 7, 16, 15, 46, 7) #that's the expected utc time
local_timezone_offset = datetime.utcnow() - datetime.now() #.. or so
expected_local = expected - local_timezone_offset
assert parse_w3dtf(d1) - exp... | ert parse_w3dtf(d2) - expected_local < timedelta(0,1,0)
|
Cladis/wikilabels | wikilabels/wsgi/util.py | Python | mit | 2,938 | 0.005106 | import os
from functools import lru_cache, wraps
from itertools import chain
import uglipyjs
from flask import current_app, request
def read_param(request, param, default=None, type=str):
try:
value = request.args.get(param, request.form.get(param, default))
return type(value.strip())
except ... | return "".join(open(static_file_path(path)).read()
for path in static_paths)
def build_script_tags(static_paths, config):
return "".join('<script src="{0}"></script>'\
.format(static_path(path, config))
for path in static_paths)
def build_style_tags(sta... | ="text/css" href="{0}" />'\
.format(static_path(path, config))
for path in static_paths)
def app_path(path, config):
return path_join("/", config['wsgi']['application_root'], path)
def static_path(path, config):
return app_path(path_join("static", path), config)
def url_... |
ambv/flake8-bugbear | tests/b303_b304.py | Python | mit | 705 | 0 | """
Should emit:
B303 - on line 25
B304 - on line 42
"""
import sys
import something_else
def this_is_okay( | ):
something_else.maxint
maxint = 3
maxint
maxint = 3
def this_is_also_okay():
maxint
class CustomClassWithBrokenMetaclass:
__metaclass__ = type
maxint = 5 # this is okay
# the following shouldn't crash
(a, b, c) | = list(range(3))
# it's different than this
a, b, c = list(range(3))
(
a,
b,
c,
) = list(range(3))
# and different than this
(a, b), c = list(range(3))
a, *b, c = [1, 2, 3, 4, 5]
b[1:3] = [0, 0]
def this_is_also_fine(self):
self.maxint
def this_is_... |
JaapJoris/autodidact | autodidact/views/decorators.py | Python | agpl-3.0 | 3,963 | 0.002271 | from functools import wraps
from django.shortcuts import get_object_or_404, redirect
from django.http import Http404, HttpResponseForbidden, HttpResponseBadRequest
from autodidact.models import *
def needs_course(view):
@wraps(view)
def wrapper(request, course_slug, *args, **kwargs):
if isinstance(cour... | Course object required')
if isinstance(session_nr, Session):
session = session_nr
else:
session_nr = int(se | ssion_nr)
session = course.sessions.filter(number=session_nr).first()
if session is None:
raise Http404()
if not session.active and not request.user.is_staff:
raise Http404()
return view(request, course, session, *args, **kwargs)
return wra... |
EugeneHasJeans/EugeneHasJeans.github.io | documents/lifelines.py | Python | agpl-3.0 | 799 | 0.032541 | import time
import RPi.GPIO as GPIO
GPIO.VERSION
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11,GPIO.OUT)
GPIO.setup(12,GPIO.OUT)
from smbus import SMBus
bus = SMBus(1)
def read_ain(i):
global bus
#bus.write_byte_data(0x48, 0x40 | ((i) & 0x03), 0)
bus.write_byte(0x48, i)
bus.read_byte(0x48)#first 2 are l... | state, and last state repeated.
bus.read_byte(0x48)
return bus.read_byte(0x48)
while(True):
alcohol = read_ain(2)*0.001
heartrate = read_ain( | 1)
print "-------------------------\n"
print("Alcohol Sensor: {0:.3f}%".format(alcohol))
if(heartrate<60) or (heartrate>100):
GPIO.output(11,0)
GPIO.output(12,1)
else:
GPIO.output(11,1)
GPIO.output(12,0)
print("Heart Rate Sensor: {0:.0f} BPM\n".format(heartrate))
time.sleep(1)#sec
|
jenaiz/Crawly | common/__init__.py | Python | mit | 149 | 0.006711 | #!/usr/bin/env python
# enco | ding: utf-8
"""
__init__.py
Created by on 2012-06-08.
Copyright (c) 2012 __MyCompanyName__. Al | l rights reserved.
"""
|
mce35/agocontrol | devices/rrdtool/RRDtool.py | Python | gpl-3.0 | 3,622 | 0.022916 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# python-rrdtool, rrdtool bindings for Python.
# Based on the rrdtool Python bindings for Python 2 from
# Hye-Shik Chang <[email protected]>.
#
# Copyright 2012 Christian Jurk <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# ... | ool.OperationalError('RRD file is read-only: {!s}' \
.format(self.filename))
elif not isinstance(values, (list, tuple)):
raise rrdtool.ProgrammingError('The v | alues parameter must be a ' \
'list or tuple')
else:
for row in values:
if isinstance(row, str):
vl.append(row)
elif isinstance(row, (list, tuple)):
if len(row) < 2:
raise rrdtool.ProgrammingError('Value {!r} has too ' \
'few elements in sequence object'.format(row))
else:... |
pinterest/kingpin | examples/test_service_client.py | Python | apache-2.0 | 1,287 | 0.000777 | #!/usr/bin/python
#
# Copyright 2016 Pinterest, 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... | ,
timeout=3000,
poo | l_size=10,
always_retry_on_new_host=True)
print testservice_client.ping()
|
Alphadelta14/XCSV | xcsv/__init__.py | Python | mit | 152 | 0 |
from wrapper | import parse_header, safe_parse_header, XCSVDialect
__all__ = ["parse_header", "safe_parse_header", "XCSVDialect"]
__versio | n__ = "0.2.4"
|
depop/kombu | kombu/tests/mocks.py | Python | bsd-3-clause | 4,240 | 0 | from __future__ import absolute_import
from itertools import count
import anyjson
from kombu.transport import base
class Message(base.Message):
def __init__(self, *args, **kwargs):
self.throw_decode_error = kwargs.get('throw_decode_error', False)
super(Message, self).__init__(*args, **kwargs)
... | self, *args, **kwargs):
self._called('exchange_declare')
def prepare_message(self, body, priority=0, content_type=None,
content_encoding=None, headers=None, properties={}):
self._called('prepare_message')
return dict(body=body,
headers=headers,
... | oding)
def basic_publish(self, message, exchange='', routing_key='',
mandatory=False, immediate=False, **kwargs):
self._called('basic_publish')
return message, exchange, routing_key
def exchange_delete(self, *args, **kwargs):
self._called('exchange_delete')
d... |
baylee-d/osf.io | admin/collection_providers/forms.py | Python | apache-2.0 | 9,406 | 0.003827 | import bleach
import json
from django import forms
from osf.models import CollectionProvider, CollectionSubmission
from admin.base.utils import get_nodelicense_choices, get_defaultlicense_choices, validate_slug
class CollectionProviderForm(forms.ModelForm):
collected_type_choices = forms.CharField(widget=forms.... | get('issue_choices'))])
issue_choices_added = issue_choices_new - issue_choices_old
issue_choices_removed = issue_choices_old - issue_choices_new
for item in issue_choices_removed:
if CollectionSubmission.objects.filter(collection=collection_provider.primary_collectio... | sed as metadata on objects.'.format(item)
)
else:
# if this is creating a CollectionProvider
issue_choices_added = []
issue_choices_removed = []
choices = self.data.get('issue_choices')
if choices:
issue_choices_adde... |
remram44/rpaths | tests/test_abstract.py | Python | bsd-3-clause | 15,818 | 0 | from __future__ import unicode_literals
try:
import unittest2 as unittest
except ImportError:
import unittest
from rpaths import unicode, PY3, AbstractPath, PosixPath, WindowsPath
class TestAbstract(unittest.TestCase):
def test_construct(self):
"""Tests building an AbstractPath."""
with ... | lute._components(),
['\\', 'some', 'other', 'thing.h\xE9h\xE9'])
def test_root(self):
"""Tests roots, drives and UNC shares."""
a = WindowsPath(b'some/relative/path')
b = WindowsPath('alsorelative')
c = WindowsPath(b'/this/is/absolute')
d = WindowsPa... | ile')
def split_root(f):
return tuple(p.path for p in f.split_root())
self.assertEqual(split_root(a),
('.', 'some\\relative\\path'))
self.assertEqual(split_root(b),
('.', 'alsorelative'))
self.assertFalse(b.is_absolute)
... |
Anaethelion/Geotrek | geotrek/trekking/migrations/0029_auto__add_service__add_servicetype.py | Python | bsd-2-clause | 32,683 | 0.006915 | # -*- coding: utf-8 -*-
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from django.conf import settings
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Service'
db.create_table('o_t_service', (
('structure', self.gf... | ': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'pictogram': ('django.db.models.fields.files.FileField', [], {'max_length': '512', 'null': 'True', 'db | _column': "'picto'", 'blank': 'True'}),
'structure': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['authent.Structure']", 'db_column': "'structure'"}),
'website': ('django.db.models.fields.URLField', [], {'max_length': '256', 'null': 'True', 'db_column': "'website'", 'blank': '... |
x684867/nemesis | src/node/tools/test.py | Python | mit | 42,571 | 0.015691 | #!/usr/bin/env python
#
# Copyright 2008 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# noti... | def Starting(self):
print '1..%i' % len(self.cases)
self._done = 0
def AboutToRun(self, case):
pass
def HasRun(self, output):
self._done += 1
command = basename(output.command[-1])
if output.UnexpectedOutput():
print 'not ok %i - %s' % (self._done, command)
for l in output.outp... | else:
print 'ok %i - %s' % (self._done, command)
duration = output.test.duration
# total_seconds() was added in 2.7
total_seconds = (duration.microseconds +
(duration.seconds + duration.days * 24 * 3600) * 10**6) / 10**6
print ' ---'
print ' duration_ms: %d.%d' % (total_seconds, d... |
LighthouseHPC/lighthouse | src/LAPACK341/sort341/sing.py | Python | mit | 2,743 | 0.010208 | import urllib, shutil, csv
from time import time
import os
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.insert(0,parentdir)
import summary.summary
print "----------------- Sort the sing routines in v3.4.1 -----------------"
###----------- get new_list
new_list = summary.summa... | complex)
print "Singular valu | e decomposition (SVD) complex16: ", len(sing_complex16)
print "Singular value decomposition (SVD) auxiliary: ", len(sing_aux)
print "total time: ", time()-start
|
EmanueleCannizzaro/scons | test/Platform.py | Python | mit | 2,185 | 0.004119 | #!/usr/bin/env python
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to us... | ON
# OF CONTRACT, TORT | OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "test/Platform.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog"
import TestSCons
test = TestSCons.TestSCons()
test.write('SConstruct', """
env = Environment()
Platform('... |
paultag/aiodocker | aiodocker/constants.py | Python | mit | 29 | 0 | ST | REAM_HEADER_SIZ | E_BYTES = 8
|
lkishline/expyfun | expyfun/_eyelink_controller.py | Python | bsd-3-clause | 28,789 | 0.000035 | """Tools for controlling eyelink communication"""
# Authors: Eric Larson <[email protected]>
# Dan McCloy <[email protected]>
#
# License: BSD (3-clause)
import numpy as np
import datetime
from distutils.version import LooseVersion
import os
from os import path as op
import sys
import subprocess
import time
fro... | cation and control methods
Parameters
----------
ec : instance of ExperimentController | None
ExperimentContr | oller instance to interface with. Necessary for
doing calibrations.
link : str | None
If 'default', the default value will be read from EXPYFUN_EYELINK.
If None, dummy (simulation) mode will be used. If str, should be
the network location of eyelink (e.g., "100.1.1.1").
fs : int
... |
jileiwang/CJ-Glo | tools/distance.py | Python | apache-2.0 | 2,385 | 0.002096 | import argparse
import numpy as np
import sys
def generate():
parser = argparse.ArgumentParser()
parser.add_argument('--vocab_file', default='vocab.txt', type=str)
parser.add_argument('--vectors_file', default='vectors.txt', type=str)
args = parser.parse_args()
with open(args.vocab_file, 'r') as f... | -------------\n")
for x in a:
print("%35s\t\t%f" % (ivocab[x], dist[x]))
if __name__ == "__main__":
N = 20; # number of closest words that will be shown
W, vocab, ivocab = generate()
while True:
input_term = raw_input("\nEnter word or sentence (EXIT to break): ")
if in... | vocab, ivocab, input_term)
|
Arlefreak/MaloBarba | storeApi/migrations/0013_productimages.py | Python | mit | 1,161 | 0.005168 | # -*- coding: utf-8 -* | -
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('storeApi', '0012_product_tags'),
]
| operations = [
migrations.CreateModel(
name='ProductImages',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(default=b'', max_length=140, verbose_name=b'Name')),
... |
fparma/events | website/errorhandler.py | Python | mit | 363 | 0 | from flask import render_template
from website import app
@app.errorhandler(403)
def not_authorized(path):
return | render_template('status/403.html'), 403
@app.errorhandler(404)
def page_not_found(path):
return render_template('status | /404.html'), 404
@app.errorhandler(410)
def resource_gone(path):
return render_template('status/410.html'), 410
|
tuskar/tuskar-ui | openstack_dashboard/dashboards/admin/info/tests.py | Python | apache-2.0 | 3,281 | 0.003657 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | : (injected_file_content_bytes, 1)>',
'<Quota: (metadata_items, 1)>',
'<Quota: (injected_files, 1)>',
'<Quota: (gigabytes, 1000)>',
'<Quota: (ram, 10000)>',
| '<Quota: (floating_ips, 1)>',
'<Quota: (fixed_ips, 10)>',
'<Quota: (instances, 10)>',
'<Quota: (snapshots, 1)>',
'<Quota: (volumes, 1)>',
'<Qu... |
yosi-dediashvili/SubiT | tests/api/providers/torec/test_hamster.py | Python | gpl-3.0 | 1,257 | 0.005569 | import sys
sys.path.append("..\\..")
import os
import time
from api.providers.torec.hamster import TorecHashCodesHamster
from api.requestsmanager import RequestsManager
import unittest
class TestTorecHashCodeHamster(unittest.TestCase):
def setUp(self):
self.hamster = TorecHashCodesHamster(Reque... | assertEquals(len(self.hamster._records), 2)
time.sleep(120)
self.assertEquals(len(self.hamster._records), 0)
def test_remove_after_after_request(self):
self.hamster.add_sub_id("23703")
self.hamster.add_sub_id("2638")
self.assertEquals(len(self.hamster._records), 2)
... | len(self.hamster._records), 1)
self.assertEquals(self.hamster._records.keys()[0], "23703")
def run_tests():
test_runner = unittest.TextTestRunner(verbosity=0)
tests = unittest.defaultTestLoader.loadTestsFromTestCase(
TestTorecHashCodeHamster)
test_runner.run(tests) |
michelle/sink | 164/tml.py | Python | mit | 733 | 0.004093 | """Functions for TML layout that are used in the gram | mar to construct DOM-like
node objects used in the 164 layout engine.
"""
def createNode(name, attributes=None, children=None):
"""Creates a DOM-like node obje | ct, using the 164 representation so that
the node can be processed by the 164 layout engine.
"""
node = dict(attributes)
node['name'] = name
# Represent the list of child nodes as a dict with numeric keys.
node['children'] = dict(enumerate(children)) if children else {}
return node
def crea... |
paineliu/tflearn | rnn02.py | Python | apache-2.0 | 2,697 | 0.00482 | # coding = utf-8
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as | tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MN | IST_data/", one_hot=True)
tf.set_random_seed(1)
np.random.seed(1)
# Hyper Parameters
BATCH_SIZE = 128
TIME_STEP = 28 # rnn time step / image height
INPUT_SIZE = 28 # rnn input size / image width
LR = 0.01 # learning rate
# data
mnist = input_data.read_data_sets('./mnist', one_hot=True)... |
uclouvain/osis_louvain | base/forms/search/search_tutor.py | Python | agpl-3.0 | 1,699 | 0.001178 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | e 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.
#
# A copy of this license - GNU General Public License - is available
# at the root of the source code... | nses/.
#
##############################################################################
from django import forms
from django.utils.translation import ugettext_lazy as _
from base.forms.search.search_form import BaseSearchForm
from base.models import tutor
class TutorSearchForm(BaseSearchForm):
name = forms.CharF... |
alexforencich/verilog-ethernet | tb/test_ip_demux_64_4.py | Python | mit | 25,346 | 0.00075 | #!/usr/bin/env python
"""
Copyright (c) 2014-2018 Alex Forencich
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,... | myhdl import *
import os
import ip_ep
module = 'ip_demux'
testbench = 'test_%s_64_4' % module
srcs = []
srcs.append("../rtl/%s.v" % module)
srcs.append("%s.v" % testbench)
src = ' '.join(srcs)
build_cmd = "iverilog -o %s.vvp %s" % (testbench, src)
def bench():
# Parameters
M_COUNT = 4
DATA_WIDTH = ... | BLE = 1
USER_WIDTH = 1
# Inputs
clk = Signal(bool(0))
rst = Signal(bool(0))
current_test = Signal(intbv(0)[8:])
s_ip_hdr_valid = Signal(bool(0))
s_eth_dest_mac = Signal(intbv(0)[48:])
s_eth_src_mac = Signal(intbv(0)[48:])
s_eth_type = Signal(intbv(0)[16:])
s_ip_version = Signal... |
jcamachor/hive | ql/src/gen/thrift/gen-py/queryplan/ttypes.py | Python | apache-2.0 | 43,635 | 0.002177 | #
# Autogenerated by Thrift Compiler (0.14.1)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#
from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException
from thrift.protocol.TProtocol import TProtocolException
from thrift.TRecursive impo... | Begin('adjacencyType', TType.I32, 3)
oprot.writeI32(self.adjacencyType)
oprot.writeFieldEnd()
oprot | .writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.items()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isins... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.