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 |
|---|---|---|---|---|---|---|---|---|
aijunbai/quadrotor_openrave | addict/addict.py | Python | bsd-2-clause | 7,622 | 0.000131 | from inspect import isgenerator
import re
import copy
class Dict(dict):
"""
Dict is a subclass of dict, which allows you to get AND SET(!!)
items in the dict using the attribute syntax!
When you previously had to write:
my_dict = {'a': {'b': {'c': [1, 2, 3]}}}
you can now do the same simpl... |
for key, value in self.items():
y[copy.deepcopy(k | ey, memo)] = copy.deepcopy(value, memo)
return y
def update(self, d):
""" Recursively merge d into self. """
for k, v in d.items():
if ((k not in self) or
(not isinstance(self[k], dict)) or
(not isinstance(v, dict))):
self[k] = v
... |
stephanie-wang/ray | python/ray/tune/automl/genetic_searcher.py | Python | apache-2.0 | 9,413 | 0 | import logging
import numpy as np
from ray.tune.automl.search_policy import AutoMLSearcher
logger = logging.getLogger(__name__)
LOGGING_PREFIX = "[GENETIC SEARCH] "
class GeneticSearch(AutoMLSearcher):
"""Implement the genetic search.
Keep a collection of top-K parameter permutations as base genes,
the... | sample_2[i])
else:
next | _gen.append(sample_1[i])
return next_gen
@staticmethod
def _crossover(candidate):
"""Perform crossover action to candidates.
For example, new gene = 60% sample_1 + 40% sample_2.
Args:
candidate: List of candidate genes (encodings).
Examples:
>>... |
Wajihulhassan/SelfContainedPrevirt | tools/occam/occam/targets/run.py | Python | bsd-3-clause | 2,270 | 0.002204 | # ------------------------------------------------------------------------------
# OCCAM
#
# Copyright © 2011-2012, SRI International
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redis... | OR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (I... | ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ------------------------------------------------------------------------------
from occam import target
import sys
def readFile(fn):
if fn == '-':
return sys.stdin.read()
else:
return op... |
stephrdev/brigitte | brigitte/accounts/views.py | Python | bsd-3-clause | 3,125 | 0.00128 | # -*- coding: utf-8 -*-
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render, redirect, get_object_or_404
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_la... | , {
'user': user,
'repository_list': user.repository_set.user_public_repositories(user),
})
@login_required
def keys_list(request):
return render(request, 'accounts/keys_list.html', {
'keys': request.user.sshpublickey_set.all(),
})
@login_required
def keys_add(request):
if re... | er = request.user
key.save()
messages.success(request, _('Key added.'))
return redirect('accounts_keys_list')
else:
form = SshPublicKeyForm()
return render(request, 'accounts/keys_change.html', {'form': form})
@login_required
def keys_change(request, pk):
key =... |
pombredanne/voc | tests/builtins/test_print.py | Python | bsd-3-clause | 1,816 | 0 | from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class PrintTests(TranspileT | estCase):
def test_fileobj(self):
self.assertCodeExecution("""
class FileLikeObject:
| def __init__(self):
self.buffer = ''
def write(self, content):
self.buffer = self.buffer + (content * 2)
out = FileLikeObject()
print('hello', 'world', file=out)
print('goodbye', 'world', file=out)
print()
... |
tempbottle/restcommander | play-1.2.4/python/Lib/compiler/pyassem.py | Python | apache-2.0 | 26,171 | 0.001719 | """A flow graph representation for Python bytecode"""
import dis
import types
import sys
from compiler import misc
from compiler.consts \
import CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS
class FlowGraph:
def __init__(self):
self.current = self.entry = Block()
self.exit = Block("... | he last of the
# children. because the nodes in a graph are emitted in
# reverse post order, the "next" block will always be emitted
# immediately after its parent.
# Worry: maintai | ning this invariant could be tricky
if block is None:
block = self.newBlock()
# Note: If the current block ends with an unconditional
# control transfer, then it is incorrect to add an implicit
# transfer to the block graph. The current code requires
# these edges t... |
maria-grigorieva/django_cassandra_engine | django_cassandra_engine/management/commands/flush.py | Python | bsd-2-clause | 1,112 | 0 | from django.core.management.commands.flush import Command as FlushComm | and
from django_cassandra_engine.utils import get_engine_from_db_alias
class Command(FlushCommand):
def handle_noargs(self, **options):
engine = get_engine_from_db_alias(option | s['database'])
if engine == 'django_cassandra_engine':
options['load_initial_data'] = False
options['inhibit_post_migrate'] = True
return super(Command, self).handle_noargs(**options)
@staticmethod
def emit_post_syncdb(verbosity, interactive, database):
engine =... |
h4ck3rm1k3/pywikibot-core | scripts/watchlist.py | Python | mit | 3,349 | 0.000299 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Allows access to the bot account's watchlist.
The watchlist can be updated manually by running this script.
Syntax:
python pwb.py watchlist [-all | -new]
Command line options:
-all - Reloads watchlists for all wikis where a watchlist is already
pr... | ing, 2005
# (C) Pywikibot team, 2005-2016
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
#
import os
import pywikibot
from pywikibot import config
from pywikibot.data.api import CachedRequest
from scripts.maintenance.cache import... | ywikibot.Site()
watchlist = [p.title() for p in site.watched_pages()]
return watchlist
def isWatched(pageName, site=None):
"""Check whether a page is being watched."""
watchlist = get(site)
return pageName in watchlist
def refresh(site, sysop=False):
"""Fetch the watchlist."""
pywikibot.... |
jemandez/creaturas-magicas | Configuraciones básicas/scripts/addons/piemenus/pie_viewMenu.py | Python | gpl-3.0 | 7,255 | 0.015851 | # -*- coding: utf-8 -*-
# Copyright (c) 2010, Dan Eicher.
# 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,
# thi... | eft", -80, 0, 0))
menu.menu_items.append(ViewRight("Right", 80, 0, 0))
menu.menu_items.append(ViewBottom("Bottom", 0, -55, 0))
menu.menu_items.append(ViewTop("Top", 0, 55, 0))
menu.menu_items.append(ViewBack("Back", -65, 30, 0))
menu.menu_items.append(Vi | ewFront("Front", 65, 30, 0))
menu.menu_items.append(ViewSelected("Selected", -65, -30, 0, icon="EDIT"))
menu.menu_items.append(ViewCamera("Camera", 65, -30, 0, icon="OUTLINER_DATA_CAMERA"))
menu.menu_items.append(ViewOrtho("Orth/Persp", -200, 100, 0, calc_mode = "POLY_LOOP", layout = "PREDEF")) #top left co... |
jeremiah-c-leary/vhdl-style-guide | vsg/rules/move_token_next_to_another_token_if_it_exists_between_tokens.py | Python | gpl-3.0 | 2,515 | 0.001988 |
from vsg import parser
from vsg import violation
from vsg.rules import utils as rules_utils
from vsg.rule_group import structure
from vsg.vhdlFile import utils
class move_token_next_to_another_token_if_it_exists_between_tokens(structure.Rule):
'''
Moves one token next to another and places a single space be... | def _get_tokens_of_interest(self, oFile):
return oFile.get_tokens_bounded_by(self.between_tokens[0], self.between_tokens[1], bIncludeTillEndOfLine=True)
def _analyze(self, lToi):
for oToi in lToi:
lTokens = oToi.get_tokens()
for iToken, oToken in enumerate(lTokens):
... | = iToken
if isinstance(oToken, self.token_to_move):
iMoveIndex = iToken
if not (iStartIndex + 2 == iMoveIndex and isinstance(lTokens[iStartIndex + 1], parser.whitespace)):
oViolation = violation.New(oToi.get_line_number(), oToi, self.soluti... |
dundeemt/SoCo | soco/music_services/accounts.py | Python | mit | 7,489 | 0 | # -*- coding: utf-8 -*-
"""Accounts for Third Party music services."""
from __future__ import (
absolute_import, unicode_literals
)
import logging
import weakref
import requests
from .. import discovery
from ..xml import XML
log = logging.getLogger(__name__) # pylint: disable=C0103
# pylint: disable=too-ma... | self.service_ty | pe,
self.nickname,
hex(id(self))
)
def __str__(self):
return self.__repr__()
@staticmethod
def _get_account_xml(soco):
"""Fetch the account data from a Sonos device.
Args:
soco (SoCo): a SoCo instance to query. If soco is none, a
... |
PetePriority/home-assistant | homeassistant/components/ecobee/climate.py | Python | apache-2.0 | 16,743 | 0 | """
Platform for Ecobee Thermostats.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/climate.ecobee/
"""
import logging
import voluptuous as vol
from homeassistant.components import ecobee
from homeassistant.components.climate import (
DOMAIN, STATE... | min_on_time'
ATTR_RESUME_ALL = 'resume_all'
DEFAULT_RESUME_ALL = False
TEMPERATURE_HOLD = 'temp'
VACATION_HOLD = 'vacation'
AWAY_MODE = 'awayMode'
DEPENDENCIES = ['ecobee']
SERVICE_SET_FAN_MIN_ON_TIME = 'ecobee_set_fan_min_on_time'
SERVICE_RESUME_PROGRAM = 'ecobee_resume_program'
SET_FAN_MIN_ON_TIME_SCHEMA = vol.Sc... | Required(ATTR_FAN_MIN_ON_TIME): vol.Coerce(int),
})
RESUME_PROGRAM_SCHEMA = vol.Schema({
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(ATTR_RESUME_ALL, default=DEFAULT_RESUME_ALL): cv.boolean,
})
SUPPORT_FLAGS = (SUPPORT_TARGET_TEMPERATURE | SUPPORT_AWAY_MODE |
SUPPORT_HOLD_MODE |... |
JeroenZegers/Nabu-MSSS | nabu/neuralnetworks/models/dblstm_capsnet.py | Python | mit | 3,928 | 0.033859 | """@file dblstm_capsnet.py
contains the DBLSTMCapsNet class"""
import tensorflow as tf
import model
from nabu.neuralnetworks.components import layer, ops
import pdb
class DBLSTMCapsNet(model.Model):
"""A capsule network with bidirectional recurrent LSTM"""
def _get_outputs(self, inputs, input_seq_length, is_trai... | _dim, linear_out_flag=True)
primary_c | apsules = primary_capsules_layer(output, input_seq_length)
primary_capsules = tf.reshape(primary_capsules, [output.shape[0].value, tf.shape(output)[1],
num_capsules*2, capsule_dim])
primary_capsules = ops.squash(primary_capsules)
output = tf.identity(primary_capsules, 'primary_capsule... |
mnunberg/yobot | py/gui/smiley.py | Python | gpl-3.0 | 18,464 | 0.00195 | #!/usr/bin/env python
#simple smileys icon builder..
SMILEYS_INDEX=(
"""
# Default smileys
[default]
happy.png :) :-)
excited.png :-D :-d :D :d
sad.png :-( :(
wink.png ;-) ;)
tongue.png :P :p :-P :-p
shocked.png =-O =-... | :O :o
tongue.png :-P :P :-p :p
glasses-cool.png (H) (h)
angry.png :@ :-@
embarrassed.png :$ :-$
confused.png :S :s :-S :-s
sad.png :( :-(
crying.png | :'(
neutral.png :| :-|
devil.png (6)
angel.png (A) (a)
in_love.png (L) (l)
love-over.png (U) (u)
msn.png (M) (m)
cat.png (@)
dog.png (&)
moon.png (S)
star.png (*)
film.png (~)
mus... |
DrOctogon/unwash_ecom | tests/unit/partner/model_tests.py | Python | bsd-3-clause | 4,657 | 0.000429 | import six
from decimal import Decimal as D
from oscar.core.loading import get_model
from django.test import TestCase
from oscar.test import factories, decorators
from oscar.apps.partner import abstract_models
Partner = get_model('partner', 'Partner')
PartnerAddress = get_model('partner', 'PartnerAddress')
Country =... | ord.allocate(5)
def test_consuming_allocation(self):
self.stockrecord.allocate(5)
self.stockrecord.consume_allocation(3)
self.assertEqual(2, self.stockrecord.num_allocated)
self.assertEqual(7, self.stockrecord.num_in_stock)
def test_cancelling_allocation(self):
self.sto... | elf.stockrecord.num_allocated)
self.assertEqual(10, self.stockrecord.num_in_stock)
def test_cancelling_allocation_ignores_too_big_allocations(self):
self.stockrecord.allocate(5)
self.stockrecord.cancel_allocation(6)
self.assertEqual(0, self.stockrecord.num_allocated)
self.as... |
Yubico/python-yubicommon | yubicommon/ctypes/libloader.py | Python | bsd-2-clause | 12,066 | 0.000083 | # ----------------------------------------------------------------------------
# Copyright (c) 2008 David James
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are ... | the DT_RPATH and DT_RUNPATH binary sections are omitted.
directories = []
for name in ("LD_LIBRARY_PATH",
"SHLIB_PATH", # HPUX
"LIBPATH", # OS/2, AIX
"LIBR | ARY_PATH", # BE/OS
):
if name in os.environ:
directories.extend(os.environ[name].split(os.pathsep))
directories.extend(self.other_dirs)
directories.append(".")
directories.append(os.path.dirname(__file__))
try:
directories.ex... |
tmenjo/cinder-2015.1.0 | cinder/tests/integrated/integrated_helpers.py | Python | apache-2.0 | 4,453 | 0 | # Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | :
self.useFixture(fixtures.EnvironmentVariable(var))
# set up services
self.volume = self.st | art_service('volume')
# NOTE(dulek): Mocking eventlet.sleep so test won't time out on
# scheduler service start.
with mock.patch('eventlet.sleep'):
self.scheduler = self.start_service('scheduler')
self._start_api_service()
self.addCleanup(self.osapi.stop)
sel... |
Kingdread/dc-reloaded | freeze.py | Python | gpl-3.0 | 918 | 0 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from cx_Freeze import setup, Executable
from setupcommon import setupdata
base = "Win32GUI" if sys.platform == "win32" else None
build_exe_options = {
"excludes": ["tkinter"],
"zip_includes": [
# Tuple source/dest file, otherwise they end up in wro... | _help.html",
"dc/interface/static/short_help.html"),
],
}
bdist_msi_options = {
"add_to_path": False,
"upgrade_code": "{ce110df4-67c4-43f4-bfa6-fcfd1ac11378}",
}
executables = [
| Executable(
"scripts/dc-reloaded",
base=base,
icon="resource-files/cpu.ico",
shortcutName="DC reloaded",
shortcutDir="ProgramMenuFolder",
),
]
setup(
executables=executables,
options={
"build_exe": build_exe_options,
"bdist_msi": bdist_msi_options,
... |
timj/scons | bin/time-scons.py | Python | mit | 12,346 | 0.000729 | #!/usr/bin/env python
#
# time-scons.py: a wrapper script for running SCons timings
#
# This script exists to:
#
# 1) Wrap the invocation of runtest.py to run the actual TimeSCons
# timings consistently. It does this specifically by building
# SCons first, so .pyc compilation is not part of the t... | name__, ', '.join(map(repr, args)))
if isinstance(command, list):
# TODO: quote arguments containing spaces
| # TODO: handle meta characters?
s = ' '.join(command)
else:
s = self.subst(command)
if not s.endswith('\n'):
s += '\n'
sys.stdout.write(s)
sys.stdout.flush()
def execute(self, command, stdout=None, stderr=None):
"""
Executes a... |
neilhan/tensorflow | tensorflow/contrib/losses/python/losses/loss_ops_test.py | Python | apache-2.0 | 48,390 | 0.00777 | # Copyright 2016 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... | ([1.2, 0.0], shape=[2,])
loss = tf.contrib.losses.absolute_difference(
self._predictions, self._targets, weight)
with self.test_session():
self.assertAlmostEqual(5.6, loss.eval(), 3)
def testNonZeroLo | ssWithTwoDimBatchSpecificWeights(self):
weight = tf.constant([1.2, 0.0], shape=[2, 1])
loss = tf.contrib.losses.absolute_difference(
self._predictions, self._targets, weight)
with self.test_session():
self.assertAlmostEqual(5.6, loss.eval(), 3)
def testNonZeroLossWithSampleSpecificWeights(s... |
funkyeah/tiddlyweb | tiddlyweb/util.py | Python | bsd-3-clause | 6,686 | 0.000598 | """
A grab bag of miscellaneous utility functions for TiddlyWeb that don't
fit in elsewhere.
Web specific utilities are in tiddlyweb.web.util.
"""
import logging
import codecs
import os
import sys
try:
from hashlib import sha1
except ImportError:
from sha import sha as sha1
class LockError(IOError):
""... | he
content of the tiddler is non-textual. This is usuallly used
to determine if the tiddler should be base64 encoded.
"""
return (tiddler.type and tiddler.type != 'None'
and not pseudo_binary(tiddler.type))
def pseudo_binary(content_type):
"""
Return true if the content type should... | eudo binary is a type of textual content for which (this) TiddlyWeb
(instance) has no serialization. TiddlyWeb requires that such content
be uploaded encoded in UTF-8.
"""
content_type = content_type.lower()
return (content_type.startswith('text/')
or content_type.endswith('+xml')
... |
stephanellis/netmanager | netmanager/views_settings.py | Python | gpl-3.0 | 2,305 | 0.004338 | from pyramid.response import Response
from pyramid.view import view_config, view_defaults
from sqlalchemy.exc import DBAPIError
from pyramid.httpexceptions import HTTPFound
from pyramid.security import Everyone, Authenticated
from .models import (
DBSession,
get_operator,
asdict,
alog,
)
import ... | pw1 and pw2:
if pw1 == pw2:
self.request.operator.set_password(pw1)
| log.info("%s changed password" % self.request.operator.call)
alog(self.request, "changed password")
else:
log.info("%s attempted to change password, but they did not match" % self.request.operator.call)
alog(self.request, "attempted to change pass... |
marcstreeter/ChatterBlog | app/shared/error.py | Python | apache-2.0 | 1,203 | 0.004988 |
class Errors(Exception):
__status_code = 400
__error_cat = "General Error"
__default_message = "System Error Occurred"
def __init__(self, message= | None, status_code=None, payload=None):
Exception.__init__(self)
self.category = self.__error_cat
self.message = message or self.__default_message
self.status_code = status_code or self.__status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ... | "System Error"
__default_message = "Oops, Pardon us! An engineer has been notified and woken from slumber."
__status_code = 500
# User Errors
class UserErrors(Errors):
__error_cat = "User Error"
__default_message = "Error Caused By User"
class InvalidUsageError(UserErrors):
__default_message = "... |
SMMAR11/smmarbsence | app/forms/admin.py | Python | gpl-3.0 | 4,838 | 0.017813 | # coding: utf-8
# Imports
from app.models import *
from django import forms
from django.contrib.admin.widgets import FilteredSelectMultiple
class FGroupeUtilisateur(forms.ModelForm) :
# Champ
util = forms.ModelMultipleChoiceField(
label = 'Utilisateurs composant le groupe',
queryset = TUtilis... | ', is_stacked = False)
)
class Meta :
fields = '__all__'
model = TGroupeUtilisateur
def __init__(self, *args, **kwargs) :
super(FGroupeUtilisateur, self).__init__(*args, **kwargs)
# Définition de la valeur | initiale du champ personnalisé
if self.instance.get_pk() :
self.fields['util'].initial = [u.get_pk() for u in self.instance.get_util_set().all()]
def save(self, *args, **kwargs) :
# Création/modification d'une instance TGroupeUtilisateur
obj = super(FGroupeUtilisateur, s... |
geebzter/game-framework | CDJKPlayer.py | Python | apache-2.0 | 3,670 | 0.007629 | __author__ = 'Collin Day and Joe Kvedaras'
import random
# Example of how to implement an RPS player within the framework
import Player
import Message
class CDJKPlayer(Player.Player):
def __init__(self):
# Call super class constructor
Player.Player.__init__(self)
self.reset()
def pla... | t random.
#we put random numbers in certain pla | ces to throw off others stratigies
# count number of rock, paper and scissors moves made in the past
count = [0, 0, 0]
for move in opponents_moves:
count[move] += 1
if (count[0] > count[1] & count[0] < count[2]) | (count[0] < count[1] & count[0] > count[2]):
... |
fadushin/esp8266 | micropython/ulog/ulog/mqtt_sink.py | Python | bsd-2-clause | 2,794 | 0.005011 | #
# Copyright (c) dushin.net 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, this list of conditions and the foll... | WEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import mqtt.simple
import ujson
class Sink :
def __init__(self, config... | es'] if 'retries' in config else 1
self.retain = config['retain'] if 'retain' in config else False
self.qos = config['qos'] if 'qos' in config else 0
self.topic = config['topic'] if 'topic' in config else 'log'
self.client = mqtt.simple.MQTTClient(client_id=name, server=host, port=port)
... |
adrn/gala | gala/potential/potential/tests/test_composite.py | Python | mit | 5,631 | 0 | # Third party
import astropy.units as u
import pytest
import numpy as np
# This project
from ..core import PotentialBase, CompositePotential
from ...common import PotentialParameter
from ..builtin import (KeplerPotential, HernquistPotential,
HenonHeilesPotential)
from ..ccompositepotential impo... | composite """
p1 = KeplerPotential(units=galactic, m=1*u.Msun)
p2 = HernquistPotential(units=galactic,
m=1.E11, c=0.26)
comp1 = CompositePotential()
comp1['0'] = p1
comp1['1'] = p2
py_p1 = MyPotential(m=1., x0=[1., 0., 0.], units=galactic)
py_p2 = MyPotential(m=... | tic)
# python + python
new_p = py_p1 + py_p2
assert isinstance(new_p, CompositePotential)
assert not isinstance(new_p, CCompositePotential)
assert len(new_p.keys()) == 2
# python + python + python
new_p = py_p1 + py_p2 + py_p2
assert isinstance(new_p, CompositePotential)
assert len... |
dwadler/QGIS | python/plugins/processing/gui/MessageDialog.py | Python | gpl-2.0 | 2,138 | 0 | # -*- coding: utf-8 -*-
"""
***************************************************************************
MessageDialog.py
---------------------
Date : October 2014
Copyright : (C) 2014 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
***********... | s.filterwarnings("ignore", category=DeprecationWarning)
WIDGET, BASE = uic.loadUiType(
os.path.join(pluginPath, 'ui', 'DlgMessage.ui'))
class MessageDialog(BASE, WIDGET):
def __init__(self):
super(MessageDialog, self).__init__(None)
self.setupUi(self)
self.txtMessage.anchorCl... | lf.txtMessage.setHtml(message)
def openLink(self, url):
if url.toString() == "log":
self.close()
logDock = iface.mainWindow().findChild(QDockWidget, 'MessageLog')
logDock.show()
else:
QDesktopServices.openUrl(url)
|
ianmiell/OLD-shutitdist | gperf/gperf.py | Python | gpl-2.0 | 1,224 | 0.043301 | """ShutIt module. See http://shutit.tk/
"""
from shutit_module import ShutItModule
class gperf(ShutItModule):
def is_installed(self, shutit):
return shutit.file_exists('/root/shutit_build/module_record/' + self.module_id + '/built')
def build(self, shutit):
shutit.send('mkdir -p /tmp/build/gperf')
shutit.... | shutit.send('make')
shutit.send('make install')
return True
def get_config(self, shutit):
shutit.get_config(self.module_id,'version','3.0.4')
return True
#def check_ready(self, shutit):
# return True
#def start(self, shutit):
# return True
#def stop(self, shutit):
# return True
def finalize(self... | erf.gperf', 158844782.004,
description='',
maintainer='ian.miell@gmail.com',
depends=['shutit.tk.sd.pkg_config.pkg_config']
)
|
JacobPorter/BisPin | Utilities/SeqDoubleIterator.py | Python | gpl-3.0 | 775 | 0.016774 | import SeqIterator
| import Constants
"""
@author: Jacob Porter
@summary: An iterator class for iterating through two sequence record files simultaneously.
@requires: SeqIterato | r
"""
class SeqDoubleIterator:
def __init__(self, file_name1, file_name2, file_type=Constants.FASTQ, gzip_switch = False):
self.SeqIterator1 = SeqIterator.SeqIterator(file_name1, file_type=file_type, gzip_switch = gzip_switch)
self.SeqIterator2 = SeqIterator.SeqIterator(file_name2, file_type=f... |
Vaayne/vaayne.com | app/func/spider/run.py | Python | mit | 997 | 0.011033 | # -*- coding:utf-8 -*-
# Created by Vaayne at 2016/09/04 09:49
from gevent.monkey import patch_all
patch_all()
from gevent.pool import Pool
import logging
import coloredlogs
from .wx_iwgc import WxWGC
from .smzdm import Smzdm
from .fly import FlyerTea
import os |
import sys
import time
log = logging.getLogger(__file__)
coloredlogs.install(logging.INFO)
iwgc = WxWGC()
fly = FlyerTea()
sm = Smzdm()
def get_urls():
with open('wx.csv', 'r') as f:
res = f.readlines()
urls = list(map(lambda x: x.replace('\n', '').split(',')[0:3], res))
return urls
def main(... | ge(1, 1001)]))
p.map(iwgc.run_, urls)
if __name__ == '__main__':
while 1:
try:
main()
except Exception as e:
log.exception(e)
finally:
time.sleep(60*60)
|
jcarlson23/lammps | tools/moltemplate/src/nbody_by_type.py | Python | gpl-2.0 | 24,666 | 0.00596 | #!/usr/bin/env python
# Author: Andrew Jewett (jewett.aij at g mail)
# http://www.chem.ucsb.edu/~sheagroup
# License: 3-clause BSD License (See LICENSE.TXT)
# Copyright (c) 2011, Regents of the University of California
# All rights reserved.
man_page_text = """
nbody_by_type.py reads a LAMMPS data file ... | ine = (line[:icomm | ent]).strip()
if len(line) > 0:
tokens = SplitQuotedString(line)
if ((len(tokens) <= i_atomid) or (len(tokens) <= i_atomtype)):
raise(InputError('Error not enough columns on line '+str(iv+1)+' of \"Atoms\" section.'))
tokens = SplitQuotedString(line)
... |
zstackio/zstack-woodpecker | integrationtest/vm/vpc_ha/test_vpc_netflow_v9.py | Python | apache-2.0 | 4,086 | 0.007342 | '''
@author: Pengtao.Zhang
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.operations.vpc_operations as vpc_ops
import os
from itertools import izip
import zstackwoodpecker.operations.resource_oper... | der = test_stub.create_vm('vm_sender', 'image_with_network_tools', 'l3VlanNetwork1')
vm_sender.check()
vm_sender_ip = vm_sender.get_vm().vmNics[0].ip
vm_sender_l3_uuid = vm_s | ender.get_vm().vmNics[0].l3NetworkUuid
print 'debug vm_sender_l3_uuidis: %s' %vm_sender_l3_uuid
print 'debug vr.inv.uuid: %s' %vr.inv.uuid
test_obj_dict.add_vm(vm_sender)
test_obj_dict.add_vm(vm_colloctor)
#add vpc to netflow
test_util.test_dsc("add vpc to netflow")
vpc_ops.add_vpc_to_netflow(n... |
jrising/open-estimate | openest/generate/v1/effectset.py | Python | gpl-3.0 | 23,746 | 0.003411 | # -*- coding: utf-8 -*-
################################################################################
# Copyright 2014, Distributed Meta-Analysis System
################################################################################
"""Software structure for generating Monte-Carlo collections of results.
NOTE: Hi... | iginal: netCDF object, data: [days x counti | es],
times: [yyyyddd]}. [VRD]
Controllers (elsewhere) loop through these, and for each available
forecast call a make_tar_* function passing in a make_generator
function. The make_tar_* functions call make_generator with each
individual region, retrieving a set of results, and then package those
results into the outp... |
suutari/shoop | shuup/core/management/commands/makemessages.py | Python | agpl-3.0 | 5,247 | 0 | # This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
"""
Patched version of Django's Makemessages that works with Jinja2.
Works by monkey patch... | super(Command, self).handle(*args, **options)
finally:
trans_real.templatize = old_templatize
def build_potfiles(self):
"""
Build PO Template files and return paths to them.
Extends base classes version of this method by adding the
"Remove POT-Creation-Date" fe... | es = super(Command, self).build_potfiles()
if self.no_pot_date:
unique_potfiles = sorted(set(potfiles)) # Remove duplicates
for potfile in unique_potfiles:
_remove_pot_creation_date(potfile)
return potfiles
def write_po_file(self, potfile, locale):
... |
pawartur/django-todo-lists | todo_lists/tests/model_tests.py | Python | bsd-3-clause | 3,581 | 0.002793 | from django.utils.timezone import now, timedelta
from django.test import TestCase
from django.contrib.auth.models import User
from todo_lists.models import (
ToDoList,
ToDoContext,
ToDo,
ToDoAlert,
)
class ToDoModelsTestCase(TestCase):
def setUp(self):
user1 = User(username="user1", first_... | self.assertQuerysetEqual(self.todo1.tags.all(), [])
self.todo1.tags.add("important", "work")
self.assertQuerysetEqual(self.todo1.tags.all().order_by("name"), ['<Tag: important>', '<Tag: work>'])
self.todo1.tags.remove("important")
self.assertQuerysetEqual(self.todo1.tags.all().order_... | rk>'])
|
abutcher/openshift-ansible | playbooks/openstack/inventory.py | Python | apache-2.0 | 8,542 | 0.000234 | #!/usr/bin/env python
"""
This is an Ansible dynamic inventory for OpenStack.
It requires your OpenStack credentials to be set in clouds.yaml or your shell
environment.
"""
from __future__ import print_function
from collections import Mapping
import json
import os
from keystoneauth1.exceptions.catalog import Endpo... | if not isinstance(node_labels, Mapping):
node_labels = json.loads(node_labels)
if node | _labels:
hostvars['openshift_node_labels'] = node_labels
# check for attached docker storage volumes
if 'os-extended-volumes:volumes_attached' in server:
if server.id in docker_storage_mountpoints:
hostvars['docker_storage_mountpoints'] = ' '.join(
docker_storage_mou... |
memsql/memsql-loader | memsql_loader/util/apsw_sql_step_queue/task_handler.py | Python | apache-2.0 | 10,504 | 0.001333 | import copy
from datetime import datetime
from dateutil import parser
from contextlib import contextmanager
from memsql_loader.util import apsw_helpers, super_json as json
from memsql_loader.util.apsw_sql_step_queue.errors import TaskDoesNotExist, StepAlreadyStarted, StepNotStarted, StepAlreadyFinished, StepRunning, A... | task_id=self.task_id)
def start_step(self, step_name):
""" Start a step. """
if self.finished is not None:
raise AlreadyFinished()
step_data = self._get_step(step_name)
if step_data is not None:
if 'stop' in step_data:
raise StepAlreadyFini | shed()
else:
raise StepAlreadyStarted()
steps = copy.deepcopy(self.steps)
steps.append({
"start": datetime.utcnow(),
"name": step_name
})
self._save(steps=steps)
def stop_step(self, step_name):
""" Stop a step. """
... |
open-synergy/opnsynid-hr | hr_termination_transition_payroll_account/models/hr_termination_transition.py | Python | agpl-3.0 | 316 | 0 | # -*- coding: utf-8 -*-
# Copyright 2018 OpenSyner | gy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp impo | rt models
class HrTerminationTransition(models.Model):
_name = "hr.termination_transition"
_inherit = ["hr.career_transition", "hr.termination_transition"]
|
Sigf/outbreak | birdseye/tests/test_application.py | Python | bsd-3-clause | 1,282 | 0.0039 | """
file: test_application.py
desc: TODO
"""
import os, unittest, tempfile
from birdseye.application import app
class FlaskTests(unittest.TestCase):
def test_get_static_js(self):
tempfile.tempdir = app.root_path + '/static/js/'
f = tempfile.NamedTemporaryFile()
with app.test_client() as c... | self.assertEqual(r._status_code, 200,
'Error: could not retrieve file from static css path')
def test_get_static_lib(self):
tempfile.tempdir = app | .root_path + '/lib/bower_components/'
f = tempfile.NamedTemporaryFile()
with app.test_client() as c:
r = c.get('static/lib/' + os.path.basename(f.name))
self.assertEqual(r._status_code, 200,
'Error: could not retrieve file from static js lib path')
if __name__ ==... |
Kraymer/beets | beets/ui/commands.py | Python | mit | 59,450 | 0.000084 | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# 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 t... | ib, opts, args):
def _print_rows(names):
names.sort()
print_(u' ' + u'\n '.join(names))
print_(u"Item fields:")
_print_rows(library.Item.all_keys())
print_(u"Album fields:")
_print_rows(library.Album.all_keys())
with lib.transaction() as tx:
# The SQL uses the DISTIN... | DISTINCT key FROM (%s)'
print_(u"Item flexible attributes:")
_print_keys(tx.query(unique_fields % library.Item._flex_table))
print_(u"Album flexible attributes:")
_print_keys(tx.query(unique_fields % library.Album._flex_table))
fields_cmd = ui.Subcommand(
'fields',
help=u'sho... |
eduNEXT/edunext-platform | import_shims/lms/lms_initialization/apps.py | Python | agpl-3.0 | 392 | 0.010204 | """Deprecated import support. Auto-generated by import_shims/generate_shims.sh."""
# pylint: disable=redefined-builtin,wrong-import | -position,wildcard-import,useless-suppression,line-too-long
from import_shims.warn import warn_deprecated_import
warn_deprecated_import('lms_initialization.apps', 'lms.djangoapps.lms_initialization.apps')
from lms.djangoapps.lms_initializat | ion.apps import *
|
Alexis-benoist/eralchemy | script/make_release.py | Python | apache-2.0 | 3,766 | 0.001328 | from __future__ import print_function
import os
import sys
from subprocess import Popen, PIPE
from getpass import getpass
from shutil import rmtree
import argparse
# inspired by https://github.com/mitsuhiko/flask/blob/master/scripts/make-release.py
def set_filename_version(filename, version_number):
with open(f... | open('eralchemy/version.py') as f:
lines = f.readlines()
namespace = {}
exec(lines[0], namespace)
return version_str_to_lst(namespace['version'])
def get_git_tags():
return set(Popen(['git', 'tag'], stdout=PIPE).communicate()[0].splitlines())
def get_next_version(major, minor, f... | + 1, 0, 0]
if minor:
return [current_version[0], current_version[1] + 1, 0]
if fix:
return [current_version[0], current_version[1], current_version[2] + 1]
raise UserWarning()
def main():
os.chdir(os.path.join(os.path.dirname(__file__), '..'))
current_version = get_current_version... |
foxdog-studios/pyddp | ddp/id_generator.py | Python | apache-2.0 | 850 | 0.001176 | # -*- coding: utf-8 -*-
# Copyright 2014 Foxdog Studios
#
# 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 b | y applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the | License.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from itertools import count
__all__ = ['build_id_generator']
def build_id_generator():
for id in count():
yield str(id)
|
Canule/Mash-Cogs | omaps/omaps.py | Python | gpl-3.0 | 8,950 | 0.006816 | from .utils.dataIO import fileIO
from .utils import checks
from __main__ import send_cmd_help
from __main__ import settings as bot_settings
# Sys.
from operator import itemgetter, attrgetter
import discord
from discord.ext import commands
#from copy import deepcopy
import aiohttp
import asyncio
import json
import os
im... | raw.composite(operator='atop', left=311, top=311, width=90, height=90, image=r) #720
draw(w)
# Text
draw.fill_color = Color("#7289DA")
draw.str | oke_color = Color("#5370D7")
draw.stroke_width = 0.3
draw.fill_opacity = 0.7
draw.stroke_opacity = 0.7
draw.font_style = 'oblique'
draw.font_size = 32
splitDisplayName = display_name.split(',')
# Object name/number
draw.text... |
danielnyga/pracmln | python2/pracmln/mln/inference/gibbs.py | Python | bsd-2-clause | 6,737 | 0.004601 | # -*- coding: utf-8 -*-
#
# Markov Logic Networks
#
# (C) 2006-2011 by Dominik Jain (jain@cs.tum.edu)
#
# 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
# witho... | OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, A... | FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import random
from collections import defaultdict
import numpy
from dnutils import ProgressBar
from pracmln.logic.common import Logic
from pracmln.mln.constants import ALL
from pracmln.mln.grounding.fastconj import FastCo... |
rwl/PyCIM | CIM14/ENTSOE/Dynamics/IEC61970/Core/CorePSRType.py | Python | mit | 2,441 | 0.002458 | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... | HE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER... | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from CIM14.ENTSOE.Dynamics.IEC61970.Core.CoreIdentifiedObject import CoreIdentifiedObject
class CorePSRType(CoreIdentifiedObject):
def __init__(self, PowerSystemResources=None, *args, **kw_args):
"""Initialises a new 'CorePSR... |
alexryndin/ambari | ambari-server/src/main/resources/stacks/BigInsights/4.2/services/YARN/package/scripts/historyserver.py | Python | apache-2.0 | 7,308 | 0.008894 | """
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... | dfs_user, skip=params.host_sys_prepped)
copy_to_hdfs("slider", params.user_group, params.hdfs_user, skip=params.host_sys_prepped)
params.HdfsResource(None, action="execute")
def start(self, env, upgrade_type=None):
import params
env.set_params(params)
self.configure(env) # FOR SECURITY
#... | ost_sys_prepped)
resource_created = copy_to_hdfs(
"slider",
params.user_group,
params.hdfs_user,
skip=params.host_sys_prepped) or resource_created
if resource_created:
params.HdfsResource(None, action="execute")
service('historyserver', action='start', serviceName='mapreduce')... |
rpwagner/tiled-display | flTile/test/printTileConfigCoords.py | Python | apache-2.0 | 868 | 0.012673 | import os, sys
sys.path = [os.path.j | oin(os.getcwd(), "..") ] + sys.path
sys.path = [os.path.join(os.getcwd(), "..", "..") ] + sys.path
from flTile.amConfig import CreateAMConfig
def run():
tileConfig = CreateAMConfig()
#hostname = gethostname()
#machineDesc = tileConfig.getMachineDescByHostname(hostname)
print "Machine, local rects, a... | :
localRects = []
absoluteRects = []
for tile in machineDesc.tiles:
localRects.append(tileConfig.getLocalDrawRect(tile.uid))
absoluteRects.append(tileConfig.getAbsoluteFullDisplayRect(tile.uid))
print machineDesc.hostname, localRects, absoluteRects
fullRec... |
angr/angr | angr/procedures/cgc/deallocate.py | Python | bsd-2-clause | 1,857 | 0.004308 | import angr
import logging
l = logging.getLogger(name=__name__)
class deallocate(angr.SimProcedure):
#pylint:disable=arguments-differ
def run(self, addr, length): #pylint:disable=unused-argument
# return code (see deallocate() docs)
r = self.state.solver.ite_cases((
(addr % 0x... | length = self.state.solver.max_int(length)
aligned_length = ((length + 0xfff) // 0 | x1000) * 0x1000
# only add sinkholes and unmap on success
if self.state.solver.max_int(r) == 0:
# shorten length
allowed_pages = 0
while allowed_pages * page_size < aligned_length and \
base_page_num + allowed_pages in self.state.memory._pages:
... |
flockchat/pyflock | flockos/apis/roster.py | Python | apache-2.0 | 568 | 0.005282 | # c | oding: utf-8
# python 2 and python 3 compatibility library
from six import iteritems
from ..api_client import call_api
def list_contacts(token, **kwargs):
"""
This method makes a synchronous HTTP request.
:param str token: (required)
:return: response dict
"""
params = locals() |
for key, val in iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
resource_path = '/roster.listContacts'.replace('{format}', 'json')
response = call_api(resource_path, params=params)
return response
|
JJarczyk12/Sports-Statistical-Scraper | SportsStatistics/model/databaseConstants.py | Python | mit | 2,575 | 0.015922 | '''
Created on Sep 28, 2013
@author: justin
'''
class databaseConstants():
'''
Holds the metadata behind the database creation
'''
_connDict = {
'DBType':'mysql',
'DBUsername':'root',
'DBPassword':'Ginger*12',
'DBNAme':'SportsStatistics',
'DBServer':'local... | Table list, dictionary key must match a db above
TableList = {
'DBStats':[
'TestTable',
'TestTable1',
'TestTable2',
'TestTable3'
],
'DBStatDependancyCompilation':[
'TestTab | le',
'TestTable1',
'TestTable2',
'TestTable3'
]
}
def __init__(self):
'''
All Database Metadata functionality
'''
print 'Initializing database constants '
def ConnectionString(se... |
semkiv/heppy_fcc | particles/fcc/jet.py | Python | gpl-3.0 | 341 | 0.01173 | from heppy_fcc.particles.jet import Jet as B | aseJet
from vertex import Vertex
from ROOT import TLorentzVector
import math
class Jet(BaseJet):
def __init__(self, fccjet):
self.fccjet = fccjet
self._tlv = TLorentzVector()
p4 = fccjet.Core().P4
self._tlv.Se | tXYZM(p4.Px, p4.Py, p4.Pz, p4.Mass)
|
gattazr/cohorte-herald | python/herald/transports/xmpp/bot.py | Python | apache-2.0 | 3,169 | 0 | #!/usr/bin/python
# -- Content-Encoding: UTF-8 --
"""
Herald XMPP bot
:author: Thomas Calmant
:copyright: Copyright 2014, isandlaTech
:license: Apache License 2.0
:version: 0.0.5
:status: Alpha
..
Copyright 2014 isandlaTech
Licensed under the Apache License, Version 2.0 (the "License");
you may not use ... | nick: Nick name used in MUC rooms
"""
# Set up the object
pelixmpp.BasicBot.__init__(self, jid, password)
pelixmpp.ServiceDiscoveryMixin.__init__(self)
self._nick = | nick
# Message callback
self.__cb_message = None
# Register to events
self.add_event_handler("message", self.__on_message)
def set_message_callback(self, callback):
"""
Sets the method to call when a message is received.
The method takes the message stanza... |
tobikausk/nest-simulator | pynest/examples/brunel_siegert_nest.py | Python | gpl-2.0 | 7,181 | 0 | # -*- coding: utf-8 -*-
#
# brunel_siegert_nest.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the Lic... | A PARTICULAR PURPOSE. See the
# G | NU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see <http://www.gnu.org/licenses/>.
'''Mean-field theory for random balanced network
----------------------------------------
This script performs a mean-field analysis of the ... |
reviewboard/rbtools | rbtools/api/errors.py | Python | mit | 1,777 | 0 | from __future__ import unicode_literals
import six
from rbtools.utils.encoding import force_unicode
class APIError(Exception):
def __init__(self, http_status, error_code, rsp=None, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.http_status = http_status
self.error_code ... |
class BadRequestError(APIError):
def __str__(self):
lines = [super(BadRequestError, self).__str__()]
if self.rsp and 'fields' in self.rsp:
lines.append('')
for field, error in six.iteritems(self.rsp['fields']):
lines.append(' %s: %s' % (field, '; '.joi... | ))
return '\n'.join(lines)
class CacheError(Exception):
"""An exception for caching errors."""
class ServerInterfaceError(Exception):
def __init__(self, msg, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.msg = msg
def __str__(self):
"""Return the erro... |
stanfordnlp/coqa-baselines | rc/word_model.py | Python | mit | 3,203 | 0.003122 | # -*- coding: utf-8 -*-
"""
Module to handle word vectors and initializing embeddings.
"""
import numpy as np
from gensim.models.keyedvectors import KeyedVectors
from utils import constants as Constants
from utils.timer import Timer
from collections import Counter
###################################################... | #############
# Wo | rdModel Class #
################################################################################
class GloveModel(object):
def __init__(self, filename):
self.word_vecs = {}
self.vocab = []
with open(filename, 'r') as input_file:
for line in input_file.readlines():
... |
gotostack/swift | swift/cli/recon.py | Python | apache-2.0 | 36,535 | 0.000027 | #! /usr/bin/env python
# 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
... | (perc_none).1f%%, no_result: %(number_none)d, ' \
'reported: %(reported)d' % stats
| def _ptime(self, timev=None):
"""
:param timev: a unix timestamp or None
:returns: a pretty string of the current time or provided time
"""
if timev:
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timev))
else:
return time.strftime("%Y... |
baroquebobcat/pants | tests/python/pants_test/backend/python/test_pants_requirement.py | Python | apache-2.0 | 1,740 | 0.006897 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.backend.p... | self.assertIsInstance(python_requirement_library, PythonRequirementLibrary)
pants_requirement = PythonRequirement('pantsbuild.pants=={}'.format(pants_version()))
self.assertEqual([pants_requirement.requirement],
list(pr.requirement for pr in python_requirement_library.payloa | d.requirements))
def test_default_name(self):
self.add_to_build_file('3rdparty/python/pants', 'pants_requirement()')
python_requirement_library = self.target('3rdparty/python/pants')
self.assert_pants_requirement(python_requirement_library)
def test_custom_name(self):
self.add_to_build_file('3rdp... |
SlicerRt/SlicerDebuggingTools | PyDevRemoteDebug/ptvsd-4.1.3/ptvsd/_vendored/pydevd/pydev_ipython/inputhookpyglet.py | Python | bsd-3-clause | 3,345 | 0.002093 | # encoding: utf-8
"""
Enable pyglet to be used interacive by setting PyOS_InputHook.
Authors
-------
* Nicolas P. Rougier
* Fernando Perez
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under t... | ending events, a call to time.sleep is inserted. This is
needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
though for best performance.
"""
# We need to protect against a user pressing Control-C when IPython is
# idle and this is running. We trap | KeyboardInterrupt and pass.
try:
t = clock()
while not stdin_ready():
pyglet.clock.tick()
for window in pyglet.app.windows:
window.switch_to()
window.dispatch_events()
window.dispatch_event('on_draw')
fl... |
akvo/akvo-rsr | akvo/rsr/tests/usecases/test_change_project_parent.py | Python | agpl-3.0 | 4,628 | 0.002377 | # -*- coding: utf-8 -*-
# Akvo Reporting is covered by the GNU Affero General Public License.
# See more details in the license.txt file located at the root folder of the Akvo RSR module.
# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.
from datetime import date
from a... | (period_start=date(2020, 1, 1)).parent_period,
child_project.periods.get(period_star | t=date(2020, 1, 1))
)
self.assertEqual(
new_project.object.dimension_names.get(name='Foo').parent_dimension_name,
child_project.object.dimension_names.get(name='Foo')
)
self.assertEqual(
new_project.get_disaggregation('Foo', 'Bar').parent_dimension_val... |
cancerregulome/gidget | commands/maf_processing/python/archive/mergeGeneAndUnitprot.py | Python | mit | 2,322 | 0.001292 | import sys
import traceback
__author__ = 'xshu'
# global variables
refseq2uniprotMapping = {}
def showHelp():
print\
'''
This program updates MAF by adding a column of uniprot id list
Usage: %s
Parameter Description
-gene2refseq gene id to refse | q id mapping file
-refseq2uniprot refseq id to uniprot id mapping file
-output Output file
(eg. %s -gene2refseq <<absolute gene2refseq file path>> -refseq2uniprot <<abs | olute refseq2uniprot mapping file path>> \
-output <<absolute output file path>> )
''' % (sys.argv[0], sys.argv[0])
def loadMappings(refseq2uniprot):
global refseq2uniprotMapping
refseq2uniprotHandle = open(refseq2uniprot, "r")
refseq2uniprotHandle.readline()
for line in refs... |
tweemeterjop/thug | thug/DOM/Plugin.py | Python | gpl-2.0 | 1,536 | 0.001302 | #!/usr/bin/env python
#
# Plugin.py
#
# 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 will be useful,
# but WITHOUT ANY WARRANTY; wi... | dict.__init__(self, init)
def __getstate__(self):
return list(self.__dict__.items())
def __setstate__(self, items):
for key, val in items:
self.__dict__[key] = val
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, dict.__repr__(self))
def __setitem... | key, value):
return super(Plugin, self).__setitem__(key, value)
def __getitem__(self, name):
return super(Plugin, self).__getitem__(name)
def __delitem__(self, name):
return super(Plugin, self).__delitem__(name)
__getattr__ = __getitem__
__setattr__ = __setitem__
|
jchmura/suchary-django | api/models.py | Python | mit | 1,121 | 0.000892 | import json
from django.db import models
import requests
from Suchary.settings import GCM_API_KEY
class Device(models.Model):
registration_id = models.TextField()
android_id = models.TextField(unique=True)
alias = models.TextField(blank=True)
version = models.CharField(max_length=20)
model = mod... | rsion = models.CharField(max_length=20)
type = models.CharField(max_length=20)
active = models.BooleanField(default=True)
last_used = models.DateTimeField(auto_now=True)
last_seen = models.DateTimeField(auto_now_add=True)
created = models.DateTimeField(auto_now_add=True)
def send_data(self, dat... | load = {'registration_ids': [self.registration_id], 'data': data}
r = requests.post(url, data=json.dumps(payload), headers=header)
return r
def __str__(self):
if self.alias:
return str(self.alias)
return str(self.registration_id)
|
stczhc/neupy | tests/fitting/coval.py | Python | mit | 1,681 | 0.013087 |
# Atomic covalent radius data
# http://www.periodictable.com/Properties/A/CovalentRadius.an.html
# Updated Jun. 9th, 2016
class Covalent(object):
x = {
"H": 0.37, "He": 0.32, "Li": 1.34, "Be": 0.90, "B": 0.82, "C": 0.77,
"N": 0.75, "O": 0.73, "F": 0.71, "Ne": 0.69, "Na": 1.54, "Mg": 1.30,
"Al":... | "Ga": 1.26, "Ge": 1.22, "As": 1.19, "Se": 1.16, "Br": 1.14, "Kr": 1.10,
"Rb": 2.11, "Sr": 1.92, "Y": 1.62, "Zr": 1.48, "Nb": 1.37, "Mo": 1.45,
"Tc": 1.56, "Ru": 1.26, "Rh": 1.35, "Pd": 1.31, "Ag": 1.53, "Cd": 1.48,
"In": 1.44 | , "Sn": 1.41, "Sb": 1.38, "Te": 1.35, "I": 1.33, "Xe": 1.30,
"Cs": 2.25, "Ba": 1.98, "La": 1.69, "Ce": 0.00, "Pr": 0.00, "Nd": 0.00,
"Pm": 0.00, "Sm": 0.00, "Eu": 0.00, "Gd": 0.00, "Tb": 0.00, "Dy": 0.00,
"Ho": 0.00, "Er": 0.00, "Tm": 0.00, "Yb": 0.00, "Lu": 1.60, "Hf": 1.50,
"Ta": 1.38, "W": 1.46... |
erikdejonge/python_for_kids | chapter03/furniture_placeholder.py | Python | gpl-2.0 | 156 | 0.00641 | furniture = '%s: a device for finding furni | ture in the dark'
bodyp | art1 = 'Knee'
bodypart2 = 'Shin'
print(furniture % bodypart1)
print(furniture % bodypart2) |
gonzolino/heat | heat/engine/cfn/functions.py | Python | apache-2.0 | 18,650 | 0 | #
# 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
# ... |
except ValueError:
| raise ValueError(_('Arguments to "%s" must be of the form '
'[resource_name, attribute]') % self.fn_name)
return resource_name, attribute
def _resource(self, path='unknown'):
resource_name = function.resolve(self._resource_name)
try:
return self... |
PuZZleDucK/pixelated-user-agent | service/test/support/dispatcher/__init__.py | Python | agpl-3.0 | 700 | 0 | #
# Copyright (c) 2014 ThoughtWorks Deut | schland GmbH
#
# Pixelated 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) an | y later version.
#
# Pixelated is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero G... |
AlexLloyd1/pointy-mcpointface | pointy/database/team.py | Python | mit | 3,151 | 0.000952 | import os
from typing import List, Tuple
import psycopg2
from psycopg2.extensions import AsIs
from slackclient import SlackClient
api_token = os.environ.get('POINTY_APP_TOKEN')
def check_all_scores(conn, team_id: str, retry: bool = True) -> List[Tuple[str, int]]:
with conn.cursor() as cur:
try:
... | LUES (%s)""",
(team_id,)
)
except psycopg2.ProgrammingError:
pass
conn.commit()
user_ids = []
slack_client = SlackClient(api_token)
resp = slack_client.api_call(
'users.list',
presence=False
)
| for user in resp['members']:
if user['deleted'] is False and user['is_bot'] is False and user['id'] != 'USLACKBOT':
user_ids.append(user['id'])
with conn.cursor() as cur:
args_str = b",".join(cur.mogrify('(%s,0)', (uid,)) for uid in user_ids)
cur.execute(
b"""INSERT ... |
Azure/azure-sdk-for-python | sdk/elastic/azure-mgmt-elastic/azure/mgmt/elastic/operations/_vm_host_operations.py | Python | mit | 5,849 | 0.004787 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
| def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
error = self._deser... |
beeftornado/sentry | tests/sentry/deletions/test_repository.py | Python | bsd-3-clause | 2,925 | 0.000684 | from __future__ import absolute_import
from sentry.utils.compat.mock import patch
from django.core import mail
from sentry.exceptions import PluginError
from sentry.models import Commit, Repository, ScheduledDeletion
from sentry.tasks.deletion import run_deletion
from sentry.testutils import TestCase
class DeleteR... | anization_id=org.id, key="1234abcd"
)
deletion = ScheduledDeletion.schedule(repo, days=0)
deletion.update(in_progress=True)
with self.tasks():
run_deletion(deletion.id)
assert not Repository.objects.filter(id=repo.id).exists()
assert not Commit.objects.filt... | .plugins.providers.dummy.repository.DummyRepositoryProvider.delete_repository")
def test_delete_fail_email(self, mock_delete_repo):
mock_delete_repo.side_effect = PluginError("foo")
org = self.create_organization()
repo = Repository.objects.create(
organization_id=org.id, provid... |
muttiopenbts/nazar | masstive.py | Python | gpl-2.0 | 3,056 | 0.001636 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 1 20:14:54 2015
@author: mkocbayi
Script for kicking of masscan scans.
Argument 1 should be location of file containing cidr blocks
to scan. e.g. /opt/masscan/targets/US-San Diego.txt
10.0.0.0/24
"""
import csv
import re
import time
import os
import sys
from netaddr impo... | log(output):
datetime = time.strftime("%x") + ' ' + time.strftime("%X")
with open(LOG_FILE, 'a+') as f:
f.write("%s: %s\n" % (datetime, output))
def run_cmd(cmd):
'''
Call OS cmd
'''
result = ''
p = os.popen(cmd, "r")
while 1:
line = p.readline()
result += line
... | txt
# Also convert spaces into underscore
country_search = re.search('.*/(.*?)-(.*)$', filename, )
if country_search:
country = country_search.group(1)
return country.replace(" ", "_")
def get_city_from_file(filename):
# Expect file name to look like this /path/US-SAN DIEGO.txt
# A... |
pzia/keepmydatas | src/KmdImages.py | Python | mit | 7,111 | 0.016172 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Detect same images and try to merge metadatas before deleting duplicates"""
import PIL.Image as Image
import PIL.ImageChops as ImageChops
import sys
import os
import pyexiv2
import datetime
import logging
#Handler for merging properties
def handler_mergeList(a, b):
... | nI]["Iptc.Application2.Keywords"] = handler_mergeList(metas[mainI]["Iptc.Application2.Keywords"].value, exiv_changed_keywords)
logging.info("Writing properties to %s", mainI)
if doit :
metas[mainI].write()
f | or f in sameImages[1:] :
logging.info("Removing %s", f)
if doit :
os.remove(f)
for m in metas.keys():
del(metas[m])
del(metas)
def cleanDir(folder, doit = False, quick = True):
logging.info("Cleaning %s", folder)
samef = compareImagesFolder(folder, quick ... |
Vauxoo/stoqdrivers | stoqdrivers/escp.py | Python | lgpl-2.1 | 2,767 | 0.005782 | # -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
##
## Copyright (C) 2007 Async Open Source <http://www.async.com.br>
## All rights reserved
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU Lesser General Public License as published by
## the Free Software F... | = 'p'
CMD_FORM_FEED = '\xff'
CMD_EJECT = '\x19'
QUALITY_DRAFT = '0'
QUALITY_LQ = '1'
QUALITY_NLQ = '1'
class EscPPrinter(object):
def __init__(self, device | ):
self.device = device
self.fp = open(device, 'w')
self._command(CMD_INIT)
def _command(self, command, *args):
chars = command
for arg in args:
if arg is True:
v = '1'
elif arg is False:
v = '0'
else:
... |
hughperkins/pub-prototyping | py/pytorch/test_rnn.py | Python | apache-2.0 | 1,950 | 0.001538 | import torch
from torch import autograd, nn
batch_size = 1
seq_len = 7
input_size = 6
hidden_size = 4
example = [3, 2, 0, 0, 4, 5, 1, 1]
# input = autograd.Variable(torch.rand(seq_len, batch_size, input_size))
# print('input.size()', input.size())
embedding = nn.Embedding(input_size, hidden_size)
rnn = torch.nn.RN... | e, input_size)
# print('out_unembedded.size()', out_unembedded.size())
# print('target.size()', target.size())
loss = torch.nn.functional.nll_loss(out_unembedded, target.view(-1))
# prin | t('epoch %s loss %s' % (epoch, loss.data[0]))
if epoch % 500 == 0:
print('epoch', epoch)
print('input', input.data.view(1, -1))
print('target', target.data.view(1, -1))
print('pred', pred.data.view(1, -1))
# print('out', out.data.view(1, -1))
rnn.zero_grad()
embedding.zer... |
tomhenderson/ns-3-dev-git | examples/wireless/mixed-wired-wireless.py | Python | gpl-2.0 | 17,060 | 0.008968 | # /*
# * 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 will be useful,
# * but WITHOUT ANY WARRANTY; without even the ... | #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
# Reset the address base-- all of the CSMA networks will b | e in
# the "172.16 address space
ipAddrs.SetBase(ns.network.Ipv4Address("172.16.0.0"), ns.network.Ipv4Mask("255.255.255.0"))
for i |
xrmx/django | django/db/models/fields/__init__.py | Python | bsd-3-clause | 92,054 | 0.000652 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import collections
import copy
import datetime
import decimal
import math
import uuid
import warnings
from base64 import b64decode, b64encode
from django.apps import apps
from django.db import connection
from django.db.models.lookups import default_looku... | eld', 'FloatField',
'GenericIPAddressField', 'IPAddressField', 'IntegerField', 'NOT_PROVIDED',
'NullBooleanField', 'PositiveIntegerField', 'PositiveSmallIntegerField',
'SlugField', 'SmallIntegerField', 'TextField', 'TimeField', 'URLField',
'UUIDField',
)]
class Empty(object):
pass
class NOT_PROV... | NK_CHOICE_DASH = [("", "---------")]
def _load_field(app_label, model_name, field_name):
return apps.get_model(app_label, model_name)._meta.get_field(field_name)
# A guide to Field parameters:
#
# * name: The name of the field specified in the model.
# * attname: The attribute to use on the model obj... |
captainhungrykaboom/MTAT.TK.006 | 27. märts - 2. aprill ülesanded/sõanstik2.py | Python | mit | 2,725 | 0.010169 |
# -- PROGRAMMI 1. OSA - FUNKTSIOON TUTVUSTUS() --
# Defineerime funktsiooni, mis trükib ekraanile programmi tutvustuse ja sõnastikus olevate sõnade arvu
def tutvustus():
print("Inglise-eesti sõnastik (" + str(len(inglise_sõnad)) + " sõna)")
print("'v' - välju")
print("'a' - abi")
# -- PROGRAMMI 2. OS... | ad', siis otsime sõnale vaste ning väljastame selle
elif | otsing in inglise_sõnad:
print('Inglise keeles: ' + otsing)
# Leiame, mis indeksiga kohal on 'otsing' listis 'inglise_sõnad
otsitava_sõna_indeks = inglise_sõnad.index(otsing)
# Vaste on samal kohal listis eesti_sõnad
print('Eesti keeles: ' + eesti_sõnad[otsitava_sõna_indeks])
... |
amoya-dx/account-financial-tools | currency_rate_update/__openerp__.py | Python | agpl-3.0 | 1,576 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2009 CamptoCamp. All rights reserved.
# @author Nicolas Bessi
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Publi... | to ensure account security groups are present
],
| "data": [
"view/service_cron_data.xml",
"view/currency_rate_update.xml",
"view/company_view.xml",
"security/rule.xml",
"security/ir.model.access.csv",
],
"demo": [],
"active": False,
'installable': True
}
|
census-instrumentation/opencensus-python | opencensus/trace/attributes.py | Python | apache-2.0 | 2,383 | 0 | # Copyright 2017, OpenCensus 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 w... | _attribute(self, key, value):
"""Set a key value pair."""
self.attributes[key] = value
def delete_attribute(self, key):
"""Delete an attribute given a key if existed."""
self.attributes.pop(key, None)
def get_attribute(self, key):
"""Get a attribute value."""
re... | }
for key, value in self.attributes.items():
key = utils.check_str_length(key)[0]
value = _format_attribute_value(value)
if value is not None:
attributes_json[key] = value
result = {
'attributeMap': attributes_json
}
ret... |
gttechsign/iris-panel | iris/core/migrations/0004_remove_redundant_packs.py | Python | gpl-2.0 | 15,684 | 0.006886 | # -*- coding: utf-8 -*-
#pylint: skip-file
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
# Note: Remember to use orm['appname.ModelName'] rather th... | , {'to': u"orm['auth.Group']", 'unique': 'True', 'primary_key': 'True'}),
'role': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'})
},
'core.image': {
'Meta': {'object_name': 'Image'},
'arch': ('django.db.models.fields.TextField', [],... | id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.TextField', [], {}),
'product': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['core.Product']"}),
'target': ('django.db.models.fields.TextField', [], {})
... |
mwolff44/yawd-admin | yawdadmin/utils.py | Python | bsd-3-clause | 6,198 | 0.004034 | # -*- coding: utf-8 -*-
import datetime
import json
import time
from oauth2client.client import AccessTokenRefreshError
from django.core.cache import cache
from django.utils.translation import get_language
from django.utils.encoding import force_str
from yawdadmin.resources import admin_site
from conf import settings a... | .
"""
# Hit the cache
cached = {}
if ls.ADMIN_CACHE_DB_OPTIONS:
cached = cache.get(get_option_cache_key(optionset_label), {})
if cached:
optio | ns = cached
else:
options = AppOption.objects.filter(optionset_label=optionset_label)
if ls.ADMIN_CACHE_DB_OPTIONS:
try:
cache.set(get_option_cache_key(optionset_label), options,
ls.ADMIN_CACHE_DB_OPTIONS)
except OperationalError:
... |
cloudant/couchdb-mango | test/06-text-default-field-test.py | Python | apache-2.0 | 2,174 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the ... | ervice(), "requires text service")
class NoDefaultFieldWithAnalyzer(mango.UserDocsTextTests):
DEFAULT_FIELD = {
"enabled": False,
"analyzer": "keyword"
}
def test_basic(self):
docs = self.db.find({"$text": "Ramona"})
assert len(docs) == 0
def test_other_fields_exist(se... |
@unittest.skipUnless(mango.has_text_service(), "requires text service")
class DefaultFieldWithCustomAnalyzer(mango.UserDocsTextTests):
DEFAULT_FIELD = {
"enabled": True,
"analyzer": "keyword"
}
def test_basic(self):
docs = self.db.find({"$text": "Ramona"})
assert len(doc... |
jeryfast/piflyer | piflyer/zmq_comm.py | Python | apache-2.0 | 2,795 | 0.006082 | import zmq
import random
import time
import zmq_ports as ports
import zmq_topics as topic
from websocket import create_connection
RCV_DELAY=0.01
WSPORT = 9000
########### WEBSOCKET EVENTS
########### WEBSOCKET EVENTS
if __name__ == '__main__':
#print("Starting comm")
# IPC
context = zmq.Context()
# ... |
browser_subsc | riber = context.socket(zmq.SUB)
browser_subscriber.connect("tcp://localhost:%s" % ports.TORNADO_PUB)
browser_subscriber.setsockopt_string(zmq.SUBSCRIBE, topic.COMMAND_TOPIC)
# Subscribe to gps
gps_subscriber = context.socket(zmq.SUB)
gps_subscriber.connect("tcp://localhost:%s" % ports.GPS_PUB)
... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/M2Crypto/m2urllib.py | Python | agpl-3.0 | 2,124 | 0.006591 | """M2Crypto enhancement to Python's urllib for handling
'https' url's.
Copyright (c) 1999-2003 Ng Pheng Siong. All rights reserved."""
import string, sys, urllib
from urllib import *
import SSL
import httpslib
DEFAULT_PROTOCOL='sslv23'
def open_https(self, url, data=None, ssl_context=None):
if ssl_context is ... | host = unquote(host)
realhost = host
else:
host, selector = url
urltype, rest = splittype(selector)
url = rest
user_passwd = None
if string.lower(urltype) != 'http':
realhost = None
else:
realhost, rest = splithost(rest)
if... | host:
user_passwd, realhost = splituser(realhost)
if user_passwd:
selector = "%s://%s%s" % (urltype, realhost, rest)
#print "proxy via http:", host, selector
if not host: raise IOError, ('http error', 'no host given')
if user_passwd:
import base64
... |
quake0day/oj | wordbreak__.py | Python | mit | 501 | 0.007984 | class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: Set[str]
:rtype: bool
"""
def dfs(s, d):
if s in d:
| return True
for i in xrange(len(s)):
if s[:i] in d:
return dfs(s[i:], d)
if dfs(s, wordDict):
| return True
return False
a = Solution()
print a.wordBreak("leetcode", ["leet", "code"]) |
CodyKochmann/generators | generators/tests/__init__.py | Python | mit | 182 | 0.005495 |
from .test_apply_to_last import *
from .test_chunk_on import *
from .test_chunk | s import *
from .test_map_parallel import *
from .test_skip_errors import *
from .test_switch import * | |
webhamster/pidart | gamemanager/receive-test-circuits.py | Python | gpl-3.0 | 722 | 0.019391 | #!/usr/bin/env python
from circuits import Component, Debugger, Event, handler
from | circuits.io.serial import Serial
#from time import sleep
class helloEv(Event):
"""hello Event"""
class SerInput(Component):
def __init__(self, device = '/dev/ttyUSB0'):
super(SerInput, self).__init__()
Serial(device).register(self)
def read(self, data):
print ('Received: %r' ... | nt ('test')
if __name__ == "__main__":
(SerInput(device = '/dev/ttyUSB0') + Debugger()).run()
''' + Debugger() + TT()
d.run()'''
|
poojavade/Genomics_Docker | Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/bx_python-0.7.1-py2.7-linux-x86_64.egg/EGG-INFO/scripts/nib_length.py | Python | apache-2.0 | 203 | 0.019704 | #!/usr/bin/python2.7
"""
Print the number of bases in a nib file.
usage: %prog nib_file
"""
from bx.seq import nib as seq_nib
import sys
nib = se | q_nib.N | ibFile( file( sys.argv[1] ) )
print nib.length
|
hryamzik/ansible | lib/ansible/modules/cloud/scaleway/scaleway_sshkey.py | Python | gpl-3.0 | 5,245 | 0.001335 | #!/usr/bin/python
#
# Scaleway SSH keys management module
#
# Copyright (C) 2018 Online SAS.
# https://www.scaleway.com
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future_ | _ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = { |
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: scaleway_sshkey
short_description: Scaleway SSH keys management module
version_added: "2.6"
author: Remy Leone (@sieben)
description:
- This module manages SSH keys on Scaleway account
... |
rven/odoo | addons/sale_stock/models/sale_order.py | Python | agpl-3.0 | 33,492 | 0.004718 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
import logging
from datetime import datetime, timedelta
from collections import defaultdict
from odoo import api, fields, models, _
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT, float_compare, float... | tate == 'sale':
for order in self:
pre_order_line_qty = {order_line: order_line.product_uom_qty for order_line in order.mapped('order_line') if not order_line.is_expense}
if valu | es.get('partner_shipping_id'):
new_partner = self.env['res.partner'].browse(values.get('partner_shipping_id'))
for record in self:
picking = record.mapped('picking_ids').filtered(lambda x: x.state not in ('done', 'cancel'))
addresses = (record.partner_shipping_id.... |
hoechenberger/psychopy | psychopy/tests/test_misc/test_locale.py | Python | gpl-3.0 | 1,076 | 0.006579 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from builtins import object
import pytest
import locale
from psychopy import localization
from psychopy.localization import _translate
welcome = u'Welcome to PsychoPy3!'
trans = {'en': welcome,
'ja': u'PsychoPy3へようこそ!'
}
### needs rewriting since locali... | out = _tr | anslate(welcome)
assert setlang == lang.lower()[:2]
assert out == trans[setlang]
#lo = 'en'
#localization.init(lo)
#for lang in ['', None, [], 'junk']:
# setlang = localization.init(lang)
# assert setlang == lo
|
nvbn/deploy_trigger | deploy_trigger/settings/local_nvbn.py | Python | mit | 1,371 | 0.003647 | DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'db', # Or path to databas... | ',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
| 'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
|
bytedance/fedlearner | fedlearner/data_join/raw_data_iter_impl/tf_record_iter.py | Python | apache-2.0 | 7,400 | 0.001081 | # Copyright 2020 The FedLearner 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... | ure(
int64_list=tf.train.Int64List(value=[value]))
)
self._set_tf_record(example.SerializeToString(), cache)
if self._csv_record is not None:
self._csv_record = None
self._gc_example(examp | le)
def _parse_example(self, record_str):
try:
if not self._parse_example_error:
example = tf.train.Example()
example.ParseFromString(record_str)
return example
except Exception as e: # pylint: disable=broad-except
logging.erro... |
google/ml-fairness-gym | environments/attention_allocation.py | Python | apache-2.0 | 13,033 | 0.007366 | # coding=utf-8
# Copyright 2022 The ML Fairness Gym 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 applicab... | re discovered
# incidents, for whic | h attention needs to be allocated to be discovered
discovered_incident_weight = attr.ib(default=1.0) # type: float
# Reported inicdents weight - weights how many incidents are reported, which
# are observed from a location without attention being allocated there.
reported_incident_weight = attr.ib(default=0.0)... |
Qualys/community | scan-blackout/QualysAPI.py | Python | gpl-3.0 | 8,803 | 0.004998 | import requests
import xml.etree.ElementTree as ET
from time import sleep
class QualysAPI:
"""Class to simplify the making and handling of API calls to the Qualys platform
Class Members
=============
server : String : The FQDN of the API server (with https:// prefix)
user : S... | ion knows how many attempts have been made so far
resp = self.ma | keCall(url=url, payload=payload,headers=headers, retryCount=retryCount)
# Handle rate limit failures
if 'X-RateLimit-ToWait-Sec' in resp.headers.keys():
if resp.headers['X-RateLimit-ToWait-Sec'] > 0:
# If this response header has a value > 0, we know we have to wait some tim... |
sakura-internet/saklient.python | saklient/cloud/models/model_licenseinfo.py | Python | mit | 4,306 | 0.011686 | # -*- coding:utf-8 -*-
# This code is automatically transpiled by Saklient Translator
import six
from ..client import Client
from .model import Model
from ..resources.resource import Resource
from ..resources.licenseinfo import LicenseInfo
from ...util import Util
import saklient
str = six.text_type
# module saklien... | lf._offset(offset)
## 次に取得するリストの上限レコード数を指定します。
#
# @param {int} count 上限レコード数
# @return {saklient.cloud.models.model_licenseinfo.Model_LicenseInfo} this
def limit(self, count):
Util.validate_type(count, "int")
return self._limit(count)
## Web APIのフィルタリング設定を直接指定します。
... | @return {saklient.cloud.models.model_licenseinfo.Model_LicenseInfo}
def filter_by(self, key, value, multiple=False):
Util.validate_type(key, "str")
Util.validate_type(multiple, "bool")
return self._filter_by(key, value, multiple)
## 次のリクエストのために設定されているステートをすべて破棄します。
#
# @re... |
legalsylvain/OpenUpgrade | openerp/modules/graph.py | Python | agpl-3.0 | 8,097 | 0.00247 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
# Copyright (C) 2010-2011 OpenERP s.a. (<http://openerp.com>).
#
# This program is free software: you ca... | age' in the graph
if reduce(lambda x, y: x and y in self, deps, True):
if not package in current:
packages.pop(0)
continue
later.clear()
current.remove(package)
node | = self.add_node(package, info)
node.data = info
for kind in ('init', 'demo', 'update'):
if package in tools.config[kind] or 'all' in tools.config[kind] or kind in force:
setattr(node, kind, True)
else:
later.add(pack... |
Grumbel/rfactortools | rfactortools/util.py | Python | gpl-3.0 | 4,219 | 0.000237 | # Utility functions
# Copyright (C) 2014 Ingo Ruhnke <grumbel@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, either version 3 of the License, or
# (at your option) any later versio... | se of the filenames.
"""
if not rest:
return [os.path.normpat | h(root)]
else:
results = []
if os.path.isdir(root):
for f in os.listdir(root):
if f.lower() == rest[0].lower():
p = os.path.join(root, f)
results += _lookup_path_icase(p, rest[1:])
return results
def lookup_path_icase_mult... |
skibblenybbles/django-daydreamer | daydreamer/tests/views/behaviors/http/base.py | Python | mit | 652 | 0.006135 | from __future__ import unicode_literals
import calendar
import datetime
from django.utils import http as http_utils
from daydreamer.tests.views.core import http
class TestCase(http.TestCase):
"""
Common utilities for testing HTTP view behaviors.
"""
# Utilities.
d | ef format_ | etag(self, etag):
"""
Quote the given ETag for use in an HTTP header.
"""
return http_utils.quote_etag(etag)
def format_datetime(self, dt):
"""
Format a datetime for use in an HTTP header.
"""
return http_utils.http_date(calendar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.