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 |
|---|---|---|---|---|---|---|---|---|
chienlieu2017/it_management | odoo/addons/sale_timesheet/models/procurement.py | Python | gpl-3.0 | 3,947 | 0.00304 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
class ProcurementOrder(models.Model):
_inherit = 'procurement.order'
task_id = fields.Many2one('project.task', 'Task', copy=False)
def _is_procurement_task(self):
... | t:
self.sale_line_id.order_id._create_analytic_account()
account = self.sale_line_id.order_id.project_id
project = Pr | oject.search([('analytic_account_id', '=', account.id)], limit=1)
if not project:
project_id = account.project_create({'name': account.name, 'use_tasks': True})
project = Project.browse(project_id)
return project
def _create_service_task(self):
project = ... |
BeenzSyed/tempest | tempest/hacking/checks.py | Python | apache-2.0 | 2,295 | 0 | # Copyright 2013 IBM Corp.
#
# 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 wri... | (scenario_t | ests_need_service_tags)
register(no_setupclass_for_unit_tests)
|
DailyActie/Surrogate-Model | 01-codes/scipy-master/scipy/sparse/linalg/__init__.py | Python | mit | 3,095 | 0.000323 | "" | "
==================================================
Sparse linear algebra (:mod:`scipy.sparse.linalg`)
==================================================
.. currentmodule:: scipy.sparse.linalg
Abstract linear operators
-------------------------
.. autosummary::
:toctree: generated/
LinearOperator -- abstract... | linear operator
aslinearoperator -- convert an object to an abstract linear operator
Matrix Operations
-----------------
.. autosummary::
:toctree: generated/
inv -- compute the sparse matrix inverse
expm -- compute the sparse matrix exponential
expm_multiply -- compute the product of a matrix expone... |
thisch/python-falafel | examples/project1/testrunner.py | Python | bsd-2-clause | 2,913 | 0 | #!/usr/bin/env python
from __future__ import print_function
import argparse
import os
from falafel import findout_terminal_width
from falafel import test_list
from falafel.runners import FalafelTestRunner
from falafel.loaders import FalafelTestLoader
parser = argparse.ArgumentParser(description='custom test runner ... | default='log')
parser.add_argumen | t("--debug", action="store_true",
help="print logging messages")
parser.add_argument("--interactive", '--enable-interactive-tests',
action="store_true", dest='interactive',
help="if not set then all interactive tests are skipped")
args = parser.parse_args()
... |
angr/angr | angr/procedures/stubs/format_parser.py | Python | bsd-2-clause | 27,862 | 0.003769 | from typing import List, Dict, TYPE_CHECKING
from string import digits as ascii_digits
import logging
import math
import claripy
from ... import sim_type
from ...sim_procedure import SimProcedure
from ...storage.file import SimPackets
if TYPE_CHECKING:
from angr.sim_type import SimType
l = logging.getLogger(nam... | nstance(simfd.read_storage, SimPackets):
for component in self.components:
if type(component) is bytes:
sdata, _ = simfd.read_data(len(component), short_reads=False)
self.state.add_constraints(sdata == component)
elif isinstance(compone... | sdata, _ = simfd.read_data(len(component) // 8, short_reads=False)
self.state.add_constraints(sdata == component)
elif component.spec_type == b's':
if component.length_spec is None:
sdata, slen = simfd.read_data(self.state.libc.buf_sym... |
kasra-hosseini/obspyDMT | obspyDMT/tests/test_input_handler.py | Python | gpl-3.0 | 6,739 | 0.00089 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------
# Filename: test_input_handler.py
# Purpose: testing input_handler
# Author: Kasra Hosseini
# Email: kasra.hosseinizad@earth.ox.ac.uk
# License: GPLv3
# ----------------------------... | put_dics['evradmin'] is None
assert input_dics['evradmax'] is None
assert input_dics['interval'] == 36 | 00*24
assert input_dics['pre_process'] == 'process_unit'
assert input_dics['select_data'] is False
assert input_dics['corr_unit'] == 'DIS'
assert input_dics['pre_filt'] == '(0.008, 0.012, 3.0, 4.0)'
assert input_dics['water_level'] == 600.0
assert input_dics['plot_dir_name'] == 'raw'
assert ... |
peadar/pstack | tests/pstack.py | Python | bsd-2-clause | 613 | 0.017945 | import json
import subprocess
import coremonitor
import sys
import os
PSTACK_BIN = os.environ.get("PSTACK_BIN", "pstack")
def JSON(cmd, childfunc = None):
with coremonitor.CoreMonitor( cmd, childfunc ) as cm:
args = ["./%s" % PSTACK_BIN, "-j" ]
if childfunc:
args.append(sys.executable | )
args.append(cm.core())
text = subprocess.check_output(args)
j = jso | n.loads( text )
return j
def TEXT(cmd):
with coremonitor.CoreMonitor( cmd, None ) as cm:
text = subprocess.check_output(["./%s" % PSTACK_BIN, "-a", cm.core()])
return text
|
datalib/proclib | proclib/process.py | Python | mit | 1,603 | 0 | """
proclib.process
~~~~~~~~~~~~~~~
Implements the Process class.
"""
from subprocess import Popen, PIPE
from .response import Response
from .helpers import restore_signals
class Process(object):
"""
A Process object is a wrapper around a regular
`subprocess.Popen` instance that knows how to... | self.command = command
self.process | = Popen(args=command, **conf)
def pipe(self, lines):
"""
Given a Process with a valid stdin (not a
file-handle that is not PIPE), write *lines*
of data to the process where *lines* can
be any iterable.
:param lines: Iterable of data to be piped
in to the... |
mrquim/mrquimrepo | script.module.youtube.dl/service.py | Python | gpl-2.0 | 2,091 | 0.002869 | # -*- coding: utf-8 -*-
import sys
import json
import binascii
import xbmc
from lib.yd_private_libs import util, servicecontrol, jsonqueue
sys.path.insert(0, util.MODULE_PATH)
import YDStreamExtractor # noqa E402
import threading # noqa E402
class Service(xbmc.Monitor):
def __init__(self):
self.download... | self.controller = servi | cecontrol.ServiceControl()
self.start()
def onNotification(self, sender, method, data):
if not sender == 'script.module.youtube.dl':
return
self.processCommand(method.split('.', 1)[-1], self.controller.processCommandData(data)) # Remove the "Other." prefix
def processComma... |
rishubhjain/commons | tendrl/commons/profiler.py | Python | lgpl-2.1 | 1,214 | 0.016474 | import os
import sys
def start():
# enable profling by adding to local conf.yaml "with_internal_profiling: True"
# required: "pip install GreenletProfiler"
# Pro | vides function stats in formats 'pstat', 'callgrind', 'ystat'
# stats are saved at "/var/lib/tendrl/profiling/$NS.publisher_id/last_run_func_stat.$stat_type"
# eg: tendrl-node-agent : /var/lib/tendrl/profiling/node_agent/last_run_func_stat.pstat
import atexit
import GreenletProfiler
GreenletProfiler.set... | r.stop()
sys.stdout.write("\nStopped Tendrl profiling...")
stats = GreenletProfiler.get_func_stats()
_base_path = "/var/lib/tendrl/profiling/{0}/".format(NS.publisher_id)
if not os.path.exists(_base_path):
os.makedirs(_base_path)
for stat_type in ['pstat', 'callgrind', 'ystat']:... |
wackou/smewt | smewt/__init__.py | Python | gpl-3.0 | 1,579 | 0.006333 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Smewt - A smart collection manager
# Copyright (c) 2008 Ricard Marxer <rikrd@smewt.com>
# Copyright (c) 2013 Nicolas Wack <wackou@smewt.com>
#
# Smewt is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publi... | ven the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
ORG_NAME = 'Falafelton'
APP_NAME = '... | e
from appdirs import AppDirs
dirs = AppDirs(APP_NAME, ORG_NAME, version=__version__)
import logging
class NullHandler(logging.Handler):
def emit(self, record):
pass
h = NullHandler()
logging.getLogger("smewt").addHandler(h)
from guessit.slogging import setupLogging
import smewt.config
setupLogging... |
atvcaptain/enigma2 | RecordTimer.py | Python | gpl-2.0 | 61,002 | 0.028999 | from __future__ import print_function
from boxbranding import getMachineBrand, getMachineName
import xml.etree.cElementTree
from datetime import datetime
from time import localtime, strftime, ctime, time
from bisect import insort
from sys import maxsize
import os
from enigma import eEPGCache, getBestPlayableServiceRefe... | elf):
p | ass
JUSTPLAY = config.recording.default_timertype.value == "zap"
ALWAYS_ZAP = config.recording.default_timertype.value == "zap+record"
def findSafeRecordPath(dirname):
if not dirname:
return None
dirname = os.path.realpath(dirname)
mountpoint = Harddisk.findMountPoint(dirname)
if not os.path.ismount(mountpoin... |
cnamejj/PyProc | regentest/net_sockstat.py | Python | gpl-2.0 | 1,758 | 0.004551 | #!/usr/bin/env python
"""Handle records from /proc/net/sockstat data files"""
import regentest as RG
import ProcHandlers as PH
PFC = PH.ProcFieldConstants
USED = 'used'
INUSE = 'inuse'
ORPH = 'orphan'
TW = 'tw'
ALLOC = 'alloc'
MEM = 'mem'
MEMORY = 'memory'
# ---
# pylint: disable=R0914
def re_net_sockstat(inprec... | _spd[ORPH]
__tcptw = __spd[TW]
__tcpall = __spd[ALLOC]
__tcpmem = __spd[MEM]
__spd = __ff[PFC.F_SOCK_UDP]
__udpuse = __spd[INUSE]
__udpmem = __spd[MEM]
__spd = __ff[PFC.F_SOCK_UDPLITE]
__ultuse = __spd[INUSE]
__spd = __ff[PFC.F_SOCK_RAW]
... | __ff[PFC.F_SOCK_FRAG]
__fruse = __spd[INUSE]
__frmem = __spd[MEMORY]
#...+....1....+....2....+....3....+....4....+....5....+....6....+....7....+....8
print __template.format(used=__socks, tcpuse=__tcpuse,
tcporph=__tcporph, tcptw=__tcptw, tcpall=__tcpall,
tcpmem=... |
b-carter/numpy | numpy/polynomial/tests/test_printing.py | Python | bsd-3-clause | 2,164 | 0 | from __future__ import division, absolute_import, print_function
import numpy.polynomial as poly
from numpy.testing import run_module_suite, assert_equal
class TestStr(object):
def test_polynomial_str(self):
res = str(poly.Polynomial([0, 1]))
tgt = 'poly([ 0. 1.])'
assert_equal(res, tgt)... | . 1.])'
assert_equal(res, tgt)
def test_hermiteE_str(self):
res = str(poly.HermiteE([0, 1]))
tgt = 'herme([ 0. 1.])'
assert_equal(res, tgt)
def test_laguerre_str(self):
res = str(poly.Laguerre([0, 1]))
| tgt = 'lag([ 0. 1.])'
assert_equal(res, tgt)
class TestRepr(object):
def test_polynomial_str(self):
res = repr(poly.Polynomial([0, 1]))
tgt = 'Polynomial([ 0., 1.], domain=[-1, 1], window=[-1, 1])'
assert_equal(res, tgt)
def test_chebyshev_str(self):
res = repr... |
riseofthetigers/conceptnet | maint/ratings_to_votes_to_events.py | Python | gpl-2.0 | 627 | 0.022329 | import sys
sys.path.insert(0, '..')
import settings
from util import queryset_foreach
from events.models import Event
from voting.models import Vote
from datetime import datetime
from conceptnet4.models import | Rating
def rating_to_vote(r):
obj = r.sentence or r.raw_assertion or r.assertion
score = 0
if r.score > 0: score=1
if r.score < 0: score=-1
Vote.objects.record_vote(obj, r.user, score)
ev = Event.record_event(obj, r.user, r.activity)
ev.t | imestamp = r.updated
ev.save()
def progress_callback(num, den):
print num, '/', den
queryset_foreach(Rating.objects.all(), rating_to_vote)
|
rafaelmartins/blohg | blohg/tests/vcs_backends/hg/filectx.py | Python | gpl-2.0 | 2,627 | 0.000381 | # -*- coding: utf-8 -*-
"""
blohg.tests.vcs_backends.hg.filectx
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Module with tests for blohg integration with mercurial (file context).
:copyright: (c) 2010-2013 by Rafael Goncalves Martins
:license: GPL-2, see LICENSE for more details.
"""
import codecs
import ... | _name)
self.assertEqual(ctx.content, 'test\n')
with codecs.open(self.file_path, 'a', encoding='utf-8') as fp:
fp.write('lol\n') # change file witho | ut hg add
ctx = FileCtx(self.repo, self.changectx, self.file_name)
self.assertEqual(ctx.content, 'test\nlol\n')
def test_author(self):
ctx = FileCtx(self.repo, self.changectx, self.file_name)
self.assertEqual(ctx.author, 'foo <foo@bar.com>')
def test_date_and_mdate(self):
... |
facekapow/runtime | deps/v8/tools/release/common_includes.py | Python | apache-2.0 | 29,028 | 0.009336 | #!/usr/bin/env python
# Copyright 2013 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice... | # OWNER OR CONTRIBUTORS BE LIABLE FOR 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 CON... | UDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import argparse
import datetime
import httplib
import glob
import imp
import json
import os
import re
import shutil
import subprocess
import sys
import textwrap
import time
import url... |
andybondar/CloudFerry | devlab/tests/config.py | Python | apache-2.0 | 9,435 | 0.00371 | # Users to create/de | lete
users = [
{'name': 'user1', 'password': 'passwd1', 'email': 'mail@example.com',
'tenant': 'tenant1', 'enabled': True},
{'name': 'user2', 'password': 'passwd2', 'email': 'aa@example.com',
'tenant': 'tenant2', 'enabled' | : True},
{'name': 'user3', 'password': 'paafdssswd1', 'email': 'mdsail@example.com',
'tenant': 'tenant1', 'enabled': False},
{'name': 'user4', 'password': 'asaasdf', 'email': 'asdasd@example.com',
'tenant': 'tenant2', 'enabled': False}
]
# Roles to create/delete
roles = [
{'name': 'SomeRole'}
]
... |
kubeflow/kfserving-lts | python/alibiexplainer/alibiexplainer/__init__.py | Python | apache-2.0 | 655 | 0 | # Copyright | 2019 kubeflow.org.
#
# 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
# ... | or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .explainer import AlibiExplainer # noqa # pylint: disable=unused-import
|
nhynes/neon | examples/babi/train.py | Python | apache-2.0 | 4,049 | 0.001482 | #!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright 2015 Nervana Systems Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ... | gs['save_path'] = args.save_path
# setup backend
args.batch_size = 32
be = gen_backend(**extract_valid_args(args, gen_backend))
# load the bAbI dataset
babi = babi_handler(args.data_dir, args.task)
train_set = QA(*babi.train)
valid_set = QA(*babi.test)
# create model
model = create_model(babi.vocab_size, args.rlayer... | optimizer=Adam(),
num_epochs=args.epochs,
cost=GeneralizedCost(costfunc=CrossEntropyMulti()),
callbacks=callbacks)
# output accuracies
print('Train Accuracy = %.1f%%' % (model.eval(train_set, metric=Accuracy())*100))
print('Test Accuracy = %.1f%%' % (model.eval(valid_set, metric=Accura... |
anandkp92/waf | gui/__init__.py | Python | gpl-2.0 | 96 | 0 | #! /usr/bin | /env python
# encodi | ng: UTF-8
'''give access permission for files in this folder'''
|
ruibarreira/linuxtrail | usr/lib/python2.7/dist-packages/numpy/polynomial/laguerre.py | Python | gpl-3.0 | 54,314 | 0.001252 | """
Objects for dealing with Laguerre series.
This module provides a number of objects (mostly functions) useful for
dealing with Laguerre series, including a `Laguerre` class that
encapsulates the usual arithmetic operations. (General information
on how this module represents and works with such polynomials is in th... | om a Laguerre series.
- `lagline` -- Laguerre series of given straight line.
- `lag2poly` -- convert a Laguerre series to a polynomial.
- `poly2lag` -- convert a polynomial to a Laguerre series.
Classes
-------
- `Laguerre` -- A Laguerre series class.
See also
--------
`numpy.polynomial`
| """
from __future__ import division, absolute_import, print_function
import numpy as np
import numpy.linalg as la
from . import polyutils as pu
import warnings
from .polytemplate import polytemplate
__all__ = ['lagzero', 'lagone', 'lagx', 'lagdomain', 'lagline',
'lagadd', 'lagsub', 'lagmulx', 'lagmul', 'lagdiv', ... |
TransparentHealth/python-poetri | tests/test_sign_poet.py | Python | apache-2.0 | 2,235 | 0.002685 | #!/usr/bin/env python
import unittest, os
from poetri.sign_poet import sign_poet
#This key is for testing and the CN is "transparenthealth.org"
test_private_key = """
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQComk77MDN73N/w
FphyPbL0uc0jzKvSI8qK/TGvDx+9ygPFzYq6RdsgNE5cOHdtXk6/ukaMt7s... | e08SL0wj2aqa+iuys/6k1Ociz8xoEeEK0
4kEhbDileQKBgDYGiXsUELdz3lntdK4UX+VhM60F8nfzCe4/cUeXeKuA4P3m8rjw
Gh03A/9mT6B4J3YfC4RDbcRHGDm6nFX8vDCdVe+lfo/UptPbklxhhfVBO7c3BSLi
eHoIONp3IL/VONfBSRwo15dmmOnGUhkCg6dWmQ0wxVbH1LYQzFGpPQQBAoGAYoSA
r03zGonhYlme1DvByaqgv++v3GoGDj8XQ6VY9R5BQKyFq5eISNTODFkEnWulDKXv
FIZ2WyQSGNvOY3CVQG9hLVD6w5... | 8X1oXdqRjKpY7kHXFYHB/fAxsUVCyOP82JVl5mq
yld/v0Z19nKV1e+rQz8DhdJtyUOOQ1szetHHvprDSK3KulBcojznIDgrRHqxSJcc
j1DFK16BeYLj88PTTKLtheE=
-----END PRIVATE KEY-----"""
class TestSigning(unittest.TestCase):
def test_sign_poet_happy(self):
result = sign_poet({"sub":"someapp.foo.com"}, test_private_key, "tranparenth... |
beregond/jsonmodels | setup.py | Python | bsd-3-clause | 2,441 | 0 | #!/usr/bin/env python
# coding: utf-8
import os
import sys
from setuptools.command.test import test as TestCommand
from jsonmodels import __version__, __author__, __email__
from setuptools import setup
PROJECT_NAME = 'jsonmodels'
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.e... | ',
],
license="BSD",
zip_safe=False,
keywords=PROJECT_NAME,
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
"Programming Langua | ge :: Python :: 2",
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
... |
pelikanchik/edx-platform | cms/envs/test.py | Python | agpl-3.0 | 5,662 | 0.001236 | """
This config file runs the simplest dev environment using sqlite, and db-based
sessions. Assumes structure:
/envroot/
/db # This is where it'll write the database file
/edx-platform # The location of this repo
/log # Where we're going to write log files
"""
# We intentionally define lot... | s.path.isdir(COMMON_TEST_DATA_ROOT / course_dir)
]
DOC_STORE_CONFIG = {
'host': 'localhost',
'db': 'test_xmodule',
'collection': 'test_modulestore',
}
MODULESTORE_OPTIONS = {
'default_class': 'xmodule.raw_module.RawDescriptor',
'fs_root': TEST_ROOT / "data",
'render_template': 'edxmako.shortcu... | ulestore.draft.DraftModuleStore',
'DOC_STORE_CONFIG': DOC_STORE_CONFIG,
'OPTIONS': MODULESTORE_OPTIONS
},
'direct': {
'ENGINE': 'xmodule.modulestore.mongo.MongoModuleStore',
'DOC_STORE_CONFIG': DOC_STORE_CONFIG,
'OPTIONS': MODULESTORE_OPTIONS
},
'draft': {
... |
google-research/google-research | mentormix/code/cifar_eval.py | Python | apache-2.0 | 5,345 | 0.002619 | # coding=utf-8
# Copyright 2022 The Google Research 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... | ort cifar_data_provider
import resnet_model
import tensor | flow as tf
import tensorflow.contrib.slim as slim
flags = tf.app.flags
flags.DEFINE_integer('batch_size', 25, 'The number of images in each batch.')
flags.DEFINE_string('data_dir', '', 'Data dir')
flags.DEFINE_string('dataset_name', 'cifar100', 'cifar10 or cifar100')
flags.DEFINE_string('studentnet', 'resnet32', '... |
andmos/ansible | lib/ansible/modules/packaging/os/installp.py | Python | gpl-3.0 | 9,242 | 0.002597 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Kairo Araujo <kairo@kairo.eti.br>
# 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':... | alled_pkgs[package] = pkg_info[key][1]
else:
if not module.check_mode:
rc, out, err = module.run_command("%s -a %s -X -d %s %s" % (installp_cmd, accept_license_param[accept_license], repository_path, package))
if rc != 0:
modul... | p", rc=rc, err=err)
installed_pkgs.append(package)
else:
not_found_pkgs.append(package)
if len(installed_pkgs) > 0:
installed_msg = (" Installed: %s." % ' '.join(installed_pkgs))
else:
installed_msg = ''
if len(not_found_pkgs) > 0:
not_found_msg... |
Cloudzero/cloudzero-reactor-aws | test/unit/aws/test_unit_cloudtrail.py | Python | bsd-3-clause | 4,413 | 0.002493 | # -*- coding: utf-8 -*-
# Copyright (c) 2016-present, CloudZero, Inc. All rights reserved.
# Licensed under the BSD-style license. See LICENSE file in the project root for full license information.
import pytest
from reactor.aws.cloudtrail import traverse_map, CloudTrailEvent
def test_traverse_map():
d = {'x': ... | s': None,
'additionaleventdata': {
'functionVersion': 'arn:aws:lambd | a:us-east-1:1234567890123:function:function-name:$LATEST'
},
'requestid': '6a733515-cc52-412b-bb7d-70766f30f5d0',
'eventid': 'a250f917-32ef-4174-ab0e-49d9fc955243',
'readonly': False,
'resources': [
{
'accountId': '1234567890123',
'type... |
bellowsj/aiopogo | aiopogo/pgoapi.py | Python | mit | 6,917 | 0.001446 | from logging import getLogger
from yarl import URL
from aiohttp import BasicAuth
try:
from aiosocks import Socks4Auth, Socks5Auth
except ImportError:
class Socks4Auth(Exception):
def __init__(*args, **kwargs):
raise ImportError(
'You must install aiosocks to use a SOCKS prox... | lif provider == 'google':
self.auth_prov | ider = AuthGoogle(
proxy=self._proxy, refresh_token=refresh_token)
if refresh_token:
return await self.auth_provider.get_access_token()
else:
raise InvalidCredentialsException(
"Invalid authentication provider - only ptc/google available.")... |
jxta/cc | vendor/Twisted-10.0.0/doc/web/examples/advogato.py | Python | apache-2.0 | 1,110 | 0.002703 | # Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
#
'''
Usage:
advogato.py <name> <diary entry file>
'''
from twisted.web.xmlrpc import Proxy
from twisted.internet import reactor
from getpass import getpass
import sys
class AddDiary:
def __init__(self, name, password):
... | (self, cookie):
d = self.proxy.callRemote('diary.set', cookie, -1, self.data)
d.addCallbacks(self.setDiary, self.errorSetDiary)
def setDiary(self, response):
reactor.stop()
def errorSetDiary(self, error):
| print "could not set diary", error
reactor.stop()
diary = AddDiary(sys.argv[1], getpass())
diary(sys.argv[2])
reactor.run()
|
Arkapravo/morse-0.6 | testing/base/gyroscope_testing.py | Python | bsd-3-clause | 1,647 | 0.003036 | #! /usr/bin/ | env python
"""
This script tests the 'data stream' oriented feature of the socket interface.
"""
from morse.testing.testing import MorseTestCase
try:
# Include this import to be able to use your test file as a regular
# builder script, ie, usable with: 'morse [run|exec] <your test>.py
f | rom morse.builder import *
except ImportError:
pass
import os
import sys
import socket
import math
from pymorse import Morse
class GyroTest(MorseTestCase):
def setUpEnv(self):
robot = Robot('rmax')
robot.translate(0.0, 0.0, 40.0)
robot.rotate(math.pi/16, math.pi/8, math.pi/2... |
whav/hav | src/hav/apps/theme/apps.py | Python | gpl-3.0 | 151 | 0 | from django.apps import AppConfig
class ThemeCo | nfig(AppConfig):
default_auto_field = "django.db.models | .BigAutoField"
name = "hav.apps.theme"
|
nacker/pythonProject | Django/test1/booktest/views.py | Python | apache-2.0 | 633 | 0.011058 | from django.shortcuts import render
from django.http import *
from .models import *
# from django.template import RequestContext,loader
# Create your views here.
def index(request):
# return HttpResponse('hello')
# temp=loader.get_template('booktest/index.html')
# return HttpResponse(temp.render())
b... | ects.all()
context = {'list': bookList}
return render(request, 'booktest/index.html',context)
def show(request,id):
book = BookInfo.objects.get(pk=id)
heroList = book.heroinfo_set.all()
context = {'list': heroList}
return render(request,'booktest/show.ht | ml',context) |
DevicePilot/synth | synth/timefunctions/sinewave.py | Python | mit | 5,812 | 0.007915 | """
sinewave
========
Generates a sinusoidal wave of programmable period. 32 points are generated per cycle.
Arguments::
{
"period" : the period of the cycle e.g. "PT10M"
(the above can be an array, in which case multiple sinewaves are generated and added. This can be useful for Fourier synthesis,... | d, hashes the value of the named property to offset the phase by an effectively random amount (so multiple devices are all at different points in the cycle)
"precision" : (optional) If specified, the precision of the output (1= integer, 10 = decimal place, 100 = two decimals)
}
"""
from .timefunction impor... | def __init__(self, engine, device, params):
self.engine = engine
self.device = device
p = params.get("period", "P1D") # We accept a string or a list of strings
self.periods = [] # But internally always operate on a list
if type(p) == list:
for i in p:
... |
kyrsjo/AcdOpti | src/acdOpti/analysis/Omega3P_modeInfo.py | Python | gpl-3.0 | 6,060 | 0.007923 | # -*- coding: utf8 -*-
#
# Copyright 2011 Kyrre Ness Sjøbæk
# This file is part of AcdOpti.
#
# AcdOpti 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 you... | if os.path.isdir(os.path.join(finishedFolder, "omega3p_resu | lts")):
outputFilePath = os.path.join(finishedFolder, "omega3p_results", "omega3p.out")
elif os.path.isfile(os.path.join(finishedFolder,"output")):
outputFilePath = os.path.join(finishedFolder, "output")
else:
#self.exportResults.setValSingle("modes", "!!FILE_NOT_FOUN... |
Vincentyao1995/Globalink2017-UBC | Vincent/REE_Patterns/ModifiedGaussianModel.py | Python | mit | 11,072 | 0.0215 | import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
import spectral.io.envi as envi
import tensorflow as tf
from scipy import optimize
switch_excel = 0
switch_envi = 1
switch_dataFrame = 0
switch_sp_choice_envi = 0
switch_mutiBands = 1
#Modified ga... | s.centers
reflectance = sp_lib.spectra[int(sp_choice)]
spectrum = np.array([wavelength,reflectance]).T
hull = qhull(spectrum)
return spectrum, hull
# input excel file path, sheet name and pic file index. Return this file's average specturm reading from excel and the co | ntinuum of this avg sp. specturm: [[928,0.25], [935,0.41]....]
def get_hull_fromExcel(filePath =None, sheetName ='Sheet1', sp_index = 0):
df_excel = read_excel(filePath, sheetName = sheetName)
df_values = df_excel.values
list_column = list(df_excel.columns)
x_begin = list_column.index(928.080017)
... |
testmana2/test | Network/IRC/IrcNetworkEditDialog.py | Python | gpl-3.0 | 9,059 | 0.003864 | # -*- coding: utf-8 -*-
# Copyright (c) 2012 - 2015 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Module implementing a dialog for editing IRC network definitions.
"""
from __future__ import unicode_literals
import copy
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QT... | ity)
if index == -1:
index = 0
self.identityCombo.setCurrentIndex(index)
@pyqtSlot(str)
def on_identityCombo_currentIndexChanged(self, identity):
"""
Private slot to handle the selection of an identity.
@param identity se | lected entity (string)
"""
from .IrcNetworkManager import IrcIdentity
if identity == IrcIdentity.DefaultIdentityDisplay:
identity = IrcIdentity.DefaultIdentityName
self.__network.setIdentityName(identity)
@pyqtSlot()
def on_editIdentitiesButton_clicked(self):
... |
DistrictDataLabs/yellowbrick | tests/test_contrib/test_wrapper.py | Python | apache-2.0 | 7,549 | 0.001722 | # tests.test_contrib.test_wrapper
# Tests third-party estimator wrapper
#
# Author: Benjamin Bengfort
# Created: Fri Oct 02 17:27:50 2020 -0400
#
# Copyright (C) 2020 The scikit-yb developers
# For license information, see LICENSE.txt
#
# ID: test_wrapper.py [] benjamin@bengfort.com $
"""
Tests third-party estimato... | r_detector(self):
"""
Assert a wrapped estimator passes is_outlier_detector check
"""
tpe = wrap(ThirdPartyEstimator(), OUTLIER_DETECTOR)
assert sk_is_outlier_detector(tpe)
def test_wraps_is_probabilistic(self) | :
"""
Assert a wrapped estimator passes is_probabilistic check
"""
tpe = wrap(ThirdPartyEstimator())
assert is_probabilistic(tpe)
##########################################################################
## Test Non-sklearn Estimators
##########################################... |
f0rk/sigdebug | sigdebug/__init__.py | Python | bsd-2-clause | 1,776 | 0.002815 | # Copyright 2011 Ryan P. Kelly <rpkelly@cpan.org>
#
# This code was inspired by this thread on stackoverflow:
# http://stackoverflow.com/questions/132058/getting-stack-trace-from-a-running-python-application
#
# This code is BSD licensed, please see LICENSE for the full text.
import sys
import signal
import traceback
... | raceback:\n" % signum
banner += "".join(traceback.format_stack(frame))
print(banner)
Pdb().set_trace(frame)
def stack(signum, frame):
"""When invoked, print out the Traceback for the provided stack frame.
:param sign | um: The signal that was received.
:param frame: A python stack frame.
"""
print("Traceback:\n" + "".join(traceback.format_stack(frame)))
def threadstacks(signum, frame):
"""Print out the Traceback of every thread currently available.
:param signum: The signal that was received.
:param frame: ... |
sallai/mbuild | mbuild/bond_graph.py | Python | mit | 5,398 | 0.000556 | """
NOTE: The functions 'con | nected_components' and '_bfs' have been
obtained (with modifications) from the Networkx Python package,
which is distributed under the following BSD license:
Copyright (C) 2004-2016, NetworkX Developers
Ar | ic Hagberg <hagberg@lanl.gov>
Dan Schult <dschult@colgate.edu>
Pieter Swart <swart@lanl.gov>
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 copyr... |
pombreda/https-gitorious.org-appstream-figment | figment/forms.py | Python | gpl-3.0 | 627 | 0.023923 | from flask.ext.wtf import Form
from wtforms import TextField, BooleanField, SelectField
from wtforms.validators import Required
class GetId | Form(Form):
identifier = TextField('identifier', validators = [Required()])
class SearchForm(Form):
text = TextField('text', validators = [Required()])
class SearchItemsForm(Form):
kind_choices = [('mimetype', 'Mimetype'), ('lib', 'Library'), ('bin', 'Binary'),
| ('python2', 'Python-2 module'), ('python3', 'Python-3 module')]
text = TextField('text', validators = [Required()])
kind = SelectField('kind', choices = kind_choices, default = '1')
|
shuxin/androguard | androguard/decompiler/dad/opcode_ins.py | Python | apache-2.0 | 61,738 | 0 | # This file is part of Androguard.
#
# Copyright (C) 2012, Geoffroy Gueguen <geoffroy.gueguen@gmail.com>
# 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:/... | y_2addr_exp(ins, val_op, op_type, vmap):
reg_a, reg_b = get_variables(vmap, ins.A, ins.B)
return AssignExpression(reg_a, BinaryExpression2Addr(val_op, reg_a, reg_b,
op_type))
def assign_lit(op_type, val_cst, val_a, val_b, vmap):
cst = Constant(val_c... | , BinaryExpressionLit(op_type, var_b, cst))
# nop
def nop(ins, vmap):
return NopExpression()
# move vA, vB ( 4b, 4b )
def move(ins, vmap):
logger.debug('Move %s', ins.get_output())
reg_a, reg_b = get_variables(vmap, ins.A, ins.B)
return MoveExpression(reg_a, reg_b)
# move/from16 vAA, vBBBB ( 8b, 1... |
garrettr/securedrop | securedrop/tests/functional/test_source_notfound.py | Python | agpl-3.0 | 256 | 0 | import source_navigation_steps
import functional_test
class TestSourceInterfaceNotFound(
functio | nal_test.FunctionalTest,
source_navigation_steps.SourceNavigati | onStepsMixin):
def test_not_found(self):
self._source_not_found()
|
syuhei176/json-mergepy | jsonutil.py | Python | mit | 3,813 | 0.009704 | # -*- coding: utf-8 -*-
import sys
def diff(a,b):
return compareTree(a, b)
def getType(a):
if isinstance(a, dict):
return 'object'
elif isinstance(a, list):
return 'array'
elif isinstance(a, str):
return 'string'
elif isinstance(a, int):
return 'number'
elif isi... | #
#a=+ b=+
result[key] = merge_part(a[key], b[key])
| elif state == 1:
#- +
pass
elif state == 2:
#none +
result[key] = b[key]
elif state == 3:
#+ -
pass
elif state == 4:
#- -
pass
elif state == 5:
#none -
pass
eli... |
jjscarafia/l10n-canada | res_partner_attributes_add_SIN/tests/test_res_partner_sin.py | Python | agpl-3.0 | 1,595 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Odoo, Open Source Management Solution
# Copyright (C) 2013 Savoir-faire Linux (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under th... | })
def test_valid_sin(self):
"""
Test SIN from fake SIN generator
:return:
"""
self.partner.sin = 252646757
def test_invalid_sin(self):
with self.assertRaises(exceptions.ValidationError):
self.partner.si | n = 100000000
|
eri-trabiccolo/exaile | xl/__init__.py | Python | gpl-2.0 | 1,239 | 0.001614 | # Copyright (C) 2008-2010 Adam Olsen
#
# 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 So | ftware Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details... | eceived a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
#
# The developers of the Exaile media player hereby grant permission
# for non-GPL compatible GStreamer and Exaile plugins t... |
dbremner/bite-project | deps/mrtaskman/server/models/tasks.py | Python | apache-2.0 | 15,327 | 0.011157 | # 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 th... | import urllib
import webapp2
from third_party.prodeagle import counter
from util import db_properties
from util import parsetime
class Error(Exception):
pass
class TaskNotFoundError(Error):
pass
class TaskTimedOutError(Error):
pass
class TaskStates(object):
SCHEDULED = 'scheduled'
ASSIGNED = 'assigne... | db.Model):
"""The results of a Task, including logs and execution time."""
exit_code = db.IntegerProperty(required=True)
execution_time = db.FloatProperty(required=False)
stdout = blobstore.BlobReferenceProperty(required=False)
stderr = blobstore.BlobReferenceProperty(required=False)
stdout_download_url = d... |
patani1/PyHDB | pyhdb/protocol/__init__.py | Python | apache-2.0 | 95 | 0 | # The following import is requir | ed to register the 'cesu8' | codec in Python:
import pyhdb.cesu8
|
feblehober123/GETWatchBot2 | run.py | Python | gpl-3.0 | 620 | 0.024194 | #!/usr/bin/env python2
#This script keeps the bot running, restarts it, and writes error logs when it bugs out.
import logging
try:
open('errors.log', 'r').close()
except IOError:
open('errors.log', 'w').close()
logging.basicConfig(level=logging.WARNING, filename='errors.log', filemode = 'a', format='[%(asctime)s] ... | t "{0}! BOT RESTARTING NOW!".format(ex)
logging.warning('Resta | rting bot')
|
Azure/azure-sdk-for-python | sdk/resources/azure-mgmt-resource/azure/mgmt/resource/links/v2016_09_01/_management_link_client.py | Python | mit | 4,330 | 0.003464 | # 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 ... | rt,ungrouped-imports
from azure.core.credentials import TokenCredential
class ManagementLinkClient:
"""Azure resources can be linked together to form logical relationships. You can establish links between resources belonging to different resource groups. However, all the linked resources must belong to the sam... | urces are deleted or moved, the link owner must clean up the remaining link.
:ivar operations: Operations operations
:vartype operations: azure.mgmt.resource.links.v2016_09_01.operations.Operations
:ivar resource_links: ResourceLinksOperations operations
:vartype resource_links:
azure.mgmt.resourc... |
denys-duchier/Scolar | config/scodocutils.py | Python | gpl-2.0 | 4,053 | 0.010856 | """
Some utilities used by upgrade scripts
"""
import sys, os, psycopg, glob, subprocess, traceback, time
sys.path.append('..')
def log(msg):
sys.stdout.flush()
sys.stderr.write(msg+'\n')
sys.stderr.flush()
SCODOC_DIR=os.environ.get('SCODOC_DIR', '')
if not SCODOC_DIR:
log('Error: environment var... | "true if field exists in sql table"
cursor = cnx.cursor()
cursor.execute("SELECT column_name FROM information_schema.columns WHERE table_name = '%s'" % table)
r = cursor.fetchall()
fields = [ f[0] for f in r ]
return field in fields
def _run_sql( sql, cnx ):
cursor = cnx.cursor() |
error = False
try:
for cmd in sql:
log('executing SQL: %s' % cmd)
cursor.execute(cmd)
cnx.commit()
except:
cnx.rollback()
log('check_field: failure. Aborting transaction.')
error = True
traceback.print_exc()
return error
d... |
suzlab/Autoware | ros/src/sensing/fusion/packages/autoware_camera_lidar_calibrator/scripts/tarfile_calibration.py | Python | bsd-3-clause | 11,900 | 0.008235 | #!/usr/bin/env python
#
# Copyright (c) 2018, Nagoya University
# 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, th... | raise RuntimeError("connected to set_camera_info service, but failed setting camera_info")
if visualize:
#Show rectified images
calibrator.set_alpha(alpha)
archive = tarfile.open(tarname, 'r') |
if mono:
for f in archive.getnames():
if f.startswith('left') and (f.endswith('.pgm') or f.endswith('png')):
filedata = archive.extractfile(f).read()
file_bytes = numpy.asarray(bytearray(filedata), dtype=numpy.uint8)
im=cv2... |
defaultnamehere/grr | lib/flows/general/collectors_test.py | Python | apache-2.0 | 21,712 | 0.003915 | #!/usr/bin/env python
"""Test the collector flows."""
import os
from grr.client import vfs
from grr.lib import action_mocks
from grr.lib import aff4
from grr.lib import artifact
from grr.lib import artifact_lib
from grr.lib import artifact_test
from grr.lib import flags
from grr.lib import rdfvalue
from grr.lib impo... | ll_flow = MockCallFlow()
with utils.Stubber(c | ollectors.ArtifactCollectorFlow, "CallFlow",
mock_call_flow.CallFlow):
collect_flow = collectors.ArtifactCollectorFlow(None, token=self.token)
collect_flow.state.Register("knowledge_base", rdfvalue.KnowledgeBase())
collect_flow.current_artifact_name = "blah"
collect_flow.... |
lykops/lykops | library/connecter/ansible/yaml/data2db.py | Python | apache-2.0 | 12,807 | 0.012321 | import os
from library.connecter.ansible.yaml import Yaml_Base
class Data_DB(Yaml_Base):
def router(self, content, name, yaml_tpye='main', file_type='tasks', preserve=True, together=False, describe=''):
''' |
检测yaml数据的语法是否正确,如果含有include或/和roles,将把这些存储在后端数据库中
:参数
content:内容
name:名称,yaml文件内容写入数据的名称
preserve:是否写入数据库
to | gether:是否返回该main下所有文件内容=
describe:yaml文件内容写入数据的描述
zhname:yaml文件内容写入数据的中文名称,很简短说明
:return
元组,第一个为执行结果,
成功为true,文件内容(格式为字典))
失败为False,返回失败原因
'''
if yaml_tpye in ('full_roles' , 'main') :
result = self.main(con... |
byteweaver/django-forums | tests/test_model_post.py | Python | bsd-3-clause | 280 | 0 | from django.tes | t import TestCase
from forums.factories import PostFactory
class CategoryModelTests(TestCase):
def setUp(self):
self.post = PostFactory()
def test_string_method(self):
self.assertEquals(str(self.post), 'Body text\nWith multiple line | s!')
|
Kosinkadink/techtem-network | resources/protocols/radchat.py | Python | gpl-2.0 | 3,558 | 0.038505 | #!/usr/bin/python2
import os,sys,socket,select
from time import strftime
variables = ['name','tripcode']
servercommands = ["/pm", "/peoplecount"]
def date():
return strftime(".%Y-%m-%d")
def chat_client(inputsocket,data,location):
#initialize radchat client files
if not os.path.exists(location+'/resources/pro... | urces/programparts/radchat/logs')
if not os.path.exists(location+'/resources/programparts/radchat/settings.txt'):
with open(location+'/resources/programparts/radchat/settings.txt', "a") as settingsfile:
settingsfile.write("")
#introduce variables
name = data[0]
tripcode = data[1]
#if there is a settings f... | :
for line in settingsfile:
if line.split()[0] == "name":
name = line[5:].replace("\n","")
if line.split()[0] == "tripcode":
tripcode = line[9:].replace("\n", "")
if line.split()[0] == "host":
host = line[5:].replace("\n","")
if line.split()[0] == "port":
port = int(line[5:].repla... |
googlecodelabs/cts-snippets | jobs-and-companies-codelab/list_companies.py | Python | apache-2.0 | 1,392 | 0 | #!/usr/bin/env python
# Copyright 2019 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, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
... | ons and
# limitations under the License.
import os
from googleapiclient.discovery import build
from googleapiclient.errors import Error
client_service = build('jobs', 'v3')
project_id = 'projects/' + os.environ['GOOGLE_CLOUD_PROJECT']
try:
# Execute a query to list all companies. Only query parameter in this c... |
anhstudios/swganh | data/scripts/templates/object/ship/shared_hutt_heavy_s02_tier4.py | Python | mit | 417 | 0.05036 | #### NOTICE: THIS FILE IS AUTOGENERATED |
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Ship()
result.template = "object/ship/shared_hutt_heavy_s02_tier4.iff"
result.attribute_template_id = -1
result.stfName(" | ","")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
cliffyg/heron | third_party/pex/pex/platforms.py | Python | apache-2.0 | 2,387 | 0.008798 | # Copyright 2014 Pants project c | ontributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import
import re
import sys
from pkg_resources import compatible_platforms, get_supported_platform
class Platform(object):
class UnknownPlatformError(Exception):
def __init__(sel... | :
super(Platform.UnknownPlatformError, self).__init__('Unknown platform: %s' % platform) # noqa
# It blows my mind this code is not in distutils or distribute.
MACOSX_VERSION_STRING = re.compile(r"macosx-(\d+)\.(\d+)-(\S+)")
MACOSX_PLATFORM_COMPATIBILITY = {
'i386': ('i386',),
'ppc': ('ppc',),
... |
Ajuska/pyladies | 04/vypisrange.py | Python | mit | 52 | 0.04 | for cislo | in range(4):
print('Řádek', cislo)
| |
io07/BOJ-V4 | problem/views.py | Python | mit | 15,626 | 0.001088 |
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseForbidden
from django.views.generic import ListView, DetailView
fro | m djang | o.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from django.utils.decorators import method_decorator
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required
from django.shortcuts im... |
mavenlin/tensorflow | tensorflow/python/layers/base.py | Python | apache-2.0 | 79,316 | 0.006518 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | Arguments:
inputs: Input te | nsor or list/tuple of input tensors.
Must match the `inputs` argument passed to the `__call__` method
at the time the updates were created.
If you pass `inputs=None`, unconditional updates |
tabsoverspaces/ReactionGame | scripts/bracket_ui.py | Python | mit | 32,901 | 0.000091 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'reactiongameui.ui'
#
# Created by: PyQt5 UI code generator 5.8.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObject... | gnCenter)
self.BarLabel3.setObjectName("BarLabel3")
self.Button1 = QtWidgets.QPushButton(self.Main)
self.Button1.setGeometry(QtCore.QRect(570, 555, 101, 23))
self.Button1.setObjectName("Button1")
self.BarLabel1 = QtWidgets.QLabel(self.Main)
self.BarLabel1.se | tGeometry(QtCore.QRect(500, 5, 270, 31))
font = QtGui.QFont()
font.setFamily("DejaVu Sans")
font.setPointSize(14)
self.BarLabel1.setFont(font)
self.BarLabel1.setAutoFillBackground(True)
self.BarLabel1.setAlignment(QtCore.Qt.AlignCenter)
self.BarLabel1.setObjectNam... |
Azure/azure-sdk-for-python | sdk/servicebus/azure-servicebus/azure/servicebus/management/_xml_workaround_policy.py | Python | mit | 1,819 | 0.002749 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | x "ns1"
in the following xml. This workaround is to remove it.
<ns0:content type="application/xml">
<ns1:RuleDescription>
<ns1:Filter xsi:type="CorrelationFilter">
<ns1:CorrelationId>1</ns1:CorrelationId>
<ns1:MessageId>1</ns1:MessageId>
...
<... | _request(self, request):
# type: (PipelineRequest) -> None
"""Mutate serialized (QueueDescription, TopicDescription, SubscriptionDescription, RuleDescription)
XML to use default namespace.
:param request: The pipeline request object
:type request: ~azure.core.pipeline.PipelineRe... |
shallyan/AutoTest | Src/Tester.py | Python | mit | 459 | 0.054466 | #coding = utf-8
import sys
from File import File
from Execute import Exec | ute
def test():
isKeep = True
dstFileName = None
argsLen = len(sys.argv)
if argsLen < 2:
sys.exit()
if argsLen >= 3:
if sys.argv[2].startswith('-nk'):
isKeep = False
if argsLen > 3:
dstFileName = sys.argv[3]
srcFile = File(sys.argv[1], isKeep, dstFileName)
srcFile.parse()
exe = Execute(src... | |
amberheilman/mousetrap | src/mousetrap/app/lib/settings.py | Python | gpl-2.0 | 3,450 | 0.007536 | # -*- coding: utf-8 -*-
# MouseTrap
#
# Copyright 2009 Flavio Percoco Premoli
#
# This file is part of mouseTrap.
#
# MouseTrap is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License v2 as published
# by the Free Software Foundation.
#
# mouseTrap is distributed ... | = Settings()
created = False
if not os.path.exists( env.co | nfigPath ):
os.mkdir( env.configPath )
if not os.path.exists( env.configFile ):
cfg.write_first(env.configFile)
created = True
cfg.readfp(open( env.configFile ))
return created, cfg
|
allofhercats/whiskey | proto/header_verifier.py | Python | mit | 285 | 0.031579 | import base_verifier
import whiskey_parser
class Head | erVerifier(object):
def __init__(self):
pass
def verify(self, node):
if node.aid == whiskey_parser.ASTID.PAGE:
for i in node.fields["children"]:
self.verify(i)
elif node.aid == whis | key_parser.ASTID.TOPLEVEL_IMPORT: |
mscuthbert/abjad | abjad/tools/scoretools/test/test_scoretools_Rest___copy__.py | Python | gpl-3.0 | 1,144 | 0.000874 | # -*- encoding: utf-8 -*-
from abjad import *
import copy
def test_scoretools_Rest___copy___01():
r'''Copy rest.
'''
rest_1 = Rest((1, 4))
rest_2 = copy.copy(rest_1)
assert isinstance(rest_1, Rest)
assert isinstance(rest_2, Rest)
assert format(rest_1) == format(rest_2)
assert rest_1 ... | copy.copy(rest_1)
assert isinstance(rest_1, Rest)
assert isinstance(rest_2, Rest)
assert format(rest_1) == format(rest_2)
assert rest_1 is not rest_2
def test_scoretools_Rest___copy___03():
r'''Copy rest with LilyPond grob overrides and LilyPond context settings.
'''
rest_1 = Rest | ((1, 4))
override(rest_1).staff.note_head.color = 'red'
override(rest_1).accidental.color = 'red'
set_(rest_1).tuplet_full_length = True
rest_2 = copy.copy(rest_1)
assert isinstance(rest_1, Rest)
assert isinstance(rest_2, Rest)
assert format(rest_1) == format(rest_2)
assert rest_1 is no... |
paulocsilvajr/python-code | src/iterar.py | Python | gpl-3.0 | 1,531 | 0.003968 | #!/usr/ | bin/python3
# -*- coding: utf-8 -*-
from time import sleep
from random import randint
from argparse import ArgumentParser
""" Exemplo de retorno de carro e passagem de argumentos. """
parser = ArgumentParser(description='Exemplo de retor | no de carro e passagem de argumentos')
parser.add_argument('-s',
action='store',
type=float,
dest='segundos',
default=0.0,
help='Intervalo de impressão em segundos, padrão: 0.0 segundos')
parser.add_argument('-n',
... |
morpheby/ist303-miye | models/Repository.py | Python | gpl-3.0 | 2,779 | 0.009356 |
from .Room import Room
from .Client import Client
from .Reservation import Reservation
from support import Singleton
from .ReservationSearcher import ReservationSearcher
@Singleton
class Repository(object):
def __init__(self):
self.rooms = []
self.clients = []
self.reservations = []
... | r x in range(4) ]
self.rooms = [Room(r,g) for r,g in single + double + quad | ]
self.clients = [Client(*name.split(' ')) for name in ['Test User', "Another One", "Third Also"]]
self.reservations = [Reservation(self.clients[i].ID, f"{i+1}/1/2005", f"{i+1}/20/2005", self.rooms[i].ID, [self.clients[i].ID]) for i in range(len(self.clients))]
# After loading reservat... |
openstack/murano | murano/tests/unit/api/v1/test_static_actions.py | Python | apache-2.0 | 5,261 | 0 | # Copyright (c) 2016 Mirantis, Inc.
# Copyright (c) 2016 AT&T Corp
#
# 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 app... | request_data)
exc_types.append(exc_type)
self.assertEqual(mock_execute.call_count, len(exc_types))
exc_type = 'ThisIsARandomTestException'
mock_execute.side_effect = client.RemoteError(exc_type=exc_type)
req = self._post('/actions', jsonutils.dump_as_bytes( | request_data))
self.assertRaises(exc.HTTPServiceUnavailable, self.controller.execute,
req, request_data)
exc_types.append(exc_type)
self.assertEqual(mock_execute.call_count, len(exc_types))
try:
int('this will throw a value error')
except Va... |
TKCERT/pfFocus | pf_focus/format.py | Python | gpl-3.0 | 2,598 | 0.006928 | #!/usr/bin/env python3
import argparse
import sys
import yaml
from pf_focus.markdown import output_mar | kdown
from pf_focus.bbcode import output_bbcode
from pf_focus.parse import parse_pfsense
from pf_focus.pfsense import PfSenseDocument
from | pf_focus.progress import Animation
def output_yaml(doc, stream):
yaml.safe_dump(doc.data, stream)
OUTPUT_FORMATS = {
'yaml': output_yaml,
'md': output_markdown,
'bbcode': output_bbcode,
}
def get_output_func(args):
return OUTPUT_FORMATS.get(args.output_format, output_yaml)
def get_progress_anim... |
gajim/python-nbxmpp | nbxmpp/modules/chat_markers.py | Python | gpl-3.0 | 1,984 | 0 | # Copyright (C) 2018 Philipp Hörist <philipp AT hoerist.com>
#
# This file is part of nbxmpp.
#
# 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 opt... | StanzaHandler(name='message',
callback=self._process_message_marker,
ns=Namespace.CHATMARKERS,
priority=15),
]
def _process_message_marker(self, _client, stanza, properties):
type_ = stanza.getTag('received', namespace=N... | if type_ is None:
type_ = stanza.getTag('acknowledged',
namespace=Namespace.CHATMARKERS)
if type_ is None:
return
name = type_.getName()
id_ = type_.getAttr('id')
if id_ is None:
sel... |
mutoulbj/chem_spider | chem_spider/sigma_urls.py | Python | mit | 10,348 | 0.001532 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import random
import time
from pyquery import PyQuery as pq
from mongodb import db, conn
from requests.exceptions import ConnectionError
from chem_log import log
# urls = [
# 'http://www.sigmaaldrich.com/china-mainland/zh/analytical-chromatography/ana... | lis = pq(ul).find('li')
for li in lis:
url_list.append(base_url + pq(li)('a').attr('href'))
return url_list
def ch | romatography_extract_product_url(i, p):
"""
获取产品列表页的产品url
:param p: pyquery对象
:return:
"""
tables = p('table.opcTable')
for t in tables:
trs = pq(t)('tbody').find('tr')
for tr in trs:
href = pq(tr)('td:first a').attr('href')
if href:
d ... |
glemaitre/scikit-learn | sklearn/datasets/tests/test_california_housing.py | Python | bsd-3-clause | 1,370 | 0 | """Test the california_housing loader, if the data is available,
or if specifically requested via environment variable
(e.g. for travis cron job)."""
import pytest
from sklearn.datasets.tests.test_common import check_return_X_y
from functools import partial
def test_fetch(fetch_california_housing_fxt):
data = fe... | f test_fetch_asframe(fetch_california_housing_fxt):
pd = pytest.importorskip('pandas')
bunch = fetch_california_housing_fxt(as_frame=True)
frame = bunch.frame
assert hasattr(bunch, 'frame') is True
assert frame.shape == (20640, 9)
assert isinstance(bunch.data, pd.DataFrame)
assert isinstance... | e_pandas):
# Check that pandas is imported lazily and that an informative error
# message is raised when pandas is missing:
expected_msg = ('fetch_california_housing with as_frame=True'
' requires pandas')
with pytest.raises(ImportError, match=expected_msg):
fetch_california_... |
TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_nlu/ext/candc/src/scripts/ccg/template.py | Python | mit | 1,061 | 0.01508 | #!/usr/bin/env python
import re
class Templates:
TOKENS = re.compile('([A-Za-z]+|[^ ])')
SIMPLE = {
'l': '_n.l.ptb()',
'r': '_n.r.ptb()',
'<': 'addr(_n)',
'>': 'addl(_n)',
}
def compile(self, template):
python = self.parse(self.TOKENS.findall(template))
return eval("lambda _n: %s" % p... | ):
t = tokens.pop(0)
if t in '([':
if t == '(':
label = "'%s'" % tokens.pop(0)
args = self.parse_args(tokens, ')')
elif s[0] == '[' | :
label = 'None'
args = self.parse_args(tokens, ']')
return 'PTB(_n, %s, %s)' % (label, ', '.join(args))
elif t in self.SIMPLE:
return self.SIMPLE[t]
else:
raise SyntaxError, "unknown token '%s'" % t
def parse_args(self, tokens, delimiter):
args = []
while tokens:
... |
rctk/rctk | rctk/wsgi.py | Python | bsd-2-clause | 991 | 0.005045 | #!/usr/bin/python
from rctk.sessions import Session, SpawnedSession, Manager
from rctk.webpy import app
import os
startupdir = os.getcwd()
manager = None
def applic | ation(environ, start_response):
global manager
if manager is None:
| classid = environ.get('rctk.classid')
debug = environ.get('rctk.debug', "false").lower() in ("1", "true")
session = environ.get('rctk.session')
frontendclass = environ.get('rctk.frontend')
options = {}
optionconfig = environ.get('options')
if optionconfig:
... |
smartchicago/chicago-early-learning | python/ecep/portal/management/commands/export_topojson.py | Python | mit | 2,327 | 0.003438 | # Copyright (c) 2013 Azavea, Inc.
# See LICENSE in the project root for copying permission
from django.conf import settings
from django.contrib.gis.geos import GEOSGeometry, MultiPolygon
from django.core.management.base import BaseCommand
from django.db.models import Count
from vectorformats.Formats import Django, Ge... | , **options):
"""
Exports neighborhood to data directory, simplifying the polygons in the process.
Simplify: https://docs.djangoproject.com/en/1.4/ref/contrib/gis/geos/#django.contrib.gis.geos.GEOSGeometry.simplify
"""
data_path = 'portal/static/js'
neighborhoods = Neighb... | n.center = n.get_center()
# Simplify our boundaries so they take up less space
newBoundary = n.boundary.simplify(settings.SIMPLIFY_EPSILON, True)
if newBoundary.geom_type == 'MultiPolygon':
n.boundary = newBoundary
elif newBoundary.geom_type == 'Polyg... |
xiandiancloud/edxplaltfom-xusong | common/lib/xmodule/xmodule/contentstore/mongo.py | Python | agpl-3.0 | 17,630 | 0.003744 | import pymongo
import gridfs
from gridfs.errors import NoFile
from xmodule.contentstore.content import XASSET_LOCATION_TAG
import logging
from .content import StaticContent, ContentStore, StaticContentStream
from xmodule.exceptions import NotFoundError
from fs.osfs import OSFS
import os
import json
from bson.son imp... | AssetKey):
location_or_id, _ = self.asset_db_key(location_or_id)
# Deletes of non-existent files are considered successful
self.fs.delete(location_or_id)
def find(self, location, throw_on_not_found=True, as_stream=False):
content_id, __ = self.asset_db_key(location)
tr... | tion:
thumbnail_location = location.course_key.make_asset_key(
'thumbnail',
thumbnail_location[4]
)
return StaticContentStream(
location, fp.displayname, fp.content_type, fp, last_modified_at=fp.u... |
tiborsimko/zenodo | docs/conf.py | Python | gpl-2.0 | 10,857 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2015, 2016 CERN.
#
# Zenodo 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 l... | se_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Language to be used for generating the HTML full-text s | earch index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
# html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
# html_search... |
ayepezv/GAD_ERP | addons/website_forum_doc/models/forum_post.py | Python | gpl-3.0 | 790 | 0.005063 | # -*- coding: utf-8 -*-
from odoo import api, fields, models
class Post(models.Model):
_inherit = 'forum.post'
documentation_toc_id = fields.Many2one('fo | rum.documentation.toc', string='Documentation ToC', ondelete='set null')
documentation_stage_id = fields.Many2one('forum.documentation.stage', string='Documentation Stage',
default=lambda self: self.env['forum.documentation.stage'].search([], limit=1))
color = fields... | orum.documentation.stage'].search([]).name_get(), {}
_group_by_full = {
'documentation_stage_id': _read_group_stage_ids,
}
|
hjweide/a-star | examples/example.py | Python | mit | 637 | 0 | import numpy as np
import pyastar2d
# The start and goal coordinates are in matrix coordinates (i, j).
start = (0, 0)
goal = (4, 4)
# The minimum cost must be 1 for the heuristic to be valid.
weights = np.array([[1, 3, 3, 3, 3],
[2, 1, 3, 3, 3],
[2, 2, 1, 3, 3],
... | [2, 2, 2, 2, 1]], dtype=np.float32)
print("Cost matrix:")
print(weights)
path = pyastar2d.astar_path(weights, | start, goal, allow_diagonal=True)
# The path is returned as a numpy array of (i, j) coordinates.
print(f"Shortest path from {start} to {goal} found:")
print(path)
|
hiearth/langstyle | langstyle/service/sound_service.py | Python | gpl-2.0 | 1,021 | 0.001959 | #!/usr/bin/env python
from .. import config
from .. import helper
class SoundService:
def __init__(self, sound_repository, sound_file_service):
self._sound_repository = sound_repository
self._sound_file_service = sound_file_service
d | ef get(self, sound_id):
sound_item = self._sound_repository.get(sound_id)
if sound_item:
return self._sound_file_service.read(sound_item.md5)
return None
def get_key(self, sound_id):
sound_item = self._sound_repository.get(sound_id)
if sound_item:
ret... | :
sound_md5 = helper.md5_hash(sound_data)
try:
self._sound_file_service.write(sound_md5, sound_data)
sound_id = self._sound_repository.add(sound_md5, user_provider_id)
return sound_id
except Exception as e:
config.service_factory.get_log_service().... |
annulen/qtwebkit-snapshots | Source/WebKit2/Scripts/webkit/parser.py | Python | lgpl-2.1 | 5,618 | 0.002314 | # Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and... | e.startswith('#elif'):
raise Exception("ERROR: '%s' is not supported in the *.in files" % trimmed)
continue
match | = re.search(r'([A-Za-z_0-9]+)\((.*?)\)(?:(?:\s+->\s+)\((.*?)\))?(?:\s+(.*))?', line)
if match:
name, parameters_string, reply_parameters_string, attributes_string = match.groups()
if parameters_string:
parameters = parse_parameters_string(parameters_string)
... |
sloria/webargs | tests/apps/django_app/echo/views.py | Python | mit | 3,826 | 0.002875 | from webargs.core import json
from django.http import HttpResponse
from django.views.generic import View
import marshmallow as ma
from webargs import fields
from webargs.djangoparser import parser, use_args, use_kwargs
from webargs.core import MARSHMALLOW_VERSION_INFO
hello_args = {"name": fields.Str(missing="World",... | o(request):
try:
args = parser.parse(hello_args, request)
except ma.ValidationError as err:
return json_response(err.messages, status=parser.DEFAULT_VALIDATION_STATUS)
except json.JSONDecodeError:
return json_response({"json": [ | "Invalid JSON body."]}, status=400)
return json_response(args)
def echo_query(request):
return json_response(parser.parse(hello_args, request, locations=("query",)))
@use_args(hello_args)
def echo_use_args(request, args):
return json_response(args)
@use_kwargs(hello_args)
def echo_use_kwargs(request, ... |
sesamesushi/desatisrevu | tests/functional/review_stats.py | Python | apache-2.0 | 4,268 | 0 | # coding: utf-8
# Copyright 2013 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 ap... | d('R2for1'))
assert_contains(
'Your review has been submitted successfully', response.body)
actions.logout()
actions.login(email, is_admin=True)
response = self.get('dashboard?action=analytics')
assert_contains(
'Google > Dashboard > Analytics', res... | compute_form = response.forms['gcb-compute-student-stats']
response = self.submit(compute_form)
self.execute_all_deferred_tasks()
response = self.get('dashboard?action=analytics')
assert_contains('Peer Review Statistics', response.body)
# JSON code for the completion statist... |
chaluemwut/fbserver | venv/lib/python2.7/site-packages/sklearn/datasets/california_housing.py | Python | apache-2.0 | 3,825 | 0 | """California housing dataset.
The original database is available from StatLib
http://lib.stat.cmu.edu/
The data contains 20,640 observations on 9 variables.
This dataset contains the average house value as target variable
and the following input variables (features): average income,
housing average age, averag... | object with the following attributes:
dataset.data : ndarray, shape [20640, 8]
Each row corresponding to the 8 feature values in order.
dataset.target : numpy array of shape (20640,)
Each value corresponds to the average house value in units of 100,000.
dataset.feature_names : array of | length 8
Array of ordered feature names used in the dataset.
dataset.DESCR : string
Description of the California housing dataset.
Notes
------
This dataset consists of 20,640 samples and 9 features.
"""
data_home = get_data_home(data_home=data_home)
if not exists(data_hom... |
couchbase/couchbase-python-client | acouchbase/tests/cases/collection_t.py | Python | apache-2.0 | 16,041 | 0.002057 | import asyncio
from functools import wraps
from nose.tools import nottest
from datetime import datetime
from datetime import timedelta
from unittest import SkipTest
from flaky import flaky
from acouchbase.cluster import (Cluster, get_event_loop,
close_event_loop)
from couchbase_tests.as... | hing"})
result = await self.try_n_times_async(10, 1, self.collection.get, self.NOKEY)
self.assertEqual(self.NOKEY, result.id)
self.assertDictEqual({"some": "thing"}, result.content_as[dict])
| @async_test
async def test_insert_fail(self):
with self.assertRaises(DocumentExistsException):
await self.collection.insert(self.KEY, self.CONTENT)
@async_test
async def test_replace(self):
result = await self.collection.replace(self.KEY, {"some": "other content"})
se... |
diegoguimaraes/django | tests/fixtures_model_package/models/__init__.py | Python | bsd-3-clause | 543 | 0 | from django.db | import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Article(models.Model):
headline = models.CharField(max_length=100, default='Default headline')
pub_date = models.DateTimeField()
def __str__( | self):
return self.headline
class Meta:
app_label = 'fixtures_model_package'
ordering = ('-pub_date', 'headline')
class Book(models.Model):
name = models.CharField(max_length=100)
class Meta:
ordering = ('name',)
|
CKboss/VirtualJudgePY | dao/problemdao.py | Python | gpl-2.0 | 5,683 | 0.003167 | '''
mysql> desc problem;
+-------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+----------------+
| pid | int(11) | NO | PRI | NULL | auto_increment |
| title... | 55) | YES | | NULL | |
| source | varchar(255) | YES | | NULL | |
| updateTime | datetime | YES | | NULL | |
+--------------+--------------+ | ------+-----+---------+----------------+
'''
import pickle
import time
from tools.encode import Base64StrToUTF8Str, UTF8StrToBase64Str
from tools.dbcore import ConnPool
from tools.dbtools import getQuerySQL,getInserSQL, getUpdateSQL,FetchAll,FetchOne,ExeSQL
def GetProblemID(orj, orid):
sql = 'SELECT problem.pid F... |
Peilong/p4factory | targets/switch/run_tests.py | Python | apache-2.0 | 1,140 | 0.000877 | #!/usr/bin/env python
# Copyrigh | t 2013- | present Barefoot Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
Backflipz/plugin.video.excubed | resources/lib/more_itertools/tests/test_recipes.py | Python | gpl-2.0 | 13,333 | 0.000525 | from random import seed
from unittest import TestCase
from nose.tools import eq_, assert_raises, ok_
from more_itertools import *
def setup_module():
seed(1337)
class TakeTests(TestCase):
"""Tests for ``take()``"""
def test_simple_take(self):
"""Test basic usage"""
t = take(5, xrange(... | sure the nth item is returned"""
l = range(10)
for i, v in enumerate(l):
eq_(nth(l, i), v)
def test_default(self):
"""Ensure a default value is returned when nth item not found"""
l = range(3)
eq_(nth(l, 100, "zebra"), "zebra")
def test_negative_item_raises... | elf):
"""Ensure asking for a negative item raises an exception"""
assert_raises(ValueError, nth, range(10), -3)
class QuantifyTests(TestCase):
"""Tests for ``quantify()``"""
def test_happy_path(self):
"""Make sure True count is returned"""
q = [True, False, True]
eq_(q... |
javierpena/dlrnapi_client | dlrnapi_client/models/params.py | Python | apache-2.0 | 7,405 | 0.000135 | # coding: utf-8
"""
DLRN API
DLRN API client
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
class Params(object):
"""NOTE: This class is auto generated by the swagger code generator program... | ious_job_id
@previous_job_id.setter
def previous_job_id(self, previous_job_id):
"""Sets the previous_job_id of this Params.
If sequential_mode is set to true, look for jobs tested by the CI
identified by previous_job_id.
| :param previous_job_id: The previous_job_id of this Params.
:type: str
"""
self._previous_job_id = previous_job_id
@property
def component(self):
"""Gets the component of this Params.
additional notes
:return: The component of this Params.
:rtype:... |
assumptionsoup/pymel | pymel/util/scanf.py | Python | bsd-3-clause | 19,439 | 0.000772 | """scanf.py: scanf-style input for Python.
Danny Yoo (dyoo@hkn.eecs.berkeley.edu)
The initial motivation for this module was based on a posting on
Python-tutor:
http://mail.python.org/pipermail/tutor/2004-July/030480.html
I haven't been able to find a nice module to do scanf-style input.
Even the Library Refere... | canf() with the following caveat: unlike C's stdin(), this
version scanf() can't be interchanged with calls to other input
functions without some kind of weird side effect. We keep a
one-character buffer into stdin, so at most you | might lose one
character to the internal buffers.
fscanf() is only allowed to work on things that support both read(1)
and seek(1, -1), since then I can reliably do a ungetch-like thing.
scanf("%s") can be dangerous in a hostile environment, since it's very
possible for something to pass in a huge string without spac... |
justinhayes/cm_api | python/src/cm_api/resource.py | Python | apache-2.0 | 4,891 | 0.007769 | # Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file ex... | 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.
try:
import json
except ImportError:
import simplejson as json
import logging
import posixpath
import time
import socket
import urllib2
LOG = logging.getLogger(__name__)
class Resource(object):
"""
Encapsulates a resource, and provides actions to invoke on it.
"""
def __init__(self, ... |
BillyLiggins/MemoryLeaks | memoryTracker.py | Python | mit | 1,292 | 0.017802 | import time
import os
import numpy as np
def getPID():
os.system("qstat > qstat.temp")
qstat = open("qstat.temp","r")
qstatString = qstat.readlines()
print qstatString[0]
PID=[]
for line in qstatString:
lineSplit=line.split()
PID.append(lineSplit[0])
print PID[2:]
... | [2:]
def trackMemory(pid,memoryDatefile,timestep):
for i in pid:
memoryDatefile.write(i+"\t")
memoryDatefile.write("\n")
while True:
for id in pid:
os.system("qstat -j "+str(id)+" > temp.info")
memInfo=open("temp.info", "r")
with open('temp.info') as f:
... |
print line.split()[7][8:-1]
tempVar=line.split()[7][8:-1]
memoryDatefile.write(tempVar+"\t")
if 'str' in line:
break
memoryDatefile.write("\n")
... |
DBWangGroupUNSW/revs | revs/path.py | Python | mit | 5,412 | 0.002772 | import logging
from pymongo.errors import DocumentTooLarge
from . import Util
class PathFinder:
def __init__(self, config, pg_conn, mongo_client):
self._config = config
self._pg_conn = pg_conn
self._mongo_client = mongo_client
self._logger = logging.getLogger(self.__class__.__nam... | tity)
flag >>= 1
for i in range(path_length):
for j in range(i + 2, path_length + 1): # assume subject != object in the same triple
if i == 0 and j == path_length: # ignore source != target restriction
continue
body_fragments.append('... | y_fragments)
|
hazelnusse/alparse | alparse.py | Python | bsd-3-clause | 11,017 | 0.005083 | """Parse C output file from Autolev code dynamics().
Prints the following to stdout:
Parameters with default values
States variables listed with default initial conditions
Section to evaluate constants
Section to evaluate right hand side of state derivatives
Section to evaluate output quantit... | lassname):
raise Exception
intopts, parameters, states = infilestrings
variables, constants, odefunc, outputs = cfilestrings
filenamebase += "_al"
fp_header = open(filenamebase + ".h", "w")
fp_implementation = open(filenamebase + ".c", "w")
fp_driver = open(filenamebase + "_main.c", "w")
... | ing = ""
for v in variables:
varstring += v + ", "
varstring = varstring[:-2] + ";\n"
# Write the header file
fp_header.write(
"#ifndef " + filenamebase.upper() + "_H\n" +
"#define " + filenamebase.upper() + "_H\n\n" +
"// All variables defined as globals with file scope... |
chienlieu2017/it_management | odoo/addons/auth_ldap/models/res_users.py | Python | gpl-3.0 | 1,456 | 0.000687 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.exceptions import AccessDenied
from odoo import api, models, registry, SUPERUSER_ID
class Users(models.Model):
_inherit = "res.users"
@classmethod
def _login(cls, db, login, password):
u... | Ldap = env['res.company.ldap']
for conf in Ldap.ge | t_ldap_dicts():
entry = Ldap.authenticate(conf, login, password)
if entry:
user_id = Ldap.get_or_create_user(conf, login, entry)
if user_id:
break
return user_id
@api.model
def check_credentials(self, pa... |
anastue/netforce | netforce_ecom/netforce_ecom/controllers/ecom_products.py | Python | mit | 11,270 | 0.015439 | # Copyright (c) 2012-2015 Netforce Co. Ltd.
#
# 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, publ... | rent_id"] else None
if parent_id:
parent=categ_ids[parent_id]
parent.setdefault("sub_categories",[]).append(r)
else:
top_categs.append(r)
for categ_id | ,num in categ_nums.items():
if not categ_id:
continue
categ=categ_ids[categ_id]
categ["num_products"]=num
def _set_total_num(c):
for s in c.get("sub_categories",[]):
_set_total_num(s)
if c.get("num_products") is None:
c["num_products"]=0
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.