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 |
|---|---|---|---|---|---|---|---|---|
skarphed/skarphed | admin/src/skarphedadmin/gui/skarphed/Role.py | Python | agpl-3.0 | 4,713 | 0.01719 | #!/usr/bin/python
#-*- coding: utf-8 -*-
###########################################################
# © 2011 Daniel 'grindhold' Brendle and Team
#
# This file is part of Skarphed.
#
# Skarphed is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License
# as ... | mlistview.append_column(self.perm_permlist_col_name)
self.perm_permlist_renderer_checkbox= gtk.CellRendererToggle()
self.perm_permlist_renderer_identifier = gtk.CellRendererText()
self.perm_permlist_renderer_name = gtk.CellRendererText()
self.perm_permlist_col_checkbox.pack_star... | ifier)
self.perm_permlist_col_name.pack_start(self.perm_permlist_renderer_name)
self.perm_permlist_col_checkbox.add_attribute(self.perm_permlist_renderer_checkbox,'active',0)
self.perm_permlist_col_identifier.add_attribute(self.perm_permlist_renderer_identifier,'text',1)
self.perm_permli... |
pcu4dros/pandora-core | workspace/lib/python3.5/site-packages/sqlalchemy/testing/suite/test_types.py | Python | mit | 24,316 | 0.000082 | # coding: utf-8
from .. import fixtures, config
from ..assertions import eq_
from ..config import requirements
from sqlalchemy import Integer, Unicode, UnicodeText, select
from sqlalchemy import Date, DateTime, Time, MetaData, String, \
Text, Numeric, Float, literal, Boolean, cast, null, JSON, and_
from ..schema i... | tadata,
Column('id', Integer, primary_key=True,
test_needs_autoincrement=True),
Column('unicode_data', cls.datatype),
)
def test_round_trip(self):
unicode_table = self.tables.unicode_table
config.db.execu | te(
unicode_table.insert(),
{
'unicode_data': self.data,
}
)
row = config.db.execute(
select([
unicode_table.c.unicode_data,
])
).first()
eq_(
row,
(self.data, )
... |
amboutin/GCP | monitoring/api/v3/api-client/list_resources_test.py | Python | apache-2.0 | 2,187 | 0 | #!/usr/bin/env python
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# di... | a Service Account for a project
that has enabled the Monitoring API.
Currently the TEST_PROJECT_ID is hard-coded to run using the project created
for this test, but it could be changed to a different project.
"""
import os
import re
from gcp.testing.flaky import flaky
import googleapiclient.discovery
import pytest
... | dule')
def client():
return googleapiclient.discovery.build('monitoring', 'v3')
@flaky
def test_list_monitored_resources(client, capsys):
PROJECT_RESOURCE = "projects/{}".format(PROJECT)
list_resources.list_monitored_resource_descriptors(
client, PROJECT_RESOURCE)
stdout, _ = capsys.readouterr... |
msbeta/apollo | modules/tools/ota/update_client.py | Python | apache-2.0 | 2,270 | 0 | #!/usr/bin/env python
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complian | ce 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 impl... | ############################################################
import requests
import os
import sys
import urllib3
from ConfigParser import ConfigParser
from modules.data.proto.static_info_pb2 import VehicleInfo
import common.proto_utils as proto_utils
def update():
# setup server url
config = ConfigParser()
... |
t1g0r/ramey | src/backend/command/CommandHandler.py | Python | gpl-3.0 | 1,966 | 0.037131 | import sys,os
from pymongo import MongoClient
import importlib
import SwitchHandler
import CameraHandler
import SensorHandler
from pprint import pprint
class CommandHandler(object):
"""docstring for CommandHandler"""
def __init__(self, dbconn, command):
super(CommandHandler, self).__init__()
self.dbconn = dbcon... | cCommand = self.dbconn.commandmapper.find({"commandkey":commandstr}).limit(1)
print "get db selesai"
#if commmand is not fou | nd, then send response
if cCommand.count() > 0:
cCommand = cCommand[0]
self.callback(self.command["account_id"],"hii %s, you just sent command name : '%s' and this is callback!" % (self.command["fullname"],cCommand["commandname"]))
try:
#execute command
#get package
self.modules = cCommand["clas... |
maliciamrg/s3cmd | S3/ConnMan.py | Python | gpl-2.0 | 6,833 | 0.00439 | # -*- coding: utf-8 -*-
## Amazon S3 manager
## Author: Michal Ludvig <michal@logix.cz>
## http://www.logix.cz/michal
## License: GPL Version 2
## Copyright: TGRMN Software and contributors
import sys
import httplib
import ssl
from threading import Semaphore
from logging import debug
from Config import Confi... | e
conn = httplib.HTTPSConnection(hostname, port, context=context)
except TypeError:
conn = httplib.HTTPSConnection(hostname, port)
return conn
def __init__(self, id, hostname, ssl, cfg):
self.ssl = ssl
self.id = id
self.counter = 0
if not ssl... | host != "":
self.c = httplib.HTTPConnection(cfg.proxy_host, cfg.proxy_port)
debug(u'proxied HTTPConnection(%s, %s)' % (cfg.proxy_host, cfg.proxy_port))
else:
self.c = httplib.HTTPConnection(hostname)
debug(u'non-proxied HTTPConnection(%s)' % ho... |
Azure/azure-sdk-for-python | sdk/servicebus/azure-servicebus/tests/perf_tests/T1_legacy_tests/receive_message_batch.py | Python | mit | 1,104 | 0.002717 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | ceiveTest):
def run_sync(self):
count = 0
while count < self.args.num_messages:
batch = self.receiver.fetch_next(max_batch_size=self.args.num_messages - count)
if self.args.peeklock:
for msg in batch:
msg.complete()
count += len... | async def run_async(self):
count = 0
while count < self.args.num_messages:
batch = await self.async_receiver.fetch_next(max_batch_size=self.args.num_messages - count)
if self.args.peeklock:
await asyncio.gather(*[m.complete() for m in batch])
count += ... |
tzaffi/boto3play | encodeAndS3sync.py | Python | mit | 2,841 | 0.036607 | import json
import os
import ntpath
import datetime as dt
import pprint
import boto3
def get_config():
'''
Load the configuration from ./config.json
'''
with open('config.json', 'r') as config_file:
return json.load(config_file)
def get_new_files(config, max_ | age_in_hours=24):
'''
Get array | of all files younger than max_age_in_hours,
unless max_age_in_hours is set to 0 - in which case all files
are provided.
Note, directories and files with the wrong extension type are ignored.
'''
now = dt.datetime.now()
content_dir = config['content']
ext = config['content_ext']
if max_age_in_hours <= 0:
cuto... |
CINPLA/expipe-dev | py-open-ephys/pyopenephys/core.py | Python | gpl-3.0 | 38,806 | 0.003298 | """
Python library for reading OpenEphys files.
Depends on: sys
os
glob
datetime
numpy
quantities
xmljson
xmltodict
Authors: Alessio Buccino @CINPLA,
Svenn-Arne Dragly @CINPLA,
Milad H. Mobarhan @CINPLA,
Mikk... | ef __init__(self, channel_group_id, filename, channels,
fileclass=None, **attrs):
self.attrs = attrs
self.filename = filename
self.id = channel_group_id
self.channel | s = channels
self.fileclass = fileclass
def __str__(self):
return "<OpenEphys channel_group {}: channel_count: {}>".format(
self.id, len(self.channels)
)
@property
def analog_signals(self):
ana = self.fileclass.analog_signals[0]
analog_signals = []
... |
MoroGasper/client | client/javascript.py | Python | gpl-3.0 | 1,277 | 0.003132 | #!/usr/bin/env python
# encoding: utf-8
"""Copyright (C) 2013 COLDWELL AG
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This... | enses/>.
"""
import json
try:
from pyv8 import PyV8
except ImportError:
import PyV8
pyv8 = PyV8
def execute(code):
if isinstance(code, unicode):
code = code.encode("utf-8")
with PyV8.JSContext() as c:
c.enter()
return c.eval(code)
def _c | onvert(data):
result = {}
for key in data.keys():
if isinstance(data[key], PyV8.JSObject):
result[key] = _convert(data[key])
else:
result[key] = data[key]
return result
def loads(data):
s = execute("JSON.stringify({})".format(data))
return json.loads(s)
|
rohitranjan1991/home-assistant | homeassistant/components/netgear_lte/notify.py | Python | mit | 1,330 | 0.001504 | """Support for Netgear LTE notifications."""
import logging
import attr
import eternalegypt
|
from homeassistant.components.notify | import ATTR_TARGET, BaseNotificationService
from . import CONF_NOTIFY, CONF_RECIPIENT, DATA_KEY
_LOGGER = logging.getLogger(__name__)
async def async_get_service(hass, config, discovery_info=None):
"""Get the notification service."""
if discovery_info is None:
return
return NetgearNotifyService... |
jobiols/management-system | mgmtsystem_hazard/models/mgmtsystem_hazard_origin.py | Python | agpl-3.0 | 1,280 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>).
#
# | This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it | will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. I... |
tortugueta/OET | patrons.py | Python | gpl-2.0 | 22,144 | 0.033689 | #! /usr/bin/python
# FIXME: for some reason the wheel does not appear centered
# FIXME: when I change some property in the shapes tab, the shape repositions
# itself
# The two previous FIXMES are related to the absolutely retarded way in which
# the Qt view looks | at the Qt Scene. I still have to figure out how to
# properly handle it.
# FIXME: The scene creation, animations and stuff, should probably be coded in
# the GraphicsWindow class, not in the MainWindow
# FIXME: When I create the corners in tab2 and also when I resize them, I need
# to add some weird offset to make the... | XME: When stopping, lowering the rps, and starting again, sometimes you
# get a first rapid short rotation. That is because the initial angle is set
# to the end angle of the previous unit rotation. This is not trivial to
# solve because when I stop an animation mid-play, I don't know how to fetch
# the current angle o... |
Davidjohnwilson/sympy | sympy/liealgebras/type_b.py | Python | bsd-3-clause | 4,651 | 0.001935 | from __future__ import print_function, division
from .cartan_type import Standard_Cartan
from sympy.core.compatibility import range
from sympy.matrices import eye
class TypeB(Standard_Cartan):
def __new__(cls, n):
if n < 2:
raise ValueError("n can not be less than 2")
return Standard_... | , n-1):
for j in range(i+1, n):
k += 1
posroots[k] = self.basic_root(i, j)
k += 1
| root = self.basic_root(i, j)
root[j] = 1
posroots[k] = root
for i in range(0, n):
k += 1
root = [0]*n
root[i] = 1
posroots[k] = root
return posroots
def roots(self):
"""
Returns the total number of root... |
matteobertozzi/RaleighSL | src/raleigh-client/pyraleigh/sql/expr.py | Python | apache-2.0 | 14,678 | 0.014852 | #!/usr/bin/env python
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | f.left, self.right)
def is_constant(self, context):
return self.left.is_constant(context) and self.right.is_constant(context)
def resolve(self, context):
self.left = self.left.resolve(context)
self.right = self.right.resolve(context)
if self.is_constant(context):
result = self.evaluate(conte... | return RqlNumber(result)
if isinstance(result, bool):
return RqlBoolean(result)
raise RqlSyntaxError("Unexpected type %s %r" % (type(result), result))
return self
def evaluate(self, context):
left = self.left.evaluate(context)
right = self.right.evaluate(context)
# Expressi... |
antoinecarme/pyaf | tests/artificial/transf_Anscombe/trend_Lag1Trend/cycle_12/ar_/test_artificial_32_Anscombe_Lag1Trend_12__20.py | Python | bsd-3-clause | 263 | 0.087452 | import pya | f.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 12, transform = "Anscombe", sigma = 0.0, e | xog_count = 20, ar_order = 0); |
jcfr/mystic | setup.py | Python | bsd-3-clause | 12,858 | 0.002178 | #!/usr/bin/env python
#
# Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
# Copyright (c) 1997-2015 California Institute of Technology.
# License: 3-clause BSD. The full license text is available at:
# - http://trac.mystic.cacr.caltech.edu/project/mystic/browser/mystic/LICENSE
from __future__ import with_... | or more
information, see `mystic.mystic.forward_model`.
All mystic solvers are highly configurable, and provide a robust set of
methods to help customize the solver for your particular optimization
problem. For each solver, a minimal interface is also provided for users
who prefer to configure their solvers in a singl... | nction call. For more
information, see `mystic.mystic.abstract_solver` for the solver API, and
each of the individual solvers for their minimal (non-API compliant)
interface.
Mystic extends the solver API to parallel computing by providing a solver
class that utilizes the parallel map-reduce algorithm. Mystic includes... |
ramineni/myironic | ironic/tests/drivers/test_ipminative.py | Python | apache-2.0 | 20,240 | 0.000296 | # coding=utf-8
# Copyright 2013 International Business Machines Corporation
# 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/... | express or implied. See the
# License for the specific language | governing permissions and limitations
# under the License.
"""
Test class for Native IPMI power driver module.
"""
import mock
from oslo_config import cfg
from pyghmi import exceptions as pyghmi_exception
from ironic.common import boot_devices
from ironic.common import driver_factory
from ironic.common import exc... |
yostashiro/awo-custom | purchase_line_split/__openerp__.py | Python | lgpl-3.0 | 1,484 | 0.001348 | # -*- coding: utf-8 -*-
# Odoo, Open Source Management Solution
# Copyright (C) 2016 Rooms For (Hong Kong) Limited T/A OSCG
# <https://www.odoo-asia.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# publishe... | d have received a copy of the GNU Affero Gener | al Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
{
'name': 'Purchase Line Split',
'summary':"""""",
'version': '8.0.0.5.0',
'category': 'Purchases',
'author': 'Rooms For (Hong Kong) Limited T/A OSCG',
'website': 'https://www.odoo-asia.com',
'licen... |
space-age-robotics/gerbmerge-patched | gerbmerge/config.py | Python | gpl-3.0 | 14,779 | 0.017119 | #!/usr/bin/env python
"""
Parse the GerbMerge configuration file.
--------------------------------------------------------------------
This program is licensed under the GNU General Public License (GPL)
Version 3. See http://www.fsf.org for details of the license.
Rugged Circuits LLC
http://ruggedcircuits.com/gerbm... | oplayer, *bottomlayer
'scoringfile': None, # Name of file to which to write scoring data, or None
'leftmargin': 0, | # Inches of extra room to leave on left side of panel for tooling
'topmargin': 0, # Inches of extra room to leave on top side of panel for tooling
'rightmargin': 0, # Inches of extra room to leave on right side of panel for tooling
'bottommargin': 0, ... |
michaelpacer/scikit-image | skimage/filters/rank/generic.py | Python | bsd-3-clause | 31,373 | 0 | """The local histogram is computed using a sliding window similar to the method
described in [1]_.
Input image can be 8-bit or 16-bit, for 16-bit input images, the number of
histogram bins is determined from the maximum value present in the image.
Result image is 8-/16-bit or double with respect to the input image an... | If None, a new array is allocated.
mask : 2-D array
Mask array that defines (>0) area of the image included in the local
neighborhood. If None, the complete image is used (default).
shift_x, shift_y : int
Offset added to the structuring element center point. Shift is bounded
... | structuring element).
Returns
-------
out : 2-D array (same dtype as input image)
Output image.
Examples
--------
>>> from skimage import data
>>> from skimage.morphology import disk
>>> from skimage.filters.rank import bottomhat
>>> img = data.camera()
>>> out ... |
camradal/ansible | lib/ansible/modules/windows/win_file.py | Python | gpl-3.0 | 2,738 | 0.002191 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Jon Hawkesworth (@jhawkesworth) <figs@unity.demon.co.uk>
#
# This file is part of Ansible
#
# Ansible 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, eith... | e',
'version': '1.0'}
DOCUMENTATION = r'''
---
module: win_file
version_added: "1.9.2"
short_description: Creates, touches or removes files or directories.
description:
- Creates (empty) files, updates file modification stamps of existing files,
and can create or remove directories.
... | M(win_template), M(copy), M(template), M(assemble)
requirements: [ ]
author: "Jon Hawkesworth (@jhawkesworth)"
options:
path:
description:
- 'path to the file being managed. Aliases: I(dest), I(name)'
required: true
aliases: ['dest', 'name']
state:
description:
- If C(directory), all i... |
Huyuwei/tvm | nnvm/tests/python/compiler/test_to_relay.py | Python | apache-2.0 | 2,176 | 0.001379 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | pache.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 License for the
# specific language governing permissions and l... | nnvm
from nnvm import testing
from nnvm import to_relay
import tvm
from tvm.relay import transform
from tvm.relay import create_executor
from tvm.contrib import graph_runtime
import numpy as np
def check_model(sym, shapes, dtypes, params):
net = nnvm.graph.create(sym)
graph_json, mod, params = nnvm.compiler.bu... |
MikeDMorgan/gwas_pipeline | scripts/pheno2plot.py | Python | mit | 7,293 | 0.000686 | '''
pheno2plot.py - format and manipulate phenotype files
====================================================
:Author:
:Release: $Id$
:Date: |today|
:Tags: Python
Purpose
-------
.. Generate plots of phenotype data
Usage
-----
.. Example use case
Example::
python pheno2plot.py
Type::
python pheno2plot.p... | pe="string",
help="Plink .fam file containing file IDs")
parser.add_option("--xvar-labels", dest="xvar_labs", type="string",
help="a comma-separated list of variable X labels"
"only applies when X is a discrete or categorical "
... | "string",
help="a comma-separated list of grouping variable "
"labels. Can only apply when the grouping variable "
"is discrete or categorical. The labels must be "
"input in the order of the data")
parser.add_option("--yvar-... |
ebukoz/thrive | erpnext/controllers/taxes_and_totals.py | Python | gpl-3.0 | 28,062 | 0.023698 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import json
import frappe, erpnext
from frappe import _, scrub
from frappe.utils import cint, flt, round_based_on_smallest_currency_fraction
from erpnex... | se currency"""
for f in fields:
val = flt(flt(doc.get(f), doc.precision(f)) * self.doc.conversion_rate, doc.precision("base_" + f))
doc.set("base_" + f, val)
def initialize_taxes(self):
for tax in self.doc.get("taxes"):
if not self.discount_amo | unt_applied:
validate_taxes_and_charges(tax)
validate_inclusive_tax(tax, self.doc)
tax.item_wise_tax_detail = {}
tax_fields = ["total", "tax_amount_after_discount_amount",
"tax_amount_for_current_item", "grand_total_for_current_item",
"tax_fraction_for_current_item", "grand_total_fraction_for_cur... |
TaxIPP-Life/til-france | til_france/pgm/output/stat_final.py | Python | gpl-3.0 | 737 | 0.001357 | import pdb
from pandas import HDFStore
import pandas.rpy.common as com
from rpy2.robjects import r
__version__ = "0.0"
def stat(year):
print("Calcul des statistiques individuelles")
simul = "C:/til/output/simul.h5"
simul = HDFStore(simul)
| df = simul['entities/register']
df = df.loc[df['period'] == year]
# export en R
not_bool = df.dtypes[df.dtypes != bool]
df = df.ix[:, not_bool.index]
r_dataframe = com.convert_to_r_dataframe(df)
name = 'result_sim'
r.assign(name, r_dataframe)
| file_dir = "C:/Myliam2/output/" + name + ".gzip"
phrase = "save(" + name + ", file='" + file_dir + "', compress=TRUE)"
r(phrase)
simul.close()
if __name__ == "__main__":
stat(2011)
|
eduNEXT/edunext-platform | lms/djangoapps/discussion/notification_prefs/tests.py | Python | agpl-3.0 | 9,839 | 0.001321 | # pylint: disable=consider-iterating-dictionary, missing-module-docstring
import json
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.test import TestCase
from django.test.client import RequestFactory
from django.test.... | ode == 204
self.assertNotPrefExists(self.user)
def test_ajax_disable_already_disabled(self):
request = self.request_factory.post("dummy")
request.user = self.user
response = ajax_disable(request)
assert response.status_code == 204
self.assertNotPrefExists(self.user)
... | cribe_post(self):
request = self.request_factory.post("dummy")
response = set_subscription(request, "dummy", subscribe=False)
assert response.status_code == 405
def test_unsubscribe_invalid_token(self):
def test_invalid_token(token, message):
request = self.request_facto... |
bkahlert/seqan-research | raw/workshop12/workshop2012-data-20120906/trunk/core/apps/razers2/tests/run_tests.py | Python | mit | 12,683 | 0.004179 | #!/usr/bin/env python
"""Execute the tests for the razers2 program.
The golden test outputs are generated by the script generate_outputs.sh.
You have to | give the root paths to the source and the binaries as arguments to
the program. These are the paths to the directory that contains the 'projects'
directory.
Usage: run_tests.py SOURCE_ROOT_PATH BINARY_ROOT_PATH
"""
import logging
import os.path
import sys
# Automagically add util/py_lib to PYTHONPATH environment va... | .path.dirname(__file__), '..', '..',
'..', '..', 'util', 'py_lib'))
sys.path.insert(0, path)
import seqan.app_tests as app_tests
def main(source_base, binary_base):
"""Main entry point of the script."""
print 'Executing test for razers2'
print '========================... |
AlexBenyuh/python_training | fixture/application.py | Python | apache-2.0 | 897 | 0.003344 | from selenium.webdriver.chrome.webdriver import WebDriver
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from fixture.session import SessionHelper
from fixture.mk import M... | wd = self.wd
wd.get("https://new.kyivstar.ua/ecare/")
wd.maximize_window()
def destroy(self):
self.wd.quit()
def is_valid(self):
try:
self.wd.current_url
return True
except:
return | False
|
csparpa/pyowm | tests/unit/airpollutionapi30/test_airpollution_manager.py | Python | mit | 15,769 | 0.005454 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import unittest
from pyowm.airpollutionapi30 import airpollution_client, airpollution_manager, coindex, so2index, ozone, no2index, airstatus
from pyowm.config import DEFAULT_CONFIG
from pyowm.constants import AIRPOLLUTION_API_VERSION
from pyowm.utils import tim... | )
self.assertIsNotNone(result.du_value)
ref_to_original = airpollution_client.AirPollutionHttpClient.get_o3
| airpollution_client.AirPollutionHttpClient.get_o3 = \
self.mock_get_o3_returning_ozone_around_coords
result = self.__test_instance.ozone_around_coords(45, 9, interval=None)
airpollution_client.AirPollutionHttpClient.o3 = ref_to_original
self.assertTrue(isinstance(result, ozon... |
LynnHo/DCGAN-LSGAN-WGAN-WGAN-GP-Tensorflow | make_gif.py | Python | mit | 1,392 | 0.001437 | import imageio
import pylib as py
# ==============================================================================
# = param =
# ==============================================================================
py.arg('--save_path', default='pics/cele... | // args.max_frames
else:
step = 1
last = - | 1
for i, filename in enumerate(filenames[::step]):
frame = 2 * (i**0.3)
if round(frame) > round(last):
last = frame
else:
continue
image = imageio.imread(filename)
writer.append_data(image)
image = imageio.imread(filename)
writer.append_data(im... |
syed/PerfKitBenchmarker | tests/aws_disk_integration_test.py | Python | apache-2.0 | 2,943 | 0.001699 | # Copyright 2015 PerfKitBenchmarker 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 appli... | }
},
'disk_spec': {
'AWS': {
'disk_type': 'standard',
'disk_size': 2,
'mount_point': MOUNT_POINT
}
}
}
}
}, MOUNT_POINT)
... | 'vm_group_1': {
'cloud': 'AWS',
'vm_spec': {
'AWS': {
'machine_type': 'm4.large',
'zone': 'us-east-1a'
}
},
'disk_spec': {
'AWS': {
... |
jesterKing/naali | tools/tests/avatar-test.py | Python | apache-2.0 | 4,768 | 0.013842 | #!/usr/local/bin/python
##
# TODO:
#
##
#import
import os
import time
import shutil
import subprocess
import getpass
import glob
import autoreport
from multiprocessing import Process
from optparse import OptionParser
import config
#variables
numberOfRuns = 2
numberOfClients = 2
testName = "avatar-test"
#folder co... | l server (default if no parameter is given)
#js = scriptDir + "/" + "autoConnect.js"
js = scriptDir + "/" + "autoConnectLocal.js"
def main():
operations(numberOfRuns)
movePc | apFiles()
cleanup()
autoreport.autoreport(testName)
os._exit(1)
def operations(numberOfRuns):
global avatarLogs
global timeStamp
#create a temp directory for pcap files
if not os.path.exists(wiresTempDir):
os.makedirs(wiresTempDir)
#create a directory for log files
timeSta... |
Nic30/hwtLib | hwtLib/amba/axiLite_comp/to_axi.py | Python | mit | 2,749 | 0.001455 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import Optional
from hwt.serializer.mode import serializeParamsUniq
from hwt.synthesizer.interface import Interface
from hwt.synthesizer.param import Param
from hwtLib.abstract.busBridge import BusBridge
from hwtLib.amba.axi4 import Axi4, Axi4_addr
from hwtLi... | missing_on_b.append(a)
return set(missing_on_b)
@serializeParamsUniq
class AxiLite_to_Axi(BusBridge):
"""
Bridge from AxiLite interface t | o Axi3/4 interface
.. hwt-autodoc::
"""
def __init__(self, intfCls=Axi4, hdl_name_override:Optional[str]=None):
self.intfCls = intfCls
super(AxiLite_to_Axi, self).__init__(hdl_name_override=hdl_name_override)
def _config(self):
self.INTF_CLS = Param(self.intfCls)
self.... |
jeroyang/newsletter | newsletter/__init__.py | Python | bsd-3-clause | 394 | 0 | #!/usr/bin/env python
# -*- | coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
import versioneer
__author__ = 'Chia-Jung, Yang' |
__email__ = 'jeroyang@gmail.com'
__version__ = versioneer.get_version()
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
|
IgnitedAndExploded/pyfire | pyfire/auth/backends.py | Python | bsd-3-clause | 1,345 | 0 | # -*- coding: utf-8 -*-
"""
pyfire.auth.backends
~~~~~~~~~~~~~~~~~~~~
Credential validation backends
:copyright: 2011 by the pyfire Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import warnings
class | InvalidAuthenticationError(Exception):
"""Raised upon fail in auth"""
pass
class CredentialValidator(object):
"""Base class to handle credential validation"""
def shutdown(self):
"""Shuts down needed connections and handles"""
pass
def validate_userpass(self, username, password)... | CredentialValidator):
"""Always returns true"""
def __init__(self):
warnings.warn("Do not use the DummyTrue validator in production",
RuntimeWarning)
super(DummyTrueValidator, self).__init__()
def validate_userpass(self, username, password):
return True
d... |
sweco-sepesd/gmlz | python/crc32_combine.py | Python | mit | 980 | 0.041837 | '''
https:// | github.com/toomuchio/pycrc32combine
'''
def gf2_matrix_square(square, mat):
for n in range(0, 32):
if (len(square) < (n + 1)):
square.append(gf2_matrix_times(mat, mat[n]))
else:
square[n] = gf2_matrix_times( | mat, mat[n])
return square
def gf2_matrix_times(mat, vec):
sum = 0
i = 0
while vec:
if (vec & 1):
sum = sum ^ mat[i]
vec = (vec >> 1) & 0x7FFFFFFF
i = i + 1
return sum
def crc32_combine(crc1, crc2, len2):
even = []
odd = []
if (len2 == 0):
return crc1
odd.append(0xEDB88320L)
row = 1
for n in r... |
enthought/etsproxy | enthought/developer/tools/vet/class_browser.py | Python | bsd-3-clause | 114 | 0 | # proxy module
from __future__ import absolute_impor | t
from etsdevtools.developer.too | ls.vet.class_browser import *
|
pcmagic/stokes_flow | sphere/sphere_rs.py | Python | mit | 20,947 | 0.001337 | # coding=utf-8
# main codes, call functions at stokes_flow.py
# Zhang Ji, 20160410
import sys
import petsc4py
petsc4py.init(sys.argv)
# import warnings
# from memory_profiler import profile
import numpy as np
from src import stokes_flow as sf
# import stokes_flow as sf
from src.stokes_flow import problem_dic, obj_dic... | ref_solution import *
# @profile
def view_matrix(m, **kwargs):
args = {
'vmin': None,
'vmax': None,
'title': ' ',
'cmap': None
}
for key, value in args.items():
if key in kwargs:
args[key] = kwargs[key]
import matplotlib.pyplot as plt
fig, ax... | cmap=plt.get_cmap(args['cmap']))
fig.colorbar(cax)
plt.title(args['title'])
plt.show()
def save_vtk(problem: sf.StokesFlowProblem):
t0 = time()
ref_slt = sphere_slt(problem)
comm = PETSc.COMM_WORLD.tompi4py()
rank = comm.Get_rank()
problem_kwargs = problem.get_kwar... |
rzanluchi/keyard | tests/app/test_app.py | Python | mit | 6,392 | 0.000156 | # -*- coding: utf-8 -*-
import falcon
import falcon.testing
import json
import mock
from keyard.app import resource
from keyard.app.utils import prepare_app
from keyard.app.middlewares import requireJSON
class TestKeyardResource(falcon.testing.TestBase):
def before(self):
self.resource = resource.Keyard... | .0', None)
def test_delete(self):
self.resource.api.unregister | .return_value = True
self.simulate_request(
'keyard', method="DELETE",
body=json.dumps({'service_name': 'web', 'version': '1.0',
'location': 'localhost:8888'}))
self.assertEqual(self.srmock.status, falcon.HTTP_200)
self.resource.api.unregiste... |
briandailey/django-pyres | django_pyres/__init__.py | Python | bsd-3-clause | 63 | 0.015873 | VERSION = (0, 1, 5)
__version__ = '.'.jo | in(map(str, VE | RSION))
|
HybridF5/jacket | jacket/db/storage/sqlalchemy/migrate_repo/versions/022_add_reason_column_to_service.py | Python | apache-2.0 | 890 | 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 t... | r the specific language governing permissions and limitations
# under the License.
from sqlalchemy import Column, MetaData, String, Table
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
services = Table('storage_services', meta, a | utoload=True)
reason = Column('disabled_reason', String(255))
services.create_column(reason)
|
guorendong/iridium-browser-ubuntu | third_party/webgl/src/sdk/tests/deqp/genHTMLfromTest.py | Python | bsd-3-clause | 1,016 | 0.04626 | import os
import re
# Generate an HTML file for each .test file in the current directory
#
TEST_LIST_FILE = '00_test_list.txt';
TEMPLATE = 'template.html';
def genHTML(template, test):
contents = re.sub('___TEST_NAME___', "'" + test + "'", template);
filename = test + '.html';
print "Generating " + filename;
wit... | ') as f:
for item in test_list:
f.write(item + '\n');
else:
print "Couldn't find template file: | " + TEMPLATE;
|
rec/DMXIS | Macros/Shapes/Adjust Shape/Phase +.py | Python | artistic-2.0 | 463 | 0.021598 | #===============================================================
# DMXIS Macro (c) 2010 db audioware limited
#===================== | ==========================================
sel = GetAllSelCh(False)
if len(sel)==0:
Message("Select some Pan/Tilt channels first!")
for ch in se | l:
nm = GetChName(ch).lower()
if nm=="pan" or nm=="tilt":
v = GetOscChase(ch);
v += 0.05
if v>1.0: v = v-1.0
SetOscChase(ch, v) |
ddasilva/numpy | tools/swig/test/testFarray.py | Python | bsd-3-clause | 5,156 | 0.002521 | #! /usr/bin/env python
from __future__ import division, absolute_import, print_function
# System imports
from distutils.util import get_platform
import os
import sys
import unittest
# Import NumPy
import numpy as np
major, minor = [ int(d) for d in np.__version__.split(".")[:2] ]
if major == 0: BadListError = TypeE... | ange(m):
for j in range(n):
self.failUnless(self.array[i, j] == i*j)
def testSetBad1(self):
"Test Farray __setitem__ method, negative row"
self.assertRaises(IndexError, self.array.__setitem__, (-1, 3), 0)
def testSetBad2(self):
"Test Farray __setitem__ metho... | item__, (1, -3), 0)
def testSetBad3(self):
"Test Farray __setitem__ method, out-of-range row"
self.assertRaises(IndexError, self.array.__setitem__, (self.nrows+1, 0), 0)
def testSetBad4(self):
"Test Farray __setitem__ method, out-of-range col"
self.assertRaises(IndexError, self... |
aristanetworks/EosSdk | examples/SimpleIntfAgent.py | Python | bsd-3-clause | 2,154 | 0.020891 | #!/usr/bin/env python
# Copyright (c) 2014 Arista Networks, Inc. All rights reserved.
# Arista Networks, Inc. Confidential and Proprietary.
import eossdk
import sys
# Listens to standard input and shuts down an interface when it
# receives a "shutdown" message. To exit, enter a blank line.
class MyTestAgent(eossdk... | n_enabled(self.intfObj_)
else "disabled")
print "- %s is currently %s" % (self.intfObj_.to_string(), curEnabledStatus)
msg = sys.stdin.readline()
if msg.startswith("shut"):
print "Shutting down %s" % self.intfObj_. | to_string()
self.intfMgr_.admin_enabled_is(self.intfObj_, False)
self.eventCount += 1
elif msg.strip():
print "Enabling %s" % self.intfObj_.to_string()
self.intfMgr_.admin_enabled_is(self.intfObj_, True)
self.eventCount += 1
else:
print "Exiting!"
... |
pytroll/pytroll-file-utils | trollmoves/heartbeat_monitor.py | Python | lgpl-3.0 | 3,623 | 0.001933 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2017
#
# Author(s):
#
# Lars Ørum Rasmussen <ras@dmi.dk>
# Janne Kotro <janne.kotro@fmi.fi>
#
# 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... | n time interval `heartbeat_alarm_scale` times
heartbeat time interval.
"""
self._alarm_scale = float(kwargs.get("heartbeat_alarm_scale", 0))
self._alarm_event = alarm_event
self._interval = self._alarm_scale * DEFAULT_MIN_INTERVAL
self._finished = threading.Event()
... |
TODO: If possibility for blocking, add a queue.
"""
if self._alarm_scale:
if msg and msg.type == "beat":
try:
self._interval = self._alarm_scale * float(msg.data["min_interval"])
except (KeyError, AttributeError, TypeError, ValueE... |
matousc89/padasip | padasip/preprocess/__init__.py | Python | mit | 380 | 0 | """
In this module are placed functions related to preprocessing of data.
"""
from pa | dasip.preprocess.standardize import standardize
from padasip.preprocess.standardize_back import standardize_back
from padasip | .preprocess.input_from_history import input_from_history
from padasip.preprocess.pca import PCA, PCA_components
from padasip.preprocess.lda import LDA, LDA_discriminants
|
oscar9/statistics_viewer | processmanager/processdirectory/stat1.py | Python | gpl-3.0 | 3,078 | 0.015595 | # encoding: utf-8
import gvsig
from gvsig import getResource
import addons.statistics_viewer.statisticprocess
reload(addons.statistics_viewer.statisticprocess)
from addons.statistics_viewer.statisticprocess.abstractprocess import AbstractStatisticProcess
import os
from addons.statistics_viewer.sv import svgraph
fro... | ynclass = manager.get("Pro | cess","ProcessProperties")
#if dynclass == None:
#dynclass = manager.createDynClass("Process", "ProcessProperties", "aqui va la descripcion")
params = self.createInputParameters("Process", "ProcessProperties", "Description")
#dynclass.addDynFieldString("name").setMandatory(False)
... |
Peter-Collins/NormalForm | src/py/TaylorTest.py | Python | gpl-2.0 | 4,842 | 0.005163 | # This software is Copyright (C) 2004-2008 Bristol University
# and is released under the GNU General Public License version 2.
import unittest
from Powers import Powers
from Polynomial import Polynomial
import Taylor
class Sine(unittest.TestCase):
def test_terms(self):
s = Taylor.Sine(1, 0)
se... | Powers((3, 0)): -1.0/6.0}), r[3])
self.assert_(r[4] == Polynomial(2, terms={Powers((0, 4)): +1.0/24.0}), r[4])
self.assert_(r[5] == Polynomial(2, terms={Powers((5, 0)): +1.0/120.0}), r[5])
class Product(unittest.TestCase):
def test_sine_times_cosine(self):
s = Taylor.Cached(Taylor.Sine(2, ... | elf.assert_(r[1] == Polynomial(2, terms={Powers((1, 0)): +1.0}), r[1])
def test_sine_times_sine(self):
s = Taylor.Cached(Taylor.Sine(2, 0))
r = s*s
self.assert_(not r[0])
self.assert_(not r[1])
self.assert_(r[2] == Polynomial(2, terms={Powers((2, 0)): +1.0}))
self.as... |
antoinecarme/pyaf | tests/artificial/transf_Integration/trend_ConstantTrend/cycle_5/ar_12/test_artificial_1024_Integration_ConstantTrend_5_12_20.py | Python | bsd-3-clause | 272 | 0.084559 | import | pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "ConstantTrend", cycle_length = 5, transform = "Integration", sigma = 0.0, exog_count = 20, ar_order = 12 | ); |
yihuang/storymaker | story/models.py | Python | gpl-3.0 | 837 | 0 | from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class Story(models.Model):
title = models.CharField(max_length=256)
created_by = models.ForeignKey(User)
root = models.ForeignKey('StoryNode', related_name='+', null=True)
def get_abs... | l(self):
return reverse('story:story', kwargs={'id': self.id})
class StoryNode(models.Model):
title = models.CharField(max_length=256)
content = models.TextField()
parent = models.ForeignKey('StoryNode', null=True)
story = mo | dels.ForeignKey(Story)
stars = models.IntegerField(default=0)
created_by = models.ForeignKey(User)
created_at = models.DateTimeField(auto_now_add=True)
def get_absolute_url(self):
return reverse('story:node', kwargs={'id': self.id})
|
pichuang/OpenNet | mininet-patch/examples/cluster/gre.py | Python | gpl-2.0 | 2,041 | 0.006859 | #!/usr/bin/python
"""
gre.py
mininet1 mininet2
-------- --------
| | | |
| s1=========s2 |
| | | | | |
| h1 | | h2 |
| | | |
-------- --------
=== : cross-link
| : link
Testing enviroment (cat /etc/hosts) :
192.168.59.100 mininet1
192.168.59.101 mininet2
"""
# from min... | art()
# Cross-link between mininet1 and mininet2
s1_endpoint_address = "192.168.59.100"
s2_endpoint_address = "192.168.59.101"
key = "99"
s1.cmdPrint("ovs-vsctl add-port s1 s1-eth2 -- set interface s1-eth2 type=gre options:local_ip=" + s1_endpoint_address + " options:remote_ip=" + s2_endpoint_addres... | ns:local_ip=" + s2_endpoint_address + " options:remote_ip=" + s1_endpoint_address + " options:key=" + key)
info("Recommand command:\n")
info("$ tcpdump -i eth0 proto GRE\n")
CLI( net )
net.stop()
if __name__ == '__main__':
setLogLevel( 'info' )
demo()
|
nocarryr/AV-Asset-Manager | avam/object_history/urls.py | Python | gpl-3.0 | 208 | 0.004808 | fr | om django.conf.urls import url
from object_history import views
urlpatterns = [
url(r'^object_history/(?P<pk>[0-9]+)/$',
views.ObjectHistory.as_view(),
name='object_history',
),
]
| |
hakonsbm/nest-simulator | pynest/nest/tests/test_errors.py | Python | gpl-2.0 | 2,240 | 0.000446 | # -*- coding: utf-8 -*-
#
# test_errors.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or... | el.NESTError, "UnknownNode", nest.Connect, (99, ), (99, ))
def test_UnknownModel(self):
"""Unknown model name"""
nest.ResetKernel()
self.assertRaisesRegex(
nest.kernel.NESTError, "UnknownModelName", nest.Create, -1)
def suite():
suite = unittest.makeSuite(ErrorTestCase, ... | 2)
runner.run(suite())
if __name__ == "__main__":
run()
|
nmiranda/dedupe | tests/test_crossvalidation.py | Python | mit | 2,046 | 0.017595 | import dedupe
import unittest
import numpy
class KFoldsTest(unittest.TestCase):
def test_normal_k(self) :
l = list(dedupe.crossvalidation.kFolds(numpy.array(range(6)), 6))
assert len(l) == 6
def test_small_k(self) :
self.assertRaises(ValueError,
lambda : lis... | numpy.ones(5))
assert score == 1
def test_all_predicted(self) :
score = dedupe.crossvalidation.scorePredictions(numpy.array([1,0,1,0]),
numpy.array([1,1,0,0]))
assert score == 0
... | :
avg_score = dedupe.crossvalidation.reduceScores([None, None])
assert avg_score == 0
def test_some_nones(self) :
avg_score = dedupe.crossvalidation.reduceScores([1, None])
assert avg_score == 1
def test_no_nones(self) :
avg_score = dedupe.crossvalidation.reduceScores([... |
Code4SA/pmg-cms-2 | pmg/models/posts.py | Python | apache-2.0 | 2,048 | 0.000488 | from builtins import str
from sqlalchemy import func, sql
from sqlalchemy.orm import validates
from .base import FileLinkMixin, ApiResource
from pmg import db
class Post(ApiResource, db.Model):
__tablename__ = "post"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String, nullable=Fal... | _timestamp(),
)
def get_preview_image(self):
if self.files:
return self.files[0].file
else:
return None
@validates("slug")
def validate_slug(self, key, value):
return value.strip("/")
def __str__(self):
return str(self.title)
class PostFil... | b.Column(
db.Integer,
db.ForeignKey("post.id", ondelete="CASCADE"),
index=True,
nullable=False,
)
post = db.relationship("Post")
file_id = db.Column(
db.Integer,
db.ForeignKey("file.id", ondelete="CASCADE"),
index=True,
nullable=False,
)
... |
axbaretto/beam | sdks/python/apache_beam/runners/worker/sdk_worker_main_test.py | Python | apache-2.0 | 4,025 | 0.003727 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | py of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ | ing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Tests for apache_beam.runners.worker.sdk_worker_main."... |
shweta97/pyta | examples/pylint/W0212_protected_access.py | Python | gpl-3.0 | 141 | 0.007092 | class MyClass:
def __init__(self | ):
self._num = 42
c = MyClass()
# Should not be accssing the protected attribute:
print(c. | _num)
|
jkorell/PTVS | Python/Tests/TestData/DjangoProject/urls.py | Python | apache-2.0 | 813 | 0.00861 | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'DjangoApplication1.views.home', name='home'),
# url(r'^Dja | ngoApplication1/', include('DjangoApplication1.fob.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^O... | url(r'^loop2/$', 'Oar.views.loop2'),
)
|
KeoH/django-keoh-kstore | kstore/models/manufacturers.py | Python | bsd-2-clause | 104 | 0.019231 | #encoding:utf-8
from .abstracts import BaseCompanyModel
class Manufacturer(BaseCompanyMod | el):
| pass
|
imyousuf/smart-patcher | src/smart-patcher.py | Python | gpl-3.0 | 5,526 | 0.007781 | #!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf (imran@smartitengineering.com)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Pu... | UT ANY WARRANTY; without even the implied warran | ty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1... |
JasonWyse/FacRankSvm_c | table6.py | Python | bsd-3-clause | 2,609 | 0.040245 | from parameter import *
from parse_digit import *
from os import system
cmd = "make -C tools >/dev/null 2>/dev/null;mkdir log model 2>/dev/null"
system(cmd)
#remove those method/data you are not interested in its result
methodlist = ['random-forest','gbdt']
data = ['MQ2007','MQ2008','MSLR','YAHOO_SET1','YAHOO_SET2',... | YAHOO_SET2':
if '(YAHOO) | ' in l:
ndcg = l.split(' ')[-2].strip()
digit = "$%1.4f$"%float(ndcg)
o.append(digit)
else:
if 'Mean' in l:
if d == 'MQ2007-list' or d == 'MQ2008-list':
digit = "NA"
else:
ndcg = l.split(' ')[-2].strip()
digit = "$%1.4f$"%float(ndcg)
o.append(digit)
print outpu... |
guoyr/geo-caching | store_commands.py | Python | mit | 835 | 0.016766 | from twisted.protocols import amp
from constants import *
class SendSingleImageInfo(amp.Command):
arguments = [(USER_UID_KEY, amp.String()), (CACHE_UID_KEY, amp.String()), (IMAGE_UID_KEY, amp.String())]
response = [("success", amp.Boolean())]
#inform new master of master change
class InitiateMasterChange(amp... | s = [(USER_UID_KEY, amp.String())]
| response = [("success", amp.Boolean())]
|
derekjamescurtis/veritranspay | tests/response_bins_tests.py | Python | bsd-3-clause | 911 | 0.004391 | from unittest import TestCase
from veritranspay.response import BinResponse
class BinsRequestResponseTests(TestCase):
def setUp(self):
# example response data from
# --
self.response_json = {
"data": {
"country_name": "Indonesia",
"country_code... | tatus_message='',**self.response_json)
def test_status_code(self):
self.assertEqual(200, | self.parsed_response.status_code)
def test_response_data(self):
self.assertEqual(self.parsed_response.serialize().get('data'), self.response_json.get('data'))
|
vangj/py-bbn | pybbn/graph/dag.py | Python | apache-2.0 | 11,592 | 0.000863 | import json
import networkx as nx
from pybbn.graph.edge import Edge, EdgeType
from pybbn.graph.graph import Graph
from pybbn.graph.node import BbnNode
from pybbn.graph.variable import Variable
class Dag(Graph):
"""
Directed acyclic graph.
"""
def __init__(self):
"""
Ctor.
""... | h, {})])
return g, dict(labels)
class Bbn(Dag):
"""
BBN.
"""
def __init__(self):
"""
Ctor.
"""
Dag.__init__(self)
self.parents = {}
def get_parents_ordered(self, id):
"""
Gets the IDs of the specified node ordered.
:param ... | lf.parents[id]) if id in self.parents else []
def __edge_added__(self, edge):
if edge.j.id not in self.parents:
self.parents[edge.j.id] = []
if edge.i.id not in self.parents[edge.j.id]:
self.parents[edge.j.id].append(edge.i.id)
def __shouldadd__(self, edge):
""... |
huaweiswitch/neutron | neutron/tests/unit/openvswitch/test_ovs_neutron_agent.py | Python | apache-2.0 | 73,059 | 0.000246 | # Copyright (c) 2012 OpenStack Foundation.
#
# 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... | [p_const.TYPE_GRE, p_const.TYPE_VXLAN])
def test_create_agent_config_map_enable_ | distributed_routing(self):
self.addCleanup(cfg.CONF.reset)
# Verify setting only enable_tunneling will default tunnel_type to GRE
cfg.CONF.set_override('enable_distributed_routing', True,
group='AGENT')
cfgmap = ovs_neutron_agent.create_agent_config_map(cfg.... |
inikdom/rnn-speech | models/AcousticModel.py | Python | mit | 45,676 | 0.004335 | # coding=utf-8
"""
Based on the paper:
http://arxiv.org/pdf/1601.06581v2.pdf
And some improvements from :
https://arxiv.org/pdf/1609.05935v2.pdf
This model is:
Acoustic RNN trained with ctc loss
"""
import tensorflow as tf
from tensorflow.python.client import timeline
import numpy as np
import time
import os
from... | lr_decay_factor: decay factor of the learning rate
:param use_iterator: if True then plug an iterator.get_next() operation for the input of the model, if None
placeholders are created instead
"""
| if self.rnn_created:
logging.fatal("Trying to create the acoustic RNN but it is already.")
# Store model parameters
self.input_keep_prob = input_keep_prob
self.output_keep_prob = output_keep_prob
if use_iterator is True:
mfcc_batch, input_lengths, label_batch... |
pronexo-odoo/odoo-argentina | l10n_ar_wsafip_fe/__openerp__.py | Python | agpl-3.0 | 2,467 | 0.004866 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 OpenERP - Team de Localización Argentina.
# https://launchpad.net/~openerp-l10n-ar-localization
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of t... | ,
'data/wsafip_fe_config.xml',
| 'security/ir.model.access.csv',
'wizard/query_invoices_view.xml',
'wizard/validate_invoices_view.xml'],
'version': '2.7.244',
'website': 'https://launchpad.net/~openerp-l10n-ar-localization'}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
MelissaChan/MachineLearning | naiveBayes/bayes.py | Python | mit | 4,473 | 0.025242 | # __author__ = MelissaChan
# -*- coding: utf-8 -*-
# 16-2-14 下午4:37
# 词表转换向量
# 创建词汇表
def createVocabList(dataSet):
vocabSet = set([])
for document in dataSet:
vocabSet = vocabSet | set(document)
return list(vocabSet)
# 转换为向量
def setOfWords2Vec(vocablist,inputset):
returnVec = [0] * len(vocablis... | dex])
del(trainingSet[randIndex])
trainMat=[]; trainClasses = []
for docIndex in trainingSet:
trainMat.append(bagOfWord2Vec(vocabList, docList[docIndex]))
trainClasses.append(classList[docIndex])
p0V,p1V,pSpam = trainNB0(array(trainMat),array(trainClasses))
# 对测试集进行分类
errorCo... | x])
if classify(array(wordVector),p0V,p1V,pSpam) != classList[docIndex]:
errorCount += 1
print "classification error",docList[docIndex]
print 'the error rate is: ',float(errorCount)/len(testSet)
for i in range(10):
spamTest() |
originaltebas/chmembers | app/informes/views.py | Python | mit | 42,730 | 0.000094 |
# app/informes/views.py
# coding: utf-8
from flask import redirect, render_template, url_for, request
from flask_login import current_user, login_required
from app.informes import informes
from app.informes.forms import FiltroInformePersonas
from app import db
from app.models import Miembro, EstadoCivil, TipoFamilia... | Miembro.id_estadocivil ==
EstadoCivil.id)\
.outerjoin(RolFamiliar,
| Miembro.id_rolfamiliar ==
RolFamiliar.id)\
.add_columns(
Miembro.id,
Miembro.fullname,
Miembro.email,
Miembro.... |
christianurich/VIBe2UrbanSim | 3rdparty/opus/src/opus_gui/models_manager/controllers/submodel_editor.py | Python | gpl-2.0 | 42,990 | 0.004862 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
from lxml import etree
from opus_gui.util import common_dialogs
import copy
from lxml.etree import SubElement
from PyQt4 import QtGui, QtCore
from opus_gui.util.convenience import create_qt_action
fr... | el)
self.table_selected_variables.horizontalHeader().setStretchLastSection(True)
self.table_selected_variables.verticalHeader().hide()
| self.table_selected_variables.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
signal = S("customContextMenuRequested(const QPoint &)")
self.connect(self.table_selected_variables, signal, self._right_click_variables)
f_create_nest = lambda x = 'nest': self.tree_structure_editor.create_str... |
unifycore/ryu | ryu/app/ofctl_rest.py | Python | apache-2.0 | 8,459 | 0.000236 | # Copyright (C) 2012 Nippon Telegraph and Telephone Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 'dpset': dpset.DPSet,
'wsgi': WSGIApplication
}
def __init__(self, *args, **kwargs):
super(RestStatsApi, self).__init__(*args, **kwargs)
self.dpset = kwargs['dpset']
wsgi = kwargs['wsgi']
self.waiters = {}
self.data = {}
self.data['dpset'] = self.dpse... | ] = self.data
path = '/stats'
uri = path + '/switches'
mapper.connect('stats', uri,
controller=StatsController, action='get_dpids',
conditions=dict(method=['GET']))
uri = path + '/desc/{dpid}'
mapper.connect('stats', uri,
... |
JaeGyu/PythonEx_1 | flask21_for_angular.py | Python | mit | 217 | 0.013825 | from flask import Flask, jsonify
from flask_restplus import Api, Resource, fields
app = Flask(__name__)
api = Api(app)
@app.route("/") |
def index():
return ""
if __n | ame__ == "__main__":
app.run(debug=True)
|
xydinesh/euwe | setup.py | Python | apache-2.0 | 1,302 | 0 | import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.txt')) as f:
README = f.read()
with open(os.path.join(here, 'CHANGES.txt')) as f:
CHANGES = f.r | ead()
requires = [
'pyramid',
'pyramid_chameleon',
'pyramid_mako',
'pyramid_debugtoolbar',
'pyramid_tm',
'SQLAlchemy',
'transaction',
'zope.sqlalchemy',
'waitress',
'WebTest',
'selenium',
'nose',
'pyramid_persona',
]
setup(name='euwe',
version='0.0',
... | ption='euwe',
long_description=README + '\n\n' + CHANGES,
classifiers=[
"Programming Language :: Python",
"Framework :: Pyramid",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='Dinesh Weerapurage',
autho... |
Uberlearner/uberlearner | uberlearner/accounts/api/api.py | Python | mit | 1,436 | 0.005571 | from avatar.templatetags.avatar_tags import avatar_url
from django.conf import settings
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from tastypie import fields
from tastypie.resources import ModelResource
from accounts.models import UserProfile
from main.api.authentication i... | ehydrate(self, bundle):
bundle.data['absolute_url'] = reverse('account_user_prof | ile_with_username', kwargs={'username': bundle.obj.username})
bundle.data['best_name'] = bundle.obj.profile.get_best_name()
bundle.data['tiny_thumbnail'] = avatar_url(bundle.obj, size=settings.AVATAR_SIZE_IN_ENROLLMENTS_GRID)
return bundle
class UserProfileResource(ModelResource):
class Met... |
the-fascinator/fascinator-portal | src/main/config/portal/default/default/scripts/actions/authtest.py | Python | gpl-2.0 | 1,050 | 0.001905 | from com.googlecode.fascinator.common import JsonSimple
class AuthtestData:
def __init__(self):
pass
def __activate__(self, context):
request = context["request"]
response = context["response"]
writer = response.getPrintWriter("text/javascript; charset=UTF-8")
result =... | if jsonpCallback is None:
response.setStatus(403)
writer.println("Error: This interface only responds to JSONP")
writer.close()
return
if context["page"].authentication.is_logged_in():
result.getJsonObject().put("isAuthenticated", "... | writer.println(jsonpCallback + "(" + result.toString() + ")")
writer.close()
|
deependhulla/technomail-debian | files/html_oldx/groupoffice/modules/chat/converse.js-0.8.6/docs/source/conf.py | Python | gpl-3.0 | 9,866 | 0.005575 | # -*- coding: utf-8 -*-
#
# Converse.js documentation build configuration file, created by
# sphinx-quickstart on Fri Apr 26 20:48:03 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
#... | #
# Values: "true" (default) or "false"
'globaltoc_includehidden': "true",
# HTML navbar class (Default: "navbar") to attach to <div> element.
# For black navbar, do "navbar navbar-inverse"
'navbar_class': "navbar",
# Fix navigation bar to top of page?
# Values: "true" ( | default) or "false"
'navbar_fixed_top': "true",
# Location of link to source.
# Options are "nav" (default), "footer" or anything else to exclude.
'source_link_position': "footer",
# Bootswatch (http://bootswatch.com/) theme.
# Options are nothing (default) or the name of a valid theme
# suc... |
dongsenfo/pymatgen | pymatgen/alchemy/tests/test_transmuters.py | Python | mit | 4,616 | 0.001733 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import warnings
import unittest
import os
from pymatgen.alchemy.transmuters import CifTransmuter, PoscarTransmuter
from pymatgen.alchemy.filters import ContainsSpecieFilter
from pymatgen.transformations.standa... | on
from pymatgen.transformations.advanced_transformations import \
SuperTransformation
'''
Cre | ated on Mar 5, 2012
'''
__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "shyuep@gmail.com"
__date__ = "Mar 5, 2012"
test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
'te... |
skosukhin/spack | lib/spack/spack/cmd/debug.py | Python | lgpl-2.1 | 3,522 | 0 | ##############################################################################
# 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... | t = which('git')
if not git:
return 'nobranch-nogit-%s' % suffix
with working_dir(spack.spack_root):
if not os.path.isdir('.git'):
return 'nobranch.nogit.%s' % suffix
# Get symbolic branch name and strip any special chars (mainly '/')
symbolic = git(
| 'rev-parse', '--abbrev-ref', '--short', 'HEAD', output=str).strip()
symbolic = re.sub(r'[^\w.-]', '-', symbolic)
# Get the commit hash too.
commit = git(
'rev-parse', '--short', 'HEAD', output=str).strip()
if symbolic == commit:
return "nobranch.%s.%s" % (comm... |
cgimenop/Excel2Testlink | ExcelParser/lib/openpyxl/chart/tests/test_reference.py | Python | mit | 2,862 | 0.004542 | from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl
import pytest
from openpyxl.xml.functions import fromstring, tostring
from openpyxl.tests.helper import compare_xml
@pytest.fixture
def Reference():
from ..reference import Reference
return Reference
@pytest.fixture
def Worksheet():
... | __(self, title="dummy"):
self.title = title
return DummyWorksheet
class TestReference:
def test_ctor(self, Reference, Worksheet):
ref = Reference(
worksheet=Worksheet(),
min_col=1,
min_row=1,
max_col=10,
max_row=12
)
... | assert str(ref) == "dummy!$A$1"
def test_from_string(self, Reference):
ref = Reference(range_string="Sheet1!$A$1:$A$10")
assert (ref.min_col, ref.min_row, ref.max_col, ref.max_row) == (1,1, 1,10)
assert str(ref) == "Sheet1!$A$1:$A$10"
def test_cols(self, Reference):
ref = Ref... |
iftekeriba/softlayer-python | SoftLayer/CLI/server/list.py | Python | mit | 2,923 | 0 | """List hardware servers."""
# :license: MIT, see LICENSE for more details.
import SoftLayer
from SoftLayer.CLI import columns as column_helper
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer.CLI import helpers
import click
# pylint: disable=unnecessary-lambda
COLUMNS = [
... | r',)),
column_helper.Column('primary_ip', ('primaryIpAddress',)),
column_helper.Column('backend_ip', ('primaryBackendIpAddress',)),
column_helper.Column('datacenter', ('datacenter', 'name')),
column_helper.Column(
'action',
| lambda server: formatting.active_txn(server),
mask='''
mask(SoftLayer_Hardware_Server)[activeTransaction[
id,transactionStatus[name,friendlyName]
]]'''),
column_helper.Column('power_state', ('powerState', 'name')),
column_helper.Column(
'created_by',
('b... |
dkopecek/amplify | third-party/quex-0.65.2/quex/engine/analyzer/mega_state/template/gain_transition_map.py | Python | gpl-2.0 | 4,059 | 0.0069 | # vim:set encoding=utf8:
# (C) 2010-2012 Frank-Rene Schäfer
from quex.engine.analyzer.mega_state.target import TargetByStateKey
from quex.engine.analyzer.transition_map import TransitionMap
from itertools import chain
def do(ATm, AStateN, ASchemeN, BTm, BStateN, BSchemeN):
"""*Tm -- transitio... | maps into a signle one.
"""
# Costs of each single transition maps
a_cost = __transition_map_cost(AStateN, len(ATm), ASchemeN)
b_cost = __transition_map_cost(BStateN, len(BTm), BSchemeN)
| # Cost of the combined transition map
combined_cost = _transition_cost_combined(ATm, BTm, AStateN + BStateN)
return ((a_cost + b_cost) - combined_cost)
def _transition_cost_combined(TM_A, TM_B, ImplementedStateN):
"""Computes the storage consumption of a transition map.
"""
# Count the numbe... |
shubhdev/edx-platform | lms/djangoapps/discussion_api/tests/test_views.py | Python | agpl-3.0 | 28,826 | 0.001249 | """
Tests for Discussion API views
"""
from datetime import datetime
import json
from urlparse import urlparse
import httpretty
import mock
from pytz import UTC
from django.core.urlresolvers import reverse
from rest_framework.test import APIClient
from discussion_api.tests.utils import (
CommentsServiceMockMixi... | not_authenticated(self):
self.client.logout()
response = self.client.get(self.url)
self.assert_response_correct(
response,
401,
{"developer_message": "Authentication credentials were not provided."}
)
class CourseViewTest( | DiscussionAPIViewTestMixin, ModuleStoreTestCase):
"""Tests for CourseView"""
def setUp(self):
super(CourseViewTest, self).setUp()
self.url = reverse("discussion_course", kwargs={"course_id": unicode(self.course.id)})
def test_404(self):
response = self.client.get(
revers... |
weichen2046/IntellijPluginDevDemo | enterprise-repo/enterprepo/enterprepo/urls.py | Python | apache-2.0 | 1,167 | 0.000857 | """enterprepo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Ad | d a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including anoth | er URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic.base import TemplateView
urlpatterns = [
url(r'^... |
arantebillywilson/python-snippets | microblog/flask/lib/python3.5/site-packages/openid/oidutil.py | Python | mit | 6,651 | 0.00015 | """This module contains general utility code that is used throughout
the library.
For users of this library, the C{L{log}} function is probably the most
interesting.
"""
__all__ = [
'log', 'appendArgs', 'toBase64', 'fromBase64', 'autoSubmitHTML',
'toUnicode'
]
import binascii
import logging
# import urllib.... | rn binascii.b2a_base64(s)[:-1]
def fromBase64(s):
if isinstance(s, str):
s = s.encode("utf-8")
try:
return binascii.a2b_base64(s)
except binascii.Error as why:
# Convert to a common exception type
raise ValueError(str(why))
class Symbol(object):
"""This class implemen... | """
def __init__(self, name):
self.name = name
def __eq__(self, other):
return type(self) is type(other) and self.name == other.name
def __ne__(self, other):
return not (self == other)
def __hash__(self):
return hash((self.__class__, self.name))
def __repr__(self... |
kingmotley/SickRage | sickbeard/providers/xthor.py | Python | gpl-3.0 | 7,253 | 0.003314 | # coding=utf-8
# Author: adaur <adaur.underground@gmail.com>
# Rewrite: Dustyn Gibson (miigotu) <miigotu@gmail.com>
# URL: https://sickrage.github.io
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publishe... | arch(self, search_strings, age=0, ep_obj=None): # pylint: disable=too-many-locals, too-many-branches, too-many-statements
results = []
if not self.login():
return results
"""
Séries / Pack TV 13
Séries / TV FR 14
Séries / HD FR 15
Séries / TV VOSTFR ... | 'only_free': try_int(self.freeleech),
'searchin': 'title',
'incldead': 0,
'type': 'desc',
'c13': 1, 'c14': 1, 'c15': 1,
'c16': 1, 'c17': 1, 'c32': 1
}
# Units
units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
def process_column... |
sinnwerkstatt/landmatrix | apps/landmatrix/models/deal_submodels.py | Python | agpl-3.0 | 5,262 | 0.00133 | # from django.contrib.gis.db import models as gismodels
# from django.contrib.postgres.fields import JSONField
# from django.db import models
# from django.utils.translation import ugettext as _
#
# from apps.landmatrix.models import Deal
# from apps.landmatrix.models.mixins import (
# OldContractMixin,
# OldDa... | d(blank=True, null=True)
# name = models.CharField(_("Nam | e"), max_length=500, blank=True)
# company = models.CharField(_("Company"), max_length=500, blank=True)
# email = models.EmailField(_("Email"), blank=True)
# phone = models.CharField(_("Phone"), max_length=500, blank=True)
#
# includes_in_country_verified_information = models.NullBooleanField(
# ... |
ntt-sic/neutron | neutron/plugins/nicira/extensions/nvp_qos.py | Python | apache-2.0 | 7,517 | 0.000133 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Nicira, 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/lic... | resource_name,
plugin, params, allow_bulk=False)
ex = extensions.ResourceExtension(collection_name,
| controller)
exts.append(ex)
return exts
def get_extended_resources(self, version):
if version == "2.0":
return dict(EXTENDED_ATTRIBUTES_2_0.items() +
RESOURCE_ATTRIBUTE_MAP.items())
else:
return {}
class... |
snownothing/Python | web/server.py | Python | mit | 651 | 0.004608 | # !/usr/bin/env python
# coding: utf-8
__author__ = 'Moch'
import tornado.ioloop
im | port tornado.options
import tornado.httpserver
from application import application
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
def main():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(application)
htt... | p.instance().start()
if __name__ == "__main__":
main()
|
nolanliou/tensorflow | tensorflow/contrib/quantize/python/quantize.py | Python | apache-2.0 | 11,989 | 0.004754 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ema_decay=ema_decay,
quant_delay=quant_delay,
is_training=is_training,
narrow_range=True,
vars_collection=vars_collection) |
# Quantize the activations.
consumer_ops = input_to_ops_map.ConsumerOperations(
layer_match.activation_op)
add_context = context
if layer_match.bypass_op:
add_context = re.search(r'^(.*)/([^/]+)', context).group(1)
_InsertQuantOp(
add_context,
layer_match.activation_o... |
google/tangent | tests/test_optimization.py | Python | apache-2.0 | 2,734 | 0.008413 | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
x = 0
x = x
x = 1 |
x = x ** 2
x = 2 ** x
x = 8
node = quoting.parse_function(f)
node = optimization.constant_folding(node)
node_opt = quoting.parse_function(f_opt)
lines = quoting.to_source(node).strip().split('\n')[1:]
lines_opt = quoting.to_source(node_opt).strip().split('\n')[1:]
# In Python 2 integer divisio... |
titeuf87/evennia | evennia/players/admin.py | Python | bsd-3-clause | 9,894 | 0.001516 | #
# This sets up how models are displayed
# in the web admin interface.
#
from builtins import object
from django import forms
from django.conf import settings
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import UserChangeForm, UserCre... | {'fields': ('db_typeclass_path', 'db_cmdset_storage'),
'description': "<i>These | fields define in-game-specific properties "
"for the Player object in-game.</i>"}))
extra = 1
max_num = 1
class PlayerTagInline(TagInline):
"""
Inline Player Tags.
"""
model = PlayerDB.db_tags.through
related_field = "playerdb"
class PlayerAttributeInline(Attri... |
toumorokoshi/miura | miura/tests/test_init.py | Python | mit | 202 | 0 | from miura import _parse_filter_string |
class TestParseFilterString(object):
def parse_filter_string_no_equals(self):
""" _parse_filter_string with no equals s | hould raise an exception """
|
cournape/ensetuptools | setuptools/utils.py | Python | bsd-3-clause | 2,491 | 0.001204 | """
This module is not part of the original setuptools code.
It was created because much of the code in order modules was (and still
is) unorganized and simple utility functions were defined as class methods
for no obious reason, uselessly cluttering some of the large classes.
This module is a place such functions.
""... | e = 1
return retcode
def execute_script(py_path):
"""
Execute the python script (located at path) and log error message
when the return value of the subprocess was non-zero.
"""
retcode = subprocess.call([sys.executable, py_path])
if retcode != 0:
log.warn("WARNING: executing Pyt... | re_file_from_zip(zipfile_path, name, path):
"""
Given the path to a zipfile and the name of a file within the zipfile,
store the content of the file, into location path.
If the name does not exist within the zipfile, and don't create a file,
obviously, but don't throw an exceoption.
"""
z = ... |
it-projects-llc/website-addons | website_sale_birthdate/__manifest__.py | Python | mit | 382 | 0 | {
"name": "website_sale_birthdate",
"author": "IT-Projects LLC, Ivan Yelizariev",
| "license": "Other OSI approved licence", # MIT
| "support": "apps@itpp.dev",
"website": "https://yelizariev.github.io",
"category": "eCommerce",
"vesion": "13.0.1.0",
"depends": ["website_sale", "partner_person"],
"data": ["views.xml"],
"installable": False,
}
|
google/init2winit | init2winit/optimizer_lib/__init__.py | Python | apache-2.0 | 603 | 0.001658 | # coding=utf-8
# Copyright 2022 The init2winit Authors.
#
# Licensed under the Apach | e 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 o... | THOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
|
lhupfeldt/multiconf | test/include_exclude2_test.py | Python | bsd-3-clause | 13,628 | 0.003082 | # Copyright (c) 2012 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
# pylint: disable=E0611
from pytest import raises
from multiconf import mc_config, ConfigItem, ConfigException, ConfigExcludedAttributeError, MC_REQUIRED, McInvalidValue
from multiconf.dec... | olve branch"""
with item(mc_include=[g_dev12, g_dev12_3, pp, dev2], mc_exclude=[g_dev34, g_dev2_34, dev3]) as it:
it.setattr('anattr', pp=1, g_dev12_3=2)
it.setattr('b', pp=1, dev2=0)
it.setattr('anotherattr', default=111, dev5=7)
cr = c | onfig(prod)
assert not cr.item
assert compare_json(cr, _include_exclude_for_configitem_expected_json, test_excluded=True)
cr = config(dev1)
assert cr.item
cr = config(dev2)
assert cr.item
assert cr.item.b == 0
cr = config(dev3)
assert not cr.item
cr = config(dev4)
assert ... |
xu2243051/idc_assets_management | idc_assets_management/idc_assets_management/settings/base.py | Python | gpl-2.0 | 7,281 | 0.004944 | """Common settings and globals."""
from os.path import abspath, basename, dirname, join, normpath
from sys import path
########## PATH CONFIGURATION
# Absolute filesystem path to the Django project directory:
DJANGO_ROOT = dirname(dirname(abspath(__file__)))
# Absolute filesystem path to the top-level project fold... | #static-root
STATIC_ROOT = normpath(join(SITE_ROOT, 'assets'))
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATI | C_URL = '/static/'
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
STATICFILES_DIRS = (
normpath(join(SITE_ROOT, 'static')),
)
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = (
'django.contrib.st... |
andyvandermeyde/match_subtitles | test/test_suite.py | Python | mit | 1,796 | 0.012249 | import unittest
import os
import inspect
import shutil
import config
import rename_subtitles
import upload_subtitles
class TestSuit(unittest.TestCase):
# TESTS
def test_basic_match(self):
rename_subtitles.main()
upload_subtitles.main()
#Match simple Test_Series_S01E01.srt with Test_Se... | .abspath(inspect.getfile(inspect.currentframe())))
print directory
resources = os.path.join(directory, "resources/")
#If the path already exists
if os.path.exists(resources):
#Remove everything to refresh the test environment
shutil.rmtree(resources)
#Create the resources folder
... | , "root/")
upload_folder = os.path.join(resources, "upload/")
#Create root folder
os.makedirs(root_folder)
#Create upload folder
os.makedirs(upload_folder)
#and some empty files for the tests
open(os.path.join(root_folder, "Test_Series_S01E01.mp4"), 'a').close()
open(os.path.join(upload_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.