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 |
|---|---|---|---|---|---|---|---|---|
rory/openstreetmap-remove-tags | osmrmtags/__init__.py | Python | agpl-3.0 | 1,564 | 0.004476 | from imposm.parser import OSMParser
from osmwriter import OSMWriter
def rm_tags(tags, tags_to_keep):
new_tags = {}
for ok_tag in tags_to_keep:
if ok_tag in tags:
new_tags[ok_tag] = tags[ok_tag]
return new_tags
class T | agRemover(object):
def __init__(self, output_writer, tags_to_keep):
self.output_writer = output_writer
self.tags_to_keep = tags_to_keep
def nodes(self, nodes):
for node in nodes:
id, tags, (lat, lon) = node
new_tags = rm_tags(tags, self.tags_to_keep)
... | tags, nodes = way
new_tags = rm_tags(tags, self.tags_to_keep)
if len(tags) > 0:
self.output_writer.way(id, new_tags, nodes)
def remove_tags(input_filename, output_fp, tags_to_keep, close_output_fp=True):
output_writer = OSMWriter(fp=output_fp)
remover = TagRemover(ou... |
bytedance/fedlearner | fedlearner/model/tree/trainer.py | Python | apache-2.0 | 21,533 | 0.000557 | # 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... | fedlearner.common.argparse_util import str_as_bool
from fedlearner.trainer.bridge import Bridge
from fedlearner.model.tree.tree imp | ort BoostingTreeEnsamble
from fedlearner.model.tree.trainer_master_client import LocalTrainerMasterClient
from fedlearner.model.tree.trainer_master_client import DataBlockInfo
def create_argument_parser():
parser = argparse.ArgumentParser(
description='FedLearner Tree Model Trainer.')
parser.add_argum... |
bfontaine/edt2ics | edt2ics/ical.py | Python | mit | 3,060 | 0.002941 | #! /usr/bin/env python
# -*- coding: UTF-8 -*-
from datetime import date, datetime, timedelta
from icalendar import Calendar, Event, vRecur
import json
import os.path
from os.path import dirname
from uuid import uuid4
class iCalSchedule(object):
DAYS = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU']
def __init_... | *map(lambda e: int(e, 10), s.split('-')))
def add_event(self, ev):
"""
Add a new recurrent event to t | his schedule
"""
day = self._get_first_weekday(ev.day)
dtstart = datetime.combine(day, ev.tstart)
dtend = datetime.combine(day, ev.tend)
tz_params = {'tzid': 'Europe/Paris'}
iev = Event()
iev.add('uid', str(uuid4()))
iev.add('status', 'confirmed')
... |
vrutkovs/atomic-reactor | tests/plugins/test_compare_components.py | Python | bsd-3-clause | 4,488 | 0.000891 | """
Copyright (c) 2017 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import print_function, unicode_literals
import os
import json
from flexmock import flexmock
from atomic_reactor.constants ... | f_dir = 'df_dir'
def simplegen(x, y):
yield "some\u2018".encode('utf-8')
flexmock(self.tasker, build_image_from_path=simplegen)
def get_built_image_info(self):
return {'Id': 'some'}
def inspect_built_image(self):
return None
def ensure_not_built(self):
... | er())
setattr(workflow, 'source', MockSource(tmpdir))
setattr(workflow.builder, 'source', MockSource(tmpdir))
setattr(workflow, 'postbuild_result', {})
return workflow
def mock_metadatas():
json_x_path = os.path.join(FILES, "example-koji-metadata-x86_64.json")
json_p_path = os.path.join(FILES,... |
Tayamarn/socorro | webapp-django/crashstats/crashstats/tests/test_pipelinecompilers.py | Python | mpl-2.0 | 1,590 | 0 | import os
import shutil
import tempfile
from crashstats.base.tests.testbase import DjangoTestCase
from crashstats.crashstats.pipelinecompilers import GoogleAnalyticsCompiler
from crashstats import crashstats
SOURCE_FILE = os.path.join(
crashstats.__path__[0], # dir of the module
'static/crashstats/js/socorro... | rt not compiler.match_file('/foo/bar.js')
def test_compile(self):
compiler = GoogleAnalyticsCompiler(False, None)
with self.settings(GOOGLE_ANALYTICS_ID='UA-12345-6'):
| outfile = os.path.join(self.tmp_static, 'google-analytics.min.js')
assert not os.path.isfile(outfile)
compiler.compile_file(SOURCE_FILE, outfile)
assert not os.path.isfile(outfile)
# Try again
compiler.compile_file(SOURCE_FILE, outfile, outdated=True)
... |
keithhamilton/blackmaas | bin/pilconvert.py | Python | bsd-3-clause | 2,387 | 0.002095 | #!/Users/keith.hamilton/Documents/GitHub/keithhamilton/blackmaas/bin/python
#
# The Python Imaging Library.
# $Id$
#
# convert image files
#
# History:
# 0.1 96-04-20 fl Created
# 0.2 96-10-04 fl Use draft mode when converting images
# 0.3 96-12-30 fl Optimize output (PNG, JPEG)
# 0.4 97-01-18 fl ... | len(argv) != 2:
usage()
try:
im = Image.open(argv[0])
if convert and im.mode != convert:
| im.draft(convert, im.size)
im = im.convert(convert)
if format:
im.save(argv[1], format, **options)
else:
im.save(argv[1], **options)
except:
print("cannot convert image", end=' ')
print("(%s:%s)" % (sys.exc_info()[0], sys.exc_info()[1]))
|
Giftingnation/GN-Oscar-Custom | oscar/apps/wishlists/abstract_models.py | Python | bsd-3-clause | 4,545 | 0.00044 | import hashlib
import random
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from oscar.core.compat import AUTH_USER_MODEL
class AbstractWishList(models.Model):
"""
Represents a user's wish lists of products.
A user can h... | if not self.pk or kwargs.get('force_insert', False):
self.key = self.__class__.random_key()
| super(AbstractWishList, self).save(*args, **kwargs)
@classmethod
def random_key(cls, length=6):
"""
Get a unique random generated key based on SHA-1 and owner
"""
while True:
key = hashlib.sha1(str(random.random())).hexdigest()[:length]
if cls._defa... |
ellisdg/3DUnetCNN | unet3d/models/pytorch/fcn/__init__.py | Python | mit | 21 | 0 | fr | om .fcn import FCN
| |
aikramer2/spaCy | spacy/tests/doc/test_doc_api.py | Python | mit | 10,763 | 0.001487 | # codin | g: utf-8
from __future__ import unicode_literals
from ..util import get_doc
from ...tokens import Doc
from ...vocab import Vocab
from ...attrs import LEMMA
from ...tokens import Span
import pytest
import numpy
@pytest.mark.parametrize('text', [["one", "two", "three"]])
def test_doc_api_compare_by_string_position(en... | et_doc(en_vocab, text)
# Get the tokens in this order, so their ID ordering doesn't match the idx
token3 = doc[-1]
token2 = doc[-2]
token1 = doc[-1]
token1, token2, token3 = doc
assert token1 < token2 < token3
assert not token1 > token2
assert token2 > token1
assert token2 <= token3
... |
Exgibichi/statusquo | test/functional/create_cache.py | Python | mit | 841 | 0.003567 | #!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http:/ | /www.opensource.org/licenses/mit-license.php.
"""Create a blockchain cache.
Creating a cache of the blockchain speeds up test execution when running
multiple functional tests. This helper script is executed by test_runner when multiple |
tests are being run in parallel.
"""
from test_framework.test_framework import StatusquoTestFramework
class CreateCache(StatusquoTestFramework):
def __init__(self):
super().__init__()
# Test network and test nodes are not required:
self.num_nodes = 0
self.nodes = []
def set... |
jss-emr/openerp-7-src | openerp/addons/mail/wizard/mail_compose_message.py | Python | agpl-3.0 | 12,527 | 0.003193 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... | default_model or active_model
- default_res_id or active_id
- reply: active_id of a message the user replies to
- default_parent_id or message_id or active_id: ID of the
mail.message we reply to
- message.res_model or default_model
... | odel or active_model
"""
if context is None:
context = {}
result = super(mail_compose_message, self).default_get(cr, uid, fields, context=context)
# get some important values from context
composition_mode = context.get('default_composition_mode', context.get('mail.co... |
vpp-dev/vpp | test/test_util.py | Python | apache-2.0 | 512 | 0 | #!/usr/bin/env python3
"""Test framework utility functions tests"""
import unittest
from framework import VppTestRunner
from vpp_papi import mac_pton, mac_ntop
class TestUtil (unittest.TestCase):
""" MAC to binary and back """
def | test_mac_to_binary(self):
mac = 'aa:bb:cc:dd:ee:ff'
b = mac_pton(mac)
mac2 = mac_ntop(b)
self.assertEqual(type(mac), type(mac2))
self.asser | tEqual(mac2, mac)
if __name__ == '__main__':
unittest.main(testRunner=VppTestRunner)
|
flupzor/newsdiffs | news/parsers/tests/test_utils.py | Python | mit | 1,938 | 0 | from django.test import TestCase
from pyquery import PyQuery as pq
from ..utils import collapse_whitespace, html_to_text
class UtilsTests(TestCase):
def test_collapse_whitespace(self):
text = '\r\n\f\u200b \n\t '
self.assertEqual(collapse_whitespace(text), "")
def test_html_to_text_one_elem... | tEqual(
"\u0041 simple test case \u00A9 with a tail \u00A9\n", text
)
def test_html_to_text_with_script_with_children(self):
html = pq("<div>A simple test case ©<script><p>This should "
"be ignored as well</p>This should be ignored.</script> "
... | a tail ©</div>")
text = html_to_text(html)
self.assertEqual(
"\u0041 simple test case \u00A9 with a tail \u00A9\n", text
)
def test_html_to_text_multiple_levels(self):
html = pq("<div>A test case © <div><p>with multiple "
"levels </p>and ... |
denverfoundation/storybase | apps/storybase_help/admin.py | Python | mit | 1,189 | 0.003364 | from django import forms
from django.conf import settings
from django.contrib import admin
from storybase.admin import StorybaseModelAdmin, StorybaseStackedInline
from storybase_help.models import HelpTranslation, Help
class HelpTranslationAdminForm(forms.ModelForm):
class Meta:
model = HelpTranslation
... | attrs={'cols': 80, 'rows': 30},
mce_attrs={'theme': 'advanced', 'force_p_newlines': False, 'forced_root_block': '', 'theme_advanced_toolbar_location': 'top', 'plugins': 'table', 'theme_advanced_buttons3_add': 'tablecontrols', 'theme_advanced_st | atusbar_location': 'bottom', 'theme_advanced_resizing' : True},
),
}
class HelpTranslationInline(StorybaseStackedInline):
model = HelpTranslation
form = HelpTranslationAdminForm
extra = 1
class HelpAdmin(StorybaseModelAdmin):
inlines = [HelpTranslationInline]
prefix_i... |
buffer/thug | thug/DOM/Crypto.py | Python | gpl-2.0 | 1,112 | 0.001799 | #!/usr/bin/env python
#
# Crypto.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... | pass
@property
def enableSmartCardEvents(self):
return False
@property
def version(self):
return "2.4"
def disableRightClick(self):
pass
| def importUserCertificates(self, nickname, cmmfResponse, forceToBackUp): # pylint:disable=unused-argument
return ""
def logout(self):
pass
|
pauliacomi/pyGAPS | src/pygaps/modelling/henry.py | Python | mit | 3,834 | 0.000261 | """Henry isotherm model."""
import numpy
from pygaps.modelling.base_model import IsothermBaseModel
class Henry(IsothermBaseModel):
r"""
Henry's law. Assumes a linear dependence of adsorbed amount with pressure.
.. math::
n(p) = K_H p
Notes
-----
The simplest method of describing a... | ""
return self.params["K"] * pressure
def initial_guess(self, pressure, loading):
"""
Return initial gu | ess for fitting.
Parameters
----------
pressure : ndarray
Pressure data.
loading : ndarray
Loading data.
Returns
-------
dict
Dictionary of initial guesses for the parameters.
"""
saturation_loading, langmuir_k... |
knorby/boxeeremotelib | boxeeremotelib/utils.py | Python | bsd-2-clause | 951 | 0.005258 | import random
class MultiResultCallbackHandler(object):
def __init__(self, cb=None):
self._count = 0
self._results = []
self._cb = cb
def result_cb(res):
self._results.append(res) | if len(self._results)==self._count:
self._fire()
self._result_cb = result_cb
def _fire(self):
if self._cb:
self._cb(self._results)
def get_cb(self):
self._count+=1
return self._result_cb
class MultiBoolCallbackHandler(MultiResultCallbackHandler):
... | |
noironetworks/neutron | neutron/tests/unit/cmd/upgrade_checks/test_checks.py | Python | apache-2.0 | 1,114 | 0 | # Copyright 2018 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the Licen | se. 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 License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the... | e.
import mock
from oslo_upgradecheck.upgradecheck import Code
from neutron.cmd.upgrade_checks import checks
from neutron.tests import base
class TestChecks(base.BaseTestCase):
def setUp(self):
super(TestChecks, self).setUp()
self.checks = checks.CoreChecks()
def test_get_checks_list(self)... |
bowen0701/algorithms_data_structures | alg_shortest_game.py | Python | bsd-2-clause | 1,558 | 0.002567 | """Shortest game.
When we play games, we always bet in one of two ways in each game:
- betting one chip
- betting all-in
Wins are paid equal to the wager, so if we bet C chips and wins,
we get 2C chips back.
Suppose yesterday was a lucky day for us, we won every game we played.
Starting with 1 chip and leaving the ... | ontinue playing game for N-1 | with K all-in opportunities.
return 1 + shortest_game(N - 1, K)
def main():
# Output: 7
N = 8
K = 0
print(shortest_game(N, K))
# Output: 6
N = 18
K = 2
print(shortest_game(N, K))
# Output: 4
N = 10
K = 10
print(shortest_game(N, K))
# Output: 0
N = 1
... |
indirectlylit/whattowatch | data-utils/_fetch_new_rt_data.py | Python | mit | 1,292 | 0.001548 | import json
import os
import time
from rottentomatoes import RT
BOX_OFFICE_COUNTRIES = [
"us",
"in",
"uk",
"nl",
]
LIMIT = 50 # max allowed by rotten tomatoes
OUTPUT_FILE = "download/more_movies.json"
def main():
assert os.environ["RT_KEY"], "Your Rotten Tomatoes API key sh... | # NOTE: you should have your API key stored in RT_KEY before this will work
movies = []
link_template = ""
for country in BOX_OFFICE_COUNTRIES:
print "requesting box office hits for {}".format(country)
r = rt.lists('movies', 'box_office', limit=LIMIT, country=country)
movies += r[... | time.sleep(10) # respect our API limits!
# to maintain compatibility with movies.json fields, our top level dict
# should have the following fields:
# total (int)
# movies (list)
# link_template (string)
total = len(movies)
result = {
"total": total,
"movies"... |
mjuric/duplicity | duplicity/backends/lftpbackend.py | Python | gpl-2.0 | 9,388 | 0.001172 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright 2002 Ben Escoto <ben@emerose.org>
# Copyright 2007 Kenneth Loafman <kenneth@loafman.com>
# Copyright 2010 Marcel Pennewiss <opensource@pennewiss.de>
# Copyright 2014 Edgar Soldin
# - webdav, fish, sftp support
# - htt... | erification switches
# - debug output
#
# This file is part of duplicity.
#
# Duplicity is free software; you can redistribute it and | /or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# Duplicity is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# ... |
lavakyan/mstm-spectrum | doc/source/scripting/mie_contrib.py | Python | gpl-3.0 | 567 | 0.003527 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from mstm_studio.contributions import MieLognormSpheres
from mstm_studio.alloy_AuAg import AlloyAuAg
import numpy as np
mie = MieLognormSpheres(name='mie', | wavelengths=np.l | inspace(300,800,51))
mie.set_material(AlloyAuAg(x_Au=1), 1.5) # golden sphere in glass
values = [1, 1.5, 0.5] # scale, mu, sigma
fig, _ = mie.plot(values)
fig.savefig('mie_contrib.png', bbox_inches='tight')
mie.MAX_DIAMETER_TO_PLOT = 20 # 100 nm is by default
fig, _ = mie.plot_distrib(values)
fig.savefig('mie_dis... |
tysonholub/twilio-python | tests/integration/preview/acc_security/service/test_verification.py | Python | mit | 1,803 | 0.002773 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class VerificationTestCase(Inte... | nel="channel")
values = {'To': "to", 'Channel': "channel", }
self.holodeck.assert_has_request(Request(
'post',
| 'https://preview.twilio.com/Verification/Services/VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Verifications',
data=values,
))
def test_create_verification_response(self):
self.holodeck.mock(Response(
201,
'''
{
"sid": "VEaaaaaaaaaaaaaaaaaa... |
neviim/logporsocket | nvmtools.py | Python | mit | 3,224 | 0.036036 | #!/usr/bin/python
# -*-coding: UTF-8-*-
import random, platform, subprocess
import sys, os, time, getopt
dev=[{ "Nome": "Neviim",
"Status": {"list":[ {"Data": "18/02/2013"},
{"Update": "20/02/2014"},
{"Versao": "0.1"}]}}]
class MacTools:
"""documentação para classe MacTools"""
def __init__(... | ef checkOSxMac(self,device,mac):
"""Returna true | se o corrente mac address correspponde ao mac address enviado"""
output = subprocess.Popen(["ifconfig", "%s" % device], stdout=subprocess.PIPE).communicate()[0]
index = output.find('ether') + len('ether ')
localAddr = output[index:index+17].lower()
return mac == localAddr
def checkLinuxMac(self,device,mac):... |
zkan/microservices-with-swarm-101 | services/front_gateway/front_gateway/wsgi.py | Python | mit | 392 | 0 | """
WSGI config for bangkok project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this | file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bangkok.settings")
application = | get_wsgi_application()
|
jonfoster/pyxb-upstream-mirror | tests/trac/test-trac-0111.py | Python | apache-2.0 | 1,835 | 0.010899 | # -*- coding: utf-8 -*-
import logging
if __name__ == '__main__':
logging.basicConfig()
_log = logging.getLogger(__name__)
import pyxb.binding.generate
import pyxb.utils.domutils
from xml.dom import Node
import os.path
xsd='''<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSch... | (self):
vals = set()
for ee in cards.iteritems():
self.assertTrue(isinstance(ee, cards._CF_enumeration._CollectionFacet_itemType))
| vals.add(ee.value())
self.assertEqual(self.Expected, vals)
def testValues (self):
vals = set()
for e in cards.itervalues():
vals.add(e)
self.assertEqual(self.Expected, vals)
def testIterValues (self):
vals = set()
for e in cards.itervalue... |
porduna/appcomposer | run_celery_single_queue.py | Python | bsd-2-clause | 153 | 0 | #!/usr/bin/python
from appcomposer.translator.tasks | import cel
import sys
cel.worker_main(sys.argv + ['--concurrency=1', '--queues=single-sync-task | s'])
|
qmlc/qmlc | qmc/qmc-rccpro.py | Python | lgpl-2.1 | 5,020 | 0.003386 | #!/usr/bin/python
import sys
if len(sys.argv) < 7:
print "Usage: " + sys.argv[0] + "pri-file in-dir out-dir qrc-var deps-var qmc-flags qrc-files..."
print " pri-file : File to create. To be included in calling project file."
print " in-dir : Source directory. Use $$PWD."
print " out-dir : Output... | file list."
print " Pass \\\" \\\" if none."
print " qmc-flags: Command-line options for qmc. Pass \\\" \\\" if none."
print " qrc-files: Names of the qrc files to process."
print "Example: __qmc-res.pri $$PWD $$OUT_PWD RESOURCES \\\" \\\" \"-g \" res.qrc res2.qrc"
print "Example: __q... | rt xml.etree.ElementTree as et
outName = sys.argv[1].strip()
inDir = sys.argv[2].strip()
outDir = sys.argv[3].strip()
varName = sys.argv[4].strip()
depName = sys.argv[5].strip()
qmcFlags = sys.argv[6].strip()
qrcFiles = sys.argv[7:]
toInFromOut = os.path.relpath(inDir, outDir)
if toInFromOut == ".":
toInFromOut =... |
uhliarik/rebase-helper | test/test_base_output.py | Python | gpl-2.0 | 3,601 | 0.001944 | # -*- coding: utf-8 -*-
#
# This tool helps you to rebase package to the latest version
# Copyright (C) 2013-2014 Red Hat, Inc.
#
# 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
# he Free Software Foundation; either version 2 ... | 02110-1301 USA.
#
# Authors: Petr Hracek <phracek@redhat.com>
# Tomas Hozza <thozza@redhat.com>
import six
from rebasehelper.base_output import OutputLogger
class TestBaseOutput(object):
"""
Class is used for testing OutputTool
"""
old_rpm_data = {'rpm': ['rpm-0.1.0.x86_64.rpm', ' rpm-devel... | file2.log']}
new_rpm_data = {'rpm': ['rpm-0.2.0.x86_64.rpm', ' rpm-devel-0.2.0.x86_64.rpm'],
'srpm': 'rpm-0.2.0.src.rpm',
'logs': ['logfile3.log', 'logfile4.log']}
patches_data = {'deleted': ['del_patch1.patch', 'del_patch2.patch'],
'modified': ['mod_patch1.pa... |
mozilla/firefox-flicks | vendor-local/lib/python/celery/backends/database/dfd042c7.py | Python | bsd-3-clause | 1,554 | 0 | # -*- coding: utf-8 -*-
"""
celery.backends.database.dfd042c7
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SQLAlchemy 0.5.8 version of :mod:`~celery.backends.database.a805d4bd`,
see the docstring of that module for an explanation of why we need
this workaround.
"""
from __future__ import absolute_import
fro... |
return self.pickler.loads(self.pickler.dumps(value, self.protocol))
else:
return value
def compare_values(self, x, y):
if self.comparator:
return self.comparator(x, y)
elif self.mutable and not hasattr(x, '__eq__') and x is not None:
util.war... | ment __eq__() for reliable comparison.')
a = self.pickler.dumps(x, self.protocol)
b = self.pickler.dumps(y, self.protocol)
return a == b
else:
return x == y
def is_mutable(self):
return self.mutable
|
egor-tensin/vk-scripts | vk/platform.py | Python | mit | 1,582 | 0 | # Cop | yright (c) 2016 Egor Tensin <Egor.Tens | in@gmail.com>
# This file is part of the "VK scripts" project.
# For details, see https://github.com/egor-tensin/vk-scripts.
# Distributed under the MIT License.
from enum import Enum
import re
class Platform(Enum):
MOBILE = 1
IPHONE = 2
IPAD = 3
ANDROID = 4
WINDOWS_PHONE = 5
WINDOWS8 = 6
... |
flaviocpontes/ffmpymedia | setup.py | Python | mit | 1,809 | 0 | from setuptools import setup
from codecs import open
from os import path
from ffmpymedia import __version__
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='ff... | 'Development Status :: 4 - Beta',
# Indicate who your project is intended for
'Intended Audience :: Developers',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In par... | , Python 3 or both.
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
author='Flávio Cardoso Pontes',
author_email='flaviopontes@acerp.org.br',
keywords=['media', 'ffmpeg']
)
|
SINGROUP/pycp2k | pycp2k/classes/_xalpha1.py | Python | lgpl-3.0 | 368 | 0.002717 | from pycp2k.inputsection import InputSection
class _xalpha1(InputSection):
def __init__(self) | :
InputSection.__init__(self)
self.Section_parameters = None
self.Xa = None
self.Scale_x = None
self._name = "XALPHA"
self._keywords = {'Xa': 'XA', 'Scale_x': 'SCALE_X'}
| self._attributes = ['Section_parameters']
|
ceelian/Flatty | src/flatty/__init__.py | Python | bsd-3-clause | 423 | 0.002364 | """flatty - marshaller/unmarshaller for light-schema python obje | cts"""
VERSION = (0, 1, 2)
__version__ = ".".join(map(str, VERSION))
__author__ = "Christian Haintz"
__contact__ = "christian.haintz@orangelabs.at"
__homepage__ = "http://packages.python.org/flatty"
__docformat__ = "restructuredtext"
from flatty import *
try:
import mongo
except ImportError:
pass
try:
imp... | t couch
except ImportError:
pass
|
chandler14362/panda3d | contrib/src/sceneeditor/seBlendAnimPanel.py | Python | bsd-3-clause | 28,869 | 0.014445 | #################################################################
# collisionWindow.py
# Written by Yi-Hong Lin, yihhongl@andrew.cmu.edu, 2004
#################################################################
# Import Tkinter, Pmw, and the floater code from this directory tree.
from direct.tkwidgets.AppShell import *
f... | [], None),
('blendAnimList', self.blendList, None),
)
self.defineoptions(kw, optiondefs)
self.id = 'Blend AnimPanel '+ aNode.getName()
self.nodeName = aNode.ge | tName()
# Initialize the superclass
AppShell.__init__(self)
# Execute option callbacks
self.initialiseoptions(BlendAnimPanel)
self.currTime = 0.0
self.animNameA = None
self.animNameB = None
self.parent.resizable(False,False) ## Disable the ability to re... |
meng89/epubuilder | epubaker/metas/epub3_meta.py | Python | mit | 570 | 0 | # coding=utf-8
from .attrs import Attrs, AltScript, Dir, FileAs, Id, Scheme, Lang
from .dcmes import Base
class Property(Attrs):
@property
def property(self):
"""xml attribute: `property`"""
return self._attrs.setdefault('property')
@property.setter
def prop | erty(s | elf, value):
self._attrs['property'] = value
class Meta3(Base, AltScript, Dir, FileAs, Id, Property, Scheme, Lang):
"""meta for Epub3.metadata"""
def __init__(self, property_, text):
Base.__init__(self, text)
self.property = property_
|
sserrot/champion_relationships | venv/Lib/site-packages/testpath/asserts.py | Python | mit | 6,826 | 0.003516 | import os
import stat
try:
from pathlib import Path
except ImportError:
try:
# Python 2 backport
from pathlib2 import Path
except ImportError:
class Path(object):
"""Dummy for isinstance checks"""
pass
__all__ = ['assert_path_exists', 'assert_not_path_exist... | ollow_symlinks, msg)
if stat.S_ISDIR(st.st_mode):
if msg is None:
msg = "Path is a directory: %r" % path
raise AssertionError(msg)
_link_target_msg = """Symlink target of:
{path}
Expected:
{expected}
Actual:
{actual}
"""
def assert_islink(path, to=None, msg=None):
"""Assert | that path exists and is a symlink.
If to is specified, also check that it is the target of the symlink.
"""
path = _strpath(path)
st = _stat_for_assert(path, False, msg)
if not stat.S_ISLNK(st.st_mode):
if msg is None:
msg = "Path exists, but is not a symlink: %r" % path
... |
AdeshAtole/coala | coalib/output/ConfWriter.py | Python | agpl-3.0 | 4,015 | 0 | from itertools import chain
from pyprint.ClosableObject import ClosableObject
from coal | ib.parsing.StringProcessing import escape
from coalib.settings.Section import Section
class ConfWriter(ClosableObject):
def __init__(self,
file_name,
key_value_delimiters=('=',),
comment_seperators=('#',),
key_delimiters=(',', ' '),
... | name_surroundings = section_name_surroundings or {"[": "]"}
ClosableObject.__init__(self)
self.__file_name = file_name
self.__file = open(self.__file_name, "w")
self.__key_value_delimiters = key_value_delimiters
self.__comment_seperators = comment_seperators
self.__key_de... |
ODM2/ODM2WebSDL | src/accounts/models.py | Python | bsd-3-clause | 910 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.db import models
from django.contrib.auth.models import AbstractUser
from dataloader.models import Affiliation
class User(AbstractUser):
affiliation_id = models.IntegerField(null=True) # Temporarily nullab... | zation_name = models.CharField(max_le | ngth=255, blank=True, null=True)
@property
def affiliation(self):
return Affiliation.objects.get(pk=self.affiliation_id)
def owns_site(self, registration):
return registration.django_user == self
def can_administer_site(self, registration):
return self.is_staff or registration... |
khchine5/book | lino_book/projects/properties/models.py | Python | bsd-2-clause | 4,443 | 0.008103 | """
Module `lino_xl.lib.properties`
-------------------------------
Imagine that we are doing a study about alimentary habits. We observe a
defined series of properties on the people who participate in our study.
Here are the properties that we are going to observe::
>>> weight = properties.INT.create_property(na... | h.choices_list()
[u'Cookies', | u'Fish', u'Meat', u'Vegetables']
>>> qs = properties.Property.objects.all()
>>> ["%s (%s)" % (p.name,','.join(map(str,p.choices_list()))) for p in qs]
[u'weight ()', u'married (True,False)', u'favdish (Cookies,Fish,Meat,Vegetables)']
PropValuesByOwner is a report that cannot be rendered into a normal grid beca... |
robert-impey/tree-sorter | randomtrees.py | Python | mit | 2,051 | 0.000488 | #!/usr/bin/env python3
import random
"""
Generates random trees
"""
import argparse
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
def generate_random_item(length=8, chars=alphabet):
item = ""
for i in range(length):
index = random.randint(0, len(chars) - 1)
... | type=int,
default=10)
parser.add_argument('--Length',
help='The length of each item.',
type=int,
default=8)
parser.add_argument('--Alphabet',
help='The alphabet of allowed charact... | se_args()
random_tree_lines = generate_random_tree_lines(
args.Depth,
args.Items,
args.Length,
args.Alphabet)
for line in random_tree_lines:
print(line)
|
elkingtowa/alphacoin | Bitcoin/ngcccbase-master/ngcccbase/p2ptrade/comm.py | Python | mit | 3,132 | 0.003831 | import urllib2
import json
import time
import threading
import Queue
from utils import make_random_id, LOGINFO, LOGDEBUG, LOGERROR
class CommBase(object):
def __init__(self):
self.agents = []
def add_agent(self, agent):
self.agents.append(agent)
class HTTPComm(CommBase):
def __init__(s... | ueue
receive_queue = self.threaded_comm.receive_queue
while not self._stop.is_set():
while not send_queue.empty():
self.upstream_comm.post_message(send_queue.get())
self.upstream_c | omm.poll_and_dispatch()
time.sleep(1)
def stop(self):
self._stop.set()
|
svamp/rp_management | roleplaying/wsgi.py | Python | gpl-3.0 | 399 | 0 | """
WSGI config for roleplaying project.
It exposes the WSGI callable as a module-level variable named ``applicat | ion``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os |
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "roleplaying.settings")
application = get_wsgi_application()
|
aaronbassett/djangocon-pusher | talk/todo/models.py | Python | mit | 891 | 0 | # -*- coding: utf-8 -*-
# Django
from django.db import models
from .mixins import SelfPublishModel
from .serializers import TodoListSerializer, TodoItemSerializer
class TodoList(SelfPublishModel, models.Model):
serializer_class = TodoListSerializer
channel_name = u"todo-list"
name = models.CharField(ma... | description = models.TextField()
def __unicode__(self):
return u"{name}".format(
name=self.name,
)
class TodoItem(SelfPublishModel, models.Model):
serializer_class = TodoItemSerializer
channel_name = u"todo-item"
todo_list = models.ForeignKey(TodoList)
done = models. | BooleanField(default=False)
text = models.CharField(max_length=100)
def __unicode__(self):
return u"{text} ({status})".format(
text=self.text,
status=(u"✓" if self.done else u"×")
)
|
ddsc/ddsc-core | ddsc_core/migrations/0078_auto__chg_field_alarm_last_checked.py | Python | mit | 28,517 | 0.007925 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Alarm.last_checked'
db.alter_column(u'ddsc_core_alarm', 'last_checked', self.gf('django.d... | 'first_born': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'logical_check': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'obj | ect_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
'value_bool': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}),
'value_double': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'value_int': ('django.d... |
Richard-West/RootTheBox | handlers/StaticFileHandler.py | Python | apache-2.0 | 2,151 | 0 | # -*- coding: utf-8 -*-
'''
Created on Mar 13, 2012
@author: moloch
Copyright 2012 Root the Box
Licensed under the Apache License, Version 2.0 (the "Lice | nse");
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 License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES ... |
iulian787/spack | var/spack/repos/builtin/packages/launchmon/package.py | Python | lgpl-2.1 | 1,541 | 0.001947 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Launchmon(AutotoolsPackage):
"""Software infrastructure that enables HPC run-time tools to... | pkgconfig', type='build')
depends_on('libgcrypt')
depends_on('libgpg-error')
depends_on("elf", type='link')
depends_on("boost")
depends_on("spectrum-mpi", when='arch=ppc64le')
patch('launchmon-char-conv.patch', when='@1.0.2')
patch('for_aarch64.patch', when=' | @:1.0.2 target=aarch64:')
def setup_build_environment(self, env):
if self.spec.satisfies('@master'):
# automake for launchmon requires the AM_PATH_LIBGCRYPT macro
# which is defined in libgcrypt.m4
env.prepend_path('ACLOCAL_PATH',
self.spec['... |
gonrin/gatco | gatco/exceptions.py | Python | mit | 78 | 0.025641 | from sanic.exceptions import *
class GatcoException(SanicException | ):
pass | |
zyga/debian.plainbox | plainbox/impl/secure/rfc822.py | Python | gpl-3.0 | 16,235 | 0 | # This file is part of Checkbox.
#
# Copyright 2012, 2013 Canonical Ltd.
# Written by:
# Sylvain Pineau <sylvain.pineau@canonical.com>
# Zygmunt Krynicki <zygmunt.krynicki@canonical.com>
#
# Checkbox is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as pu... | lass for tracking RFC822 records
This is a simple container for the dictionary of data.
Each instance also holds the origin of the data
"""
def __ | init__(self, data, origin=None):
"""
Initialize a new record.
:param data:
A dictionary with record data
:param origin:
A :class:`Origin` instance that describes where the data came from
"""
if origin is None:
origin = Origin.get_calle... |
rookuu/AdventOfCode-2015 | Day 9/Puzzle 1 and 2.py | Python | mit | 998 | 0.001002 | #!/usr/bin/env python
"""
Solution to Day X - Puzzle X of the Advent Of Code 2015 series of challenges.
--- Day X: Day X Title ---
Description of Puzzle
-----------------------------------------
Author: Luke "rookuu" Roberts
"""
from collections import defaultdict
fr | om itertools | import permutations
inputFile = open('input.txt')
dataFromFile = inputFile.read().splitlines()
places = set()
graph = defaultdict(dict)
distances = []
for line in dataFromFile:
values = line.split(" ")
places.add(values[0])
places.add(values[2])
graph[values[0]][values[2]] = int(values[4])
gra... |
lukas-krecan/tensorflow | tensorflow/python/__init__.py | Python | apache-2.0 | 3,483 | 0.001723 | # Copyright 2015 Google Inc. 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 applicable law or a... | =====
# pylint: disable=wildcard-import,unused-import,g-bad-import-order,line-too-long
"""Import core names of TensorFlow.
Programs that want to build Brain Ops and Graphs without having to import the
constructors and utilities individually can import this file:
from __future__ import absolute_import
from __future__... | ort print_function
import tensorflow.python.platform
import tensorflow as tf
"""
import inspect
import traceback
# pylint: disable=g-import-not-at-top
try:
import tensorflow.python.platform
from tensorflow.core.framework.graph_pb2 import *
except ImportError:
msg = """%s\n\nError importing tensorflow. Unless... |
yekeqiang/mypython | time_1.py | Python | gpl-2.0 | 438 | 0.004566 | #!/usr/bin/env python
import time
class Timer(object):
def __init__(self, verb | ose=False):
self.verbose = verbose
def __enter__(self):
| self.start = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.secs = self.end - self.start
self.msecs = self.secs * 1000 # millisecs
if self.verbose:
print 'elapsed time: %f ms' % self.msecs
|
iulian787/spack | var/spack/repos/builtin/packages/py-pytz/package.py | Python | lgpl-2.1 | 1,493 | 0.007368 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyPytz(PythonPackage):
"""World timezone definitions, modern and historical."""
homep... | ']
version('2020.1', sha256='c35965d010ce31b23eeb663ed3cc8c906275d6be1a34393a1d73a41febf4a048')
version('2019.3', sha256='b02c06db6cf09c12dd25137e563b31700d3b80fcc4ad23abb7a315f2789819be')
version('2019.1', sha256='d747dd3d23d77ef44c6a3526e274af6efeb0a6f1afd5a69ba4d5be4098c8e141')
version('2018.4', sha... | 4c80f2dcd22b')
version('2016.6.1', sha256='6f57732f0f8849817e9853eb9d50d85d1ebb1404f702dbc44ee627c642a486ca')
version('2014.10', sha256='a94138b638907491f473c875e8c95203a6a02efef52b6562be302e435016f4f3')
version('2014.9', sha256='c5bcbd11cf9847096ae1eb4e83dde75d10ac62efe6e73c4600f3f980968cdbd2')
vers... |
avinassh/random-python-scripts | Modern-Combat-4/MC4.py | Python | mit | 242 | 0.008264 | import requests
from time import sleep
URL = 'http://ano | nymouse.org/cgi-bin/anon-www.cgi/http://www.ign.com/private/prime/promo/modern-combat-4/code'
for i in range(1, 1000):
r = requests.get(URL)
print r.json()['code']
sleep(2 | ) |
iamaziz/PyDataset | pydataset/datasets_handler.py | Python | mit | 1,747 | 0 | # datasets_handler.py
# dataset handling file
import pandas as pd
from .utils import html2text
from .locate_datasets import __items_dict, __docs_dict, __get_data_folder_path
items = __items_dict()
docs = __docs_dict()
# make dataframe layout (of __datasets_desc()) terminal-friendly
pd.set_option('display.max_rows', ... | ormat
txt = __fi | lter_doc(doc) # edit R related txt
print(txt)
def __datasets_desc():
"""return a df of the available datasets with description"""
datasets = __get_data_folder_path() + 'datasets.csv'
df = pd.read_csv(datasets)
df = df[['Item', 'Title']]
df.columns = ['dataset_id', 'title']
# print('a list... |
gppeixoto/pcc | kmp/paguso/kmp.py | Python | mit | 2,708 | 0.016248 | import sys
verbose = 1
def brute_force(txt, pat):
n = len(txt)
m = len(pat)
# assumption: n > m
i = 0 # store window current position
occ = []
while i < n-m+1:
if verbose:
print " %si=%d" % (i*" ", i)
| print "T: %s" % txt
j = 0 # store how many matches until current
while j < m and txt[i+j]==pat[j]:
j += 1
if verbose:
print " %s%s%s" % (i*" ", (j)*"=", "" if (j==m) else "!")
print "P: %s%s" % (i*" ", pat)
print " %sj=%d" % (i*" ", i)
... | c
def init_next(pat):
"""
returns table with strict borders for each prefix length
from prefix[:0]="" until prefix[:]=pat
"""
m = len(pat)
B = (m+1)*[-1]
if m==1 or (m > 1 and pat[0]!=pat[1]):
B[1] = 0
i = 1
j = 0
while i < m:
while i+j < m and pat[j]==pat[i+j]:
... |
StellarCN/py-stellar-base | examples/payment_muxed_account.py | Python | apache-2.0 | 1,168 | 0.001712 | import pprint
from stellar_sdk import (
Asset,
Keypair,
MuxedAccount,
Network,
Server,
TransactionBuilder,
)
horizon_url = "https://horizon-testnet.stellar.org/"
network_passphrase = Network.TESTNET_NETWORK_PASS | PHRASE
alice_secret = "SAHN2RCKC5I7NFDCIUKA3BG4H4T6WMLLGSAZVDKUHF7PQXHMYWD7UAIH"
bob_account = MuxedAccount(
account_id="GBZSQ3YZMZEWL5ZRCEQ5CCSOTXCFCMKDGFFP4IEQN2KN6LCHCLI46UMF",
account_muxed_id=1234,
)
print(f"account_id_muxed: {bob_account.account_muxed}")
# You can also use addresses starting with M.
# bo... | secret(alice_secret)
server = Server(horizon_url=horizon_url)
alice_account = server.load_account(alice_keypair.public_key)
transaction = (
TransactionBuilder(
source_account=alice_account,
network_passphrase=network_passphrase,
base_fee=100,
)
.append_payment_op(destination=bob_acc... |
daStrauss/subsurface | src/expts/paramSplitFieldBoth.py | Python | apache-2.0 | 1,344 | 0.013403 | '''
Created on Oct 3, 2012
Copyright © 2013
The Board of Trustees of The Leland Stanford Junior University.
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.apa... | E-2.0
Unless required by applicable law or agreed to in writing, softwa | re
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.
@author: dstrauss
'''
import numpy as np
D = {'solverType':'splitField', 'f... |
Evert-Arends/AuroraPlusClient | run.py | Python | mit | 5,859 | 0.003072 | #!/usr/bin/env python2
# Imports
import json
import datetime
from bin import monitor, register
from ClientSettings import ClientSettings
from ClientSettings import constants
import dataCollector
import settings
import time
import sys
Monitor = monitor.Monitor()
message1 = "Client script running on version: {0}".form... | verDetails"]["Disk_Load"]["Write"] = MonitorData[6][1]
if MonitorData[8]:
if Monitor.getLastLogID() < float(MonitorData[8]):
json_data["Server"]["Messages"]["Log"] = MonitorData[7]
json_data["Server"]["Messages"]["AlertID"] = MonitorData[8]
... | json_data["Server"]["Messages"]["Alert"] = True
else:
json_data["Server"]["Messages"]["Alert"] = False
f.seek(0)
f.write(json.dumps(json_data))
f.truncate()
@staticmethod
def upload_data():
# print 'Sending json.'
... |
EricssonResearch/calvin-base | calvin/actorstore/docobject.py | Python | apache-2.0 | 12,850 | 0.003735 | import json
import inspect
import pystache
from calvin.utilities.calvinlogger import get_logger
_log = get_logger(__name__)
class DocObject(object):
"""docstring for DocObject"""
use_links = False
COMPACT_FMT = "{{{qualified_name}}} : {{{short_desc}}}"
DETAILED_FMT_MD = "{{{e_qualified_name}}} : {{{... | ame, short_desc):
docs = short_desc or "Unknown error"
super(ErrorDoc, self).__init__(namespace, name, docs)
self.label = "Error"
def search(self, search_list):
_log.debug("Actor module {}/ is missing file __init__.py".format(self.ns))
return self
class M | oduleDoc(DocObject):
"""docstring for ModuleDoc"""
COMPACT_FMT = """
{{{qualified_name}}}
{{{short_desc}}}
{{#modules_compact}}
Modules: {{{modules_compact}}}
{{/modules_compact}}
{{#actors_compact}}
Actors: {{{actors_compact}}}
{{/actors_compact}}
"""
DETAILED_FMT_PLA... |
ROGUE-JCTD/vida | vida/firestation/api.py | Python | mit | 4,167 | 0.00336 | import json
import logging
from .forms import StaffingForm
from .models import FireStation, Staffing, FireDepartment
from django.core.serializers.json import DjangoJSONEncoder
from tastypie import fields
from tastypie.authentication import SessionAuthentication, ApiKeyAuthentication, MultiAuthentication
from tastypie.a... | _simple(data, options)
return json.dumps(data, | cls=DjangoJSONEncoder,
sort_keys=True, ensure_ascii=False, indent=self.json_indent)
class FireDepartmentResource(ModelResource):
"""
The Fire Department API.
"""
class Meta:
resource_name = 'fire-departments'
queryset = FireDepartment.objects.all()
authorizati... |
ScreamingUdder/mantid | Testing/SystemTests/tests/analysis/SANSDiagnosticPageTest.py | Python | gpl-3.0 | 6,474 | 0.001545 | # pylint: disable=too-many-public-methods, invalid-name, too-many-arguments
from __future__ import (absolute_import, division, print_function)
import unittest
import os
import stresstesting
import mantid
from sans.state.data import get_data_builder
from sans.common.enums import (DetectorType, SANSFacility, IntegralE... | uilder = get_data_builder(SANSFacility.ISIS)
data_builder.set_sample_scatter("SANS2D00034484")
data_builder.set_calibration("TUBE_SANS2D_BOTH_31681_25Sept15.nxs")
data_state = data_builder.build()
# Get the rest of the state from the user file
user_file_director = StateDirectorI... | !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# COMPATIBILITY BEGIN -- Remove when appropriate
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Since we are dealing with event based data but we want to compare i... |
LennonChin/Django-Practices | MxShop/apps/trade/migrations/0004_auto_20171023_2354.py | Python | apache-2.0 | 1,497 | 0.002088 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-10-23 23:54
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):
dependencies = [
migrations.swapp... | 20171022_1507'),
]
operations = [
migrations.AlterField(
model_name='ordergoods',
name='order',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='goods', to='trade.OrderInfo', verbose_name= | '订单信息'),
),
migrations.AlterField(
model_name='orderinfo',
name='order_sn',
field=models.CharField(blank=True, max_length=30, null=True, unique=True, verbose_name='订单号'),
),
migrations.AlterField(
model_name='orderinfo',
... |
DaKnOb/mwhois | netaddr/strategy/eui48.py | Python | mit | 8,693 | 0.003681 | #-----------------------------------------------------------------------------
# Copyright (c) 2008-2015, David P. D. Moss. All rights reserved.
#
# Released under the BSD license. See the LICENSE file for details.
#-----------------------------------------------------------------------------
"""
IEEE 48-bit EUI (M... | word_size = 48
num_words = width // word_siz | e
word_sep = ''
word_fmt = '%.12X'
word_base = 16
class mac_pgsql(mac_eui48):
"""A PostgreSQL style (2 x 24-bit words) MAC address dialect class."""
word_size = 24
num_words = width // word_size
word_sep = ':'
word_fmt = '%.6x'
word_base = 16
#: The default dialect to be used w... |
scottpurdy/nupic | src/nupic/algorithms/backtracking_tm.py | Python | agpl-3.0 | 143,241 | 0.007966 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | t must be active to
activate a segment.
:param doPooling: (bool) If True, pooling is enabled. False is the default.
:param segUpdateValidDuration: TODO: document
:param burnIn: (int) Used for evaluating the prediction score. Default is 2.
:param collectStats: (bool) If True, collect training / i... | am seed: (int) Random number generator seed. The seed affects the random
aspects of initialization like the initial permanence values. A fixed
value ensures a reproducible result.
:param verbosity: (int) Controls the verbosity of the TM diagnostic output:
- verbosity == 0: silent
... |
arraystream/simpleplotly | tests/test_figure.py | Python | mit | 1,366 | 0.001464 | import unittest
import plotly.graph_objs as go
import weplot as wp
class FigureHolderTest(unittest.TestCase):
def test_can_update_layout(self):
fh = wp.FigureHolder(go.Figure())
layout = fh.figure.layout
self.assertIsNone(layout.barmode)
self.assertIsNone(layout.title)
... | self.assertEqual(layout.title, 'test plot')
fh.drop_layout_key('barmode')
self.assertIsNone(layout.barmode)
self.assertEqual(layout.title, 'test plot')
def test_update_layout_with_invalid_property_raises(self):
fh = wp.FigureHolder(go.Figure())
layout = fh.figure.layout
... | ses(ValueError, fh.update_layout, invalid_property1='any value')
fh.update_layout(barmode='group', title='test plot')
self.assertEqual(layout.barmode, 'group')
self.assertEqual(layout.title, 'test plot')
self.assertRaises(ValueError, fh.drop_layout_key, 'invalid_property2')
class Fig... |
mozts2005/OuterSpace | client-pygame/lib/pygameui/Fonts.py | Python | gpl-2.0 | 2,420 | 0.022727 | #
# Copyright 2001 - 2006 Ludek Smid [http://www.ospace.net/]
#
# This file is part of Pygame.UI.
#
# Pygame.UI is free software; you can redistribute | it and/or modify
# it under the terms of the Lesser GNU General Public License as published by
# | the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Pygame.UI 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
# Lesser ... |
miraculixx/pyrules | pyrules/rules.py | Python | mit | 6,453 | 0.003409 | import json
import yaml
from .conditions import Lo | gicEvaluator
from .dictobj import DictObject
from .language import Translator
class Rule(object):
"""
Base rule
"""
name = None
def should_trigger(self, context):
return True
def perform(self, context):
raise NotImplementedError
def record(self, context, resu | lt):
context._executed.append((self.ruleid, result))
@property
def ruleid(self):
return self.name or self.__class__.__name__.rsplit('.', 1)[-1]
class ConditionalRule(Rule):
"""
ConditionalRule defines receives two functions as parameters: condition and
action.
@param cond... |
antoinecarme/sklearn2sql_heroku | tests/classification/BinaryClass_100/ws_BinaryClass_100_SVC_sigmoid_sqlite_code_gen.py | Python | bsd-3-clause | 142 | 0.014085 | from skl | earn2sql_heroku.tests.classification import generic as class_gen
class_gen.test_model("SVC_sigmoid" , "BinaryClass_100" , " | sqlite")
|
doozr/euler.py | p0020_factorial_digit_sum_test.py | Python | gpl-3.0 | 438 | 0 | """
n! means n x (n - 1) x ... x 3 x 2 x 1
For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800,
and the sum of the digits in t | he number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
Answer:
648
"""
from math import factorial
def factorial_digit_sum(x):
return sum(int(d) for d in str(factorial(x)))
def test_0020_fact | orial_digit_sum():
assert factorial_digit_sum(100) == 648
|
stackmachine/bearweb | core/templatetags/core_extras.py | Python | mit | 1,258 | 0 | import hashlib
from django import template
from django.core import urlresolvers
register = template.Library()
@register.simple_tag(takes_context=True)
def gravatar(context, user):
email_hash = hashlib.md5(user.email.lower()).hexdigest()
return 'https://www.gravatar.com/avatar/{}?s=30&d=retro'.format(email_h... | resolved.url_name == url_name \
and resolved.namespace == namespace
if matches and kwargs:
for key in kwargs:
kwarg = kwargs.get(key)
resolved_kwarg = resolved.kwargs.g | et(key)
if not resolved_kwarg or kwarg != resolved_kwarg:
return False
return matches
|
bnsantos/python-junk-code | tests/graphs/complementGraphTest.py | Python | gpl-2.0 | 2,970 | 0.001684 | __author__ = 'bruno'
import unittest
import algorithms.graphs.complementGraph as ComplementGraph
class TestComplementGraph(unittest.TestCase):
def setUp(self):
pass
def test_complement_graph_1(self):
graph = {'a': {'b': 1, 'c': 1},
'b': {'a': 1, 'c': 1, 'd': 1},
... | ': {'a': 1, 'e': 1, 'f': 1},
'c': {'e': 1, 'd': 1, 'f': 1},
'd': {'c': 1},
'e': {'a': 1, 'c': 1, 'b': 1},
'f': {'a': 1, 'c': 1, 'b': 1}}
self.assertEqual(complement, ComplementGraph.make_complement_graph(graph))
def tes... | _complement_graph_4(self):
graph = {'a': {'b': 1, 'f': 1},
'b': {'a': 1, 'c': 1},
'c': {'b': 1, 'd': 1},
'd': {'c': 1, 'e': 1},
'e': {'d': 1, 'f': 1},
'f': {'a': 1, 'e': 1}}
complement = {'a': {'c': 1, 'e': 1, 'd': 1},... |
IGITUGraz/scoop | examples/dependency/sortingnetwork.py | Python | lgpl-3.0 | 4,724 | 0.004234 | # This file is part of DEAP.
#
# DEAP 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 Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# DEAP is distributed ... | ules that is used to sort a
sequence of numbers. Each comparator connects two wires and sort the
values by outputting the smaller value to one wire, and a larger
value to the other.
"""
def __init__(self, dimension, connectors = []):
self.dimension = dimension
for wire1, wire2 in con... | ector(self, wire1, wire2):
"""Add a connector between wire1 and wire2 in the network."""
if wire1 == wire2:
return
if wire1 > wire2:
wire1, wire2 = wire2, wire1
try:
last_level = self[-1]
except IndexError:
# Empty... |
ViktorZharina/BestBankExchange | src/config/settings.py | Python | gpl-2.0 | 427 | 0.017544 | #!/usr/bin/p | ython
# -*- coding: utf-8 -*-
# @author Viktor Zharina <viktorz1986@gmail.com>
# CC-BY-SA License
settings = {
'currencys' : ['usd', 'eur'],
'operations' : ['buy', 'sell'],
}
lang = {
'ru': {
'usd_buy' : u'USD покупка',
'usd_sell' : u'USD продажа',
'eur_buy' ... | '
}
} |
liamw9534/mopidy | mopidy/http/handlers.py | Python | apache-2.0 | 5,682 | 0 | from __future__ import unicode_literals
import logging
import os
import socket
import tornado.escape
import tornado.web
import tornado.websocket
import mopidy
from mopidy import core, models
from mopidy.utils import jsonrpc
logger = logging.getLogger(__name__)
def make_mopidy_app_factory(apps, statics):
def ... | clients = set()
@classmethod
def broadcast(cls, msg):
for client in cls.clients:
client.write_message(msg)
def | initialize(self, core):
self.jsonrpc = make_jsonrpc_wrapper(core)
def open(self):
if hasattr(self, 'set_nodelay'):
# New in Tornado 3.1
self.set_nodelay(True)
else:
self.stream.socket.setsockopt(
socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
... |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247972723/samba/dcerpc/samr/RidWithAttribute.py | Python | gpl-2.0 | 1,272 | 0.007075 | # encoding: utf-8
# module samba.dcerpc.samr
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/samr.so
# by generator 1.135
""" samr DCE/RPC """
# imports
import dcerpc as __dcerpc
import talloc as __talloc
class RidWithAttribute(__talloc.Object):
# no doc
def __init__(self, *args, **kwargs): # real signa... | a new object with type S, a subtype of T """
pass
attributes = property(lambda self: ob | ject(), lambda self, v: None, lambda self: None) # default
rid = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
|
souravbadami/oppia | core/domain/topic_domain.py | Python | apache-2.0 | 38,486 | 0.000208 | # coding: utf-8
#
# Copyright 2018 The Oppia 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 requi... | erty_name', 'new_value', 'old_value'],
'optional_attribute_names': [],
'allowed_values': {'property_name': TOPIC_PROPERTIES}
}, {
'name': CMD_MIGRATE_SUBT | OPIC_SCHEMA_TO_LATEST_VERSION,
'required_attribute_names': ['from_version', 'to_version'],
'optional_attribute_names': []
}]
class TopicRightsChange(change_domain.BaseChange):
"""Domain object for changes made to a topic rights object.
The allowed commands, together with the attributes:
... |
sourcelair/castor | castor/docker_servers/models.py | Python | mit | 1,063 | 0 | from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
import docker
@python_2_unicode_compatible
class DockerServer(models.Model):
name = models.CharField(max_length=255, unique=True)
version = models.CharField(max_length=255, defau... | ls_verify:
env['DOCKER_TLS_VERIFY'] = self.docker_tls_verify
if self.docker_cert_path:
env['DOCKER_CERT_PATH'] = self.docker_cert_path
return env
def get_client(self):
client = docker.from_env(
version=self.version,
environment=self.get_ | env()
)
return client
def __str__(self):
return 'Docker Server: %s' % self.name
|
leejz/meta-omics-scripts | query_ncbi_lineage_from_mgrast_md5.py | Python | mit | 8,172 | 0.009055 | #!/usr/bin/env python
"""
--------------------------------------------------------------------------------
Created: Jackson Lee 11/4/14
This script reads in a tab delimited file of annotations and queries
asynchronously the MGRAST REST API to parse back the original ncbi tax_id entry.
This script then uses the ncb... | help="tab-delimited MGRAST organism file")
parser.add_argument("-o", "--output_filename", action="store",
dest="outputfilename",
help="tab-delimited output file") |
options = parser.parse_args()
mandatories = ["outputfilename","inputfilename"]
for m in mandatories:
if not options.__dict__[m]:
print "\nError: Missing Arguments\n"
parser.print_help()
exit(-1)
inputfilename = options.inputfilename
outputfilenam... |
sassoftware/catalog-service | catalogService/rest/models/jobs.py | Python | apache-2.0 | 120 | 0 | from rpath_job.models import job
| Job = job.J | ob
Jobs = job.Jobs
ResultResource = job.ResultResource
System = job.System
|
keras-team/reservoir_nn | reservoir_nn/models/nlp_rnn_test.py | Python | apache-2.0 | 2,126 | 0.002352 | # Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | ights,
embed_dim=embed_dim,
vocab_size=vocab_size)
x_data = np.ones((batch_size, maxlen))
model.fit(x_data, x_data)
result = model.predict(x_data)
self.assertEqual(result.shape, (batch_size, maxlen, vocab_size))
@parameterized.parameters(LAYER_NAMES)
def test_lstm_classifier_outp... | num_classes = 2
batch_size = 5
vocab_size = 50
maxlen = 20
embed_dim = 10
model = nlp_rnn.recurrent_reservoir_nlp_classifier(
layer_name=model_name,
reservoir_weight=weights,
num_classes=num_classes,
embed_dim=embed_dim,
vocab_size=vocab_size)
x_data ... |
skosukhin/spack | var/spack/repos/builtin.mock/packages/a/package.py | Python | lgpl-2.1 | 2,262 | 0.000442 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | ICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistrib | ute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNES... |
Josef-Friedrich/audiorename | _generate-readme.py | Python | mit | 1,114 | 0 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import os
def path(*path_segments):
return os.path.join(os.getcwd(), *path_segments)
def open_file(*path_segments):
file_path = path(*path_segments)
open(file_path, 'w').close()
return open(file_path, 'a')
header = open(path('READM... | ,
'\n',
'.. code-block:: text\n',
'\n',
)
for line in sphinx_header:
sphinx.write(str(line))
footer = open(path('README_footer.rst'), 'r')
for line in header:
readme.write(line)
audiorenamer = subprocess.Popen('audiorenamer --help', shell=True,
stdout=subprocess.P... | inx.write(indented_line)
audiorenamer.wait()
for line in footer:
readme.write(line)
readme.close()
sphinx.close()
|
smartstudy/midauth | midauth/models/base.py | Python | mit | 1,286 | 0.001555 | # -*- coding: utf-8 -*-
import sqlalchemy.ext.declarative
from sqlalchemy import types
from sqlal | chemy.dialects import postgr | esql
import uuid
class Base(object):
pass
#:
Base = sqlalchemy.ext.declarative.declarative_base(cls=Base)
class GUID(types.TypeDecorator):
"""Platform-independent GUID type.
Uses Postgresql's UUID type, otherwise uses
CHAR(32), storing as stringified hex values.
.. seealso:: http://docs.sqlal... |
AOSC-Dev/acbs | acbs/deps.py | Python | lgpl-2.1 | 4,219 | 0.001896 | from collections import OrderedDict, defaultdict, deque
from typing import List, Dict, Deque
from acbs.find import find_package
from acbs.parser import ACBSPackageInfo, check_buildability
# package information cache
pool: Dict[str, ACBSPackageInfo] = {}
def tarjan_search(packages: 'OrderedDict[str, ACBSPackageInfo]... | fo:
"""This function prepares the package for reordering.
The idea is to move the installable dependencies which are in the build list to the "uninstallable" list.
"""
new_installables = []
for d in package.installables:
# skip self-dependency
if d == package.name:
new_in... | (d)
continue
try:
packages_list.index(d)
package.deps.append(d)
except ValueError:
new_installables.append(d)
package.installables = new_installables
return package
def strongly_connected(search_path: str, packages_list: List[str], results: list,... |
masci/oauthlib | tests/oauth1/rfc5849/endpoints/test_authorization.py | Python | bsd-3-clause | 2,250 | 0.002667 | from __future__ import unicode_literals, absolute_import
from mock import MagicMock
from ....unittest import TestCase
from oauthlib.oauth1 import RequestValidator
from oauthlib.oauth1.rfc5849 import errors
from | oauthlib.oauth1.rfc5849.endpoints import AuthorizationEndpoint
class ResourceEndpointTest(TestCase):
def setUp(self):
self.validator = MagicMock(wraps=RequestValidator())
self.validator.verify_request_token.return_value = True
self.validator.verify_realms.return_value = True
self... | lf.uri = 'https://i.b/authorize?oauth_token=foo'
def test_get_realms_and_credentials(self):
realms, credentials = self.endpoint.get_realms_and_credentials(self.uri)
self.assertEqual(realms, ['test'])
def test_verify_token(self):
self.validator.verify_request_token.return_value = False
... |
danpalmer/open-data-quality-dashboard | tools/csvkit/csvkit/utilities/csvjson.py | Python | mit | 5,216 | 0.006135 | #!/usr/bin/env python
import json
import codecs
from csvkit import CSVKitReader
from csvkit.cli import CSVKitUtility, match_column_identifier
from csvkit.exceptions import NonUniqueKeyColumnException
class CSVJSON(CSVKitUtility):
description = 'Convert a CSV file into JSON (or GeoJSON).'
override_flags = ['H... | }
| }
# Keyed JSON
elif self.args.key:
output = {}
for row in rows:
row_dict = dict(zip(column_names, row))
k = row_dict[self.args.key]
if k in output:
raise NonUniqueKeyColumnException('Value %s i... |
ivan-fedorov/intellij-community | python/testData/psi/ExecPy2.py | Python | apache-2.0 | 25 | 0 | e | xec 'print 1' in {}, {} | |
jbaiter/plugin.video.brmediathek | resources/lib/xbmcswift2/mockxbmc/xbmcaddon.py | Python | gpl-3.0 | 1,905 | 0.0021 | import os
from xbmcswift2.logger import log
from xbmcswift2.mockxbmc import utils
def _get_env_setting(name):
return os.getenv('XBMCSWIFT2_%s' % name.upper())
class Addon(object):
def __init__(self, id=None):
# In CLI mode, xbmcswift2 must be run from the root of the addon
# directory, so w... | 'profile': 'special://profile/addon_data/%s/' % id,
'path': 'special://home/addons/%s' % id
}
self._strings = {}
self._settings = {}
def getAddonInfo(self, id):
properti | es = ['author', 'changelog', 'description', 'disclaimer',
'fanart', 'icon', 'id', 'name', 'path', 'profile', 'stars', 'summary',
'type', 'version']
assert id in properties, '%s is not a valid property.' % id
return self._info.get(id, 'Unavailable')
def getLocalizedString(sel... |
tmr232/Sark | tests/dumpers/data_dumper.py | Python | mit | 1,365 | 0 | import sark
from dumper_helper import dump_attrs
import itertools
def main():
print('Bytes')
print(list(itertools.islice(sark.data.B | ytes(), 10)))
print()
print('Bytes Until 0')
print(list(sark.data.bytes_until()))
print()
print('Words')
print(list(itertools.islice(sark.data.Words(), 10)))
print()
print('Words Until 0')
print(list(sark.data.words_until()))
print()
print('DWords')
print(list(ite... | lice(sark.data.Qwords(), 10)))
print()
print('QWords Until 0')
print(list(sark.data.qwords_until()))
print()
print('Native Words')
print(list(itertools.islice(sark.data.NativeWords(), 10)))
print()
print('Native Words Until 0')
print(list(sark.data.native_words_until()))
p... |
firemark/grazyna | grazyna/plugins/weekend.py | Python | gpl-2.0 | 562 | 0.005357 | from datetime import datetime
from grazyna.utils import register
@register(cmd='weekend')
def weekend(bot):
"""
Answer to timeless question - are we at .weekend, yet?
"""
current_d | ate = datetime.now()
day = current_date.weekday()
nick = bot.user.nick
if day in (5, 6):
| answer = "Oczywiście %s - jest weekend. Omawiamy tylko lajtowe tematy, ok?" % nick
else:
str_day = datetime.strftime(current_date, "%A")
answer = "%s - dopiero %s, musisz jeszcze poczekać..." % (nick, str_day)
bot.reply(answer)
|
mjschultz/django-tastefulpy | tests/core/tests/fields.py | Python | bsd-3-clause | 56,271 | 0.001528 | import datetime
from dateutil.tz import *
from django.db import models
from django.contrib.auth.models import User
from django.test import TestCase
from django.http import HttpRequest
from tastefulpy.bundle import Bundle
from tastefulpy.exceptions import ApiFieldError, NotFound
from tastefulpy.fields import *
from tast... | rst Post!')
# Make sure it uses attribute when there's no data
field_7 = ApiField(attribute='title')
field_7.instance_name = 'notinbundle'
self.assertEqual(field_7.hydrate(bundle), u'First Post!')
# Make sure it falls back to instance name if th | ere is no attribute
field_8 = ApiField()
field_8.instance_name = 'title'
self.assertEqual(field_8.hydrate(bundle), u'First Post!')
# Attribute & null regression test.
# First, simulate data missing from the bundle & ``null=True``.
field_9 = ApiField(attribute='notinbundl... |
tibor0991/OBM-BOB | bob-main/test_sender.py | Python | gpl-3.0 | 455 | 0.024176 | import socket
import sys
import time
server_add = './bob_system_socket'
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
message = sys.argv[1]+" "+sys.argv[2]
if sys.argv[1] == 'set':
message+= " "+sys.argv[3]
else:
message+= " null"
try:
sock.connect(server_add)
except socket.error, msg:
print >>sys.stde... | sock.recv(1024)
if data: print 'reply from server:', dat | a
time.sleep(1)
sock.close()
|
jmacmahon/invenio | modules/oairepository/lib/oai_repository_config.py | Python | gpl-2.0 | 1,219 | 0 | # This file is part of Invenio.
# Copyright (C) 2011 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of t | he GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio 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 PARTI... | ic License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""OAI Repository Configuration."""
# Maximum number of records to put in a single bibupload
CFG_OAI_REPOSITORY_MARCXML_SIZE = 1000
# A magic value used to specify the globa... |
rbuffat/pyidf | tests/test_zonehvacoutdoorairunit.py | Python | apache-2.0 | 5,734 | 0.004709 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.zone_hvac_forced_air_units import ZoneHvacOutdoorAirUnit
log = logging.getLogger(__name__)
class TestZoneHvacOutdoorAirUnit(unittest.TestCase):
def setUp(self):
sel... | nits[0].low_air_control_temperature_schedule_name, var_low_air_control_temperature_schedule_name)
self.assertEqual(idf2.zonehvacoutdoorairunits[0].outdoor_air_node_name, var_outdoor_air_node_name)
self.assertEqual(idf2.zonehvacoutdoorairunits[0].airoutlet_node_nam | e, var_airoutlet_node_name)
self.assertEqual(idf2.zonehvacoutdoorairunits[0].airinlet_node_name, var_airinlet_node_name)
self.assertEqual(idf2.zonehvacoutdoorairunits[0].supply_fanoutlet_node_name, var_supply_fanoutlet_node_name)
self.assertEqual(idf2.zonehvacoutdoorairunits[0].outdoor_air_unit_... |
ramusus/django-vkontakte-groups | vkontakte_groups/models.py | Python | bsd-3-clause | 6,504 | 0.003455 | # -*- coding: utf-8 -*-
import logging
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext as _
from vkontakte_api.models import VkontakteManager... | _wall.models import Comment
# TODO: improve schema and queries with using owner_id field
| return Comment.objects.filter(remote_id__startswith='-%s_' % self.remote_id)
@property
def topics_comments(self):
if 'vkontakte_board' not in settings.INSTALLED_APPS:
raise ImproperlyConfigured("Application 'vkontakte_board' not in INSTALLED_APPS")
from vkontakte_board.models impor... |
arjclark/rose | etc/rose-meta/rose-demo-baked-alaska-sponge/vn1.0/lib/python/macros/desoggy.py | Python | gpl-3.0 | 1,653 | 0 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2012-7 Met Office.
#
# This file is part of Rose, a framework for meteorological suites.
#
# Rose is free software: you can redistribute it and/or modify
# it under the terms of the GNU ... | lied warranty of
# MERCHA | NTABILITY 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 Rose. If not, see <http://www.gnu.org/licenses/>.
# -----------------------------------------------------------------------------
"""T... |
artizirk/digilib | store.py | Python | bsd-3-clause | 1,148 | 0.000871 | #/usr/bin/env python3
#####################
# code for mirroring/storing copy of digi.ee forum
from pymongo import MongoClient
import digilib
clien | t = MongoClient()
db = client.digi_clone
forums = db.forums
for forum in digilib.get_forums():
if not forums.find_one({"id": forum["id" | ]}):
print("inserting forum", forum["title"])
forums.insert(forum)
threads = db.threads
for forum in forums.find():
forum_id = forum["id"]
print("geting threads from forum id", forum_id)
for thread in digilib.get_all_threads_in_forum(forum_id):
thread["forum_id"] = forum_id
... |
3dfxsoftware/cbss-addons | invoice_report_per_journal/wizard/invoice_report_per_journal.py | Python | gpl-2.0 | 5,756 | 0.004343 | # -*- encoding: utf-8 -*- #
############################################################################
# Module Writen to OpenERP, Open Source Management Solution #
# Copyright (C) Vauxoo (<http://vauxoo.com>). #
# All Rights Reserved ... | ##################
# Coded by: Sabrina Romero (sabrina@vauxoo.com) #
# Planified by: | Nhomar Hernandez (nhomar@vauxoo.com) #
# Finance by: COMPANY NAME <EMAIL-COMPANY> #
# Audited by: author NAME LASTNAME <email@vauxoo.com> #
############################################################################
# This program is free soft... |
NSLS-II-CHX/ipython_ophyd | startup/97_HDM.py | Python | bsd-2-clause | 1,766 | 0.045866 |
CHA_Vol_PV = 'XF:11IDB-BI{X | BPM:02}CtrlDAC:ALevel-SP'
HDM_Encoder_PV = 'XF:11IDA-OP{Mir:HDM-Ax:P}Pos-I'
E=np.arange(9.,11.,.05)
SI_STRIPE = -9
RH_STRIPE = 9
def take_Rdata( voltage, E):
caput(CHA_Vol_PV, voltage)
#yield from bp.abs_set(hdm.y, RH_STRIPE)
hdm.y.user_setpoint.value = RH_STRIPE
sleep( 3.0 )
E_scan(list(E)... | Si_STRIPE)
hdm.y.user_setpoint.value = SI_STRIPE
sleep( 3.0 )
E_scan(list(E))
hsi=db[-1]
return get_R( hsi, hrh )
def get_R(header_si, header_rh):
datsi=get_table(header_si)
datrh=get_table(header_rh)
th_B=-datsi.dcm_b
En=xf.get_EBragg('Si111cryo',th_B)
Rsi=datsi.elm_s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.