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 |
|---|---|---|---|---|---|---|---|---|
mupif/mupif | examples/Example10-jobMan-distrib-PBS/application10.py | Python | lgpl-3.0 | 5,189 | 0.003469 | import sys
import os
import Pyro5
import logging
sys.path.extend(['..', '../..'])
import mupif as mp
import time as timemod
import uuid
import pbs_tool
log = logging.getLogger()
@Pyro5.api.expose
class Application10(mp.Model):
"""
Simple application which sums given time values times 2
"""
def __init... | if obj.isInstance(mp.Property):
if obj.getPropertyID() == mp.DataID.PID_Time:
self.input = obj.inUnitsOf(mp.U.s).getValue()
def solveStep(self, tstep, stageID=0, runInBackground=False):
# this function is designed to run the executable in Torque or Slurm PBS and process th... | ach application/executable)
step_id = uuid.uuid4()
inpfile = "%s/inp_%s.txt" % (dirname, step_id)
outfile = "%s/out_%s.txt" % (dirname, step_id)
#
# create the input file
f = open(inpfile, 'w')
f.write("%f" % self.input)
f.close()
#
# sub... |
hirofumi0810/tensorflow_end2end_speech_recognition | utils/progressbar.py | Python | mit | 441 | 0 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __fut | ure__ import absolute_import
from __future__ import division
from __future__ | import print_function
from tqdm import tqdm
def wrap_iterator(iterator, progressbar):
if progressbar:
iterator = tqdm(iterator)
return iterator
def wrap_generator(generator, progressbar, total):
if progressbar:
generator = tqdm(generator, total=total)
return generator
|
cosven/FeelUOwn | feeluown/gui/uimodels/my_music.py | Python | gpl-3.0 | 980 | 0 | from feeluown.utils.dispatch import Signal
from feeluown.gui.widgets.my_music import MyMusicModel
class MyMusicItem(object):
def __in | it__(self, text):
self.text = text
self.clicked = Signal()
class MyMusicUiManager:
"""
.. note::
| 目前,我们用数组的数据结构来保存 items,只提供 add_item 和 clear 方法。
我们希望,MyMusic 中的 items 应该和 provider 保持关联。provider 是 MyMusic
的上下文。
而 Provider 是比较上层的对象,我们会提供 get_item 这种比较精细的控制方法。
"""
def __init__(self, app):
self._app = app
self._items = []
self.model = MyMusicModel(app)
@... |
indico/indico | indico/modules/events/sessions/schemas.py | Python | mit | 937 | 0.002134 | # This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from marshmallow import fields
from indico.core.marshmallow import mm
from indico.modules.events.sessions... | BlockSchema, many=True)
class Meta:
model = Session
| fields = ('id', 'title', 'friendly_id', 'blocks')
|
cherry-hyx/hjb-test | 脚本/deploy/t.py | Python | artistic-2.0 | 449 | 0 | # !/usr/bin/env python
# -*-coding:utf-8-*-
# by huangjiangbo
# 部署服务
# deploy.py
from ConfigParser import C | onfigParser
C | onfigFile = r'config.ini' # 读取配置文件
config = ConfigParser()
config.read(ConfigFile)
de_infos = config.items(r'deploy_server') # 远程部署服务器信息
redeploy_server_info = {}
appinfo = {}
print de_infos
for (key, value) in de_infos:
redeploy_server_info[key] = value
print redeploy_server_info
|
neuroelectro/neuroelectro_org | neuroelectro/migrations/0024_auto_20160604_1750.py | Python | gpl-2.0 | 423 | 0 | # -*- coding: utf-8 -*-
from __future__ | import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('neuroelectro', '0023_auto_20160604_1620'),
] |
operations = [
migrations.AlterField(
model_name='datatablestat',
name='last_curated_on',
field=models.DateTimeField(null=True),
),
]
|
wbg-optronix-lab/emergence-lab | core/api/user.py | Python | mit | 460 | 0 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from rest_framework import generics, permissions
from core.models import User
from core.ser | ializers import UserSerializer
class UserListAPIView(generics.ListAPIView):
"""
Read-only API View to list all users.
"""
queryset = User.objects.all()
serializ | er_class = UserSerializer
permission_classes = (permissions.IsAuthenticated,)
paginate_by = 100
|
yoshrote/Columns | columns/lib/authentication.py | Python | bsd-3-clause | 21,673 | 0.036635 | import urllib, cgi
from decorator import decorator
from pylons.controllers.util import redirect
from pylons.controllers.util import Response, Request
from columns.lib import helpers
#from columns.lib import oauthtwitter
import oauthtwitter
from columns.lib import json
from columns.lib.exc import NoResultFound
from open... | sued, assoc))
if associations:
associations.sort()
return associations[-1][1]
else:
return None
def removeAssociation(self, server_url, handle):
"""
This method removes the matching association if it's found,
and re | turns whether the association was removed or not.
@param server_url: The URL of the identity server the
association to remove belongs to. Because of the way the
server portion of the library uses this interface, don't
assume there are any limitations on the character set of
the input string. In parti... |
srguiwiz/nrvr-commander | src/nrvr/xml/etree.py | Python | bsd-2-clause | 4,914 | 0.004274 | #!/usr/bin/python
"""nrvr.xml.etree - Utilities for xml.etree.ElementTree
The main class provided by this module is ElementTreeUtil.
To be expanded as needed.
Idea and first implementation - Leo Baschy <srguiwiz12 AT nrvr DOT com>
Public repository - https://github.com/srguiwiz/nrvr-commander
Copyright (c) Nirvan... | for each level down.
|
If None then unindented.
xml_declaration
whether with XML declaration <?xml version="1.0" encoding="utf-8"?>."""
# tolerate tree instead of element
if isinstance(element, xml.etree.ElementTree.ElementTree):
# if given a tree
element = el... |
tedlaz/pyted | pykoinoxrista/koinoxrista/fmy2015.py | Python | gpl-3.0 | 3,312 | 0.000367 | # -*- coding: utf-8 -*-
import fixed_size_text as ft
nu = ft.Num()
it = ft.Int()
ymd = ft.DatYYYMMDD()
ah1 = [ft.col(8), # Ονομα Αρχείου
ft.col(8, 0, ' ', ymd), # Ημερομηνία δημιουργίας
ft.col(4), # Αρ.Κύκλου τρεξίματος
ft.col(127) # Filler
]
h1 = ft.row(0, ah1)
ah2 = [ft.col(4), # ... | 84400',
''
]
r2 = h2.write(a2)
a3 = [20220.98, 3575.14, 16645.84, 0, 0, 0, 0, 0, '']
r3 = h3.write(a3)
a4 = ['034140096', '', u'ΛΑΖΑΡΟΣ', u'ΘΕΟΔΩΡΟΣ', u'ΚΩΝΣΤΑΝΤ', '02108001427',
1, '01',
20220.98 | , 3575.14, 16645.84, 0, 0, 0, 0, 0, '', ''
]
r4 = h4.write(a4)
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
rtel = r1 + r2 + r3 + r4
print(len(r1), len(r2), len(r3), len(r4))
f = open('tstfile', 'w')
f.write(rtel.encode('CP1253'))
f.close()
|
arity-r/MiniLogic | lex.py | Python | mit | 1,410 | 0.055319 | import ply.lex as lex
from ast import Node
reserved = {
'or' : 'LOR',
'and' : 'LAND',
'neg' : 'NEG',
'exists' : 'EXISTS',
'forall' : 'FORALL',
'implies': 'IMPLIES',
'iff' : 'IFF'
}
tokens = tuple(
[
'WORD',
'VARIABLE',
'CONSTANT',
'FUNCTION',
'PREDICATE',
'COMMA',
'LPA... | error(t)
t.type = type
t.value = Node(type, t.value)
return t
def t_VARIABLE(t):
r'[u-z]'
t.value = Node('VARIABLE', t.value)
return t
def t_CONSTANT(t):
r'[a-e]'
t.value = Node('CONSTANT', t.value)
return t
def t_FUNCTION(t):
r'[f-j]'
t.value = Node('FUNCTION', t.value)
return t
def... | value)
return t
def t_newline(t):
r'\n+'
t.lexer.lineno += len(t.value)
t_ignore = ' \t'
def t_error(t):
print("Illegal character '%s'" % t.value[0])
t.lexer.skip(1)
lexer = lex.lex()
#lexer = lex.lex(optimize=1, debug=1)
if __name__ == '__main__':
data = '''neg (exists x)(forall y)[P(x,y) i... |
yaqiyang/autorest | src/generator/AutoRest.Python.Tests/Expected/AcceptanceTests/BodyDuration/autorestdurationtestservice/auto_rest_duration_test_service.py | Python | mit | 2,204 | 0.001361 | # 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 ... | t__(
self, base_url=None, filepath=None):
self.config = AutoRestDurationTestServiceConfiguration(base_url, filepath)
self._client = ServiceClient(None, self.config)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serialize... | t, self.config, self._serialize, self._deserialize)
|
Cloudify-PS/cloudify-manager-blueprints | components/nginx/scripts/creation_validation.py | Python | apache-2.0 | 445 | 0 | #!/usr/bin/env python
from os.path import join, dirname
from cloudify import ctx
ctx.download_resource(
join('components', 'utils.py'),
join(dirname(__file__), 'utils.py'))
import utils # NOQA
ru | ntime_props = ctx.instance.runtime_propert | ies
if utils.is_upgrade:
SERVICE_NAME = runtime_props['service_name']
utils.validate_upgrade_directories(SERVICE_NAME)
utils.systemd.verify_alive(SERVICE_NAME, append_prefix=False)
|
iansprice/wagtail | wagtail/contrib/modeladmin/helpers/button.py | Python | bsd-3-clause | 7,291 | 0.000137 | from __future__ import absolute_import, unicode_literals
from django.contrib.admin.utils import quote
from django.utils.encoding import force_text
from django.utils.translation import ugettext as _
class ButtonHelper(object):
default_button_classnames = ['button']
add_button_classnames = ['bicolor', 'icon',... | ude)
)
if('delete' not in exclude and ph.user_can_delete_obj(usr, obj)):
btns.append(
self.delete_button(pk, classnames_add, classnames_exclude)
)
return btns
class PageButtonHelper(ButtonHelper):
unpublish_button_classn | ames = []
copy_button_classnames = []
def unpublish_button(self, pk, classnames_add=None, classnames_exclude=None):
if classnames_add is None:
classnames_add = []
if classnames_exclude is None:
classnames_exclude = []
classnames = self.unpublish_button_classnames... |
harterj/moose | python/moosetree/Node.py | Python | lgpl-2.1 | 6,708 | 0.002534 | """
For simplicity this module should be a stand-alone package, i.e., it should not use any
non-standard python packages such as mooseutils.
"""
import copy
from . import search
class Node(object):
"""
Base class for tree nodes that accepts arbitrary attributes.
Create a new node in the tree that is a chi... |
return count
def __iter__(self):
"""Iterate of the children (e.g., `for child in node:`)"""
return iter(self.__children)
def insert(self, idx, child):
| """Insert a nod *child* before the supplied *idx* in the list of children."""
self.__children.insert(idx, child)
child.__parent = self
@property
def path(self):
"""Return the nodes that lead to the root node of the tree from this node."""
nodes = [self]
parent = s... |
cloudify-cosmo/cloudify-manager | tests/integration_tests/resources/dsl/scripts/workflows/test_deployment_id_parameters.py | Python | apache-2.0 | 664 | 0 | import sys
import json
def test_parameter(name, value):
assert value is not None
print("Tested parameter '{0}' is {1}".format(name, value))
if __name__ == '__main__':
with open("{0}/input.json".format(sys.argv[1]), 'r') as fh:
data = json.load(fh)
parameters = data.get('kwargs', {})
exp... | test_parameter(k, v)
expected_parameters.remove(k)
if expected_parameters:
raise Exception("These parameters were not | tested: {0}"
.format(expected_parameters))
|
libvirt/autotest | client/bin/package_unittest.py | Python | gpl-2.0 | 5,565 | 0.001617 | #!/usr/bin/python
import unittest, os
try:
import autotest.common as common
except ImportError:
import common
from autotest_lib.client.common_lib.test_utils import mock
from autotest_lib.client.bin import package, os_dep, utils
class TestPackage(unittest.TestCase):
def setUp(self):
self.god = mo... | sertEquals(info, package_info)
def test_install(self):
# setup
input_package = "package.rpm"
self.god.stub_function(package, "info")
self.god.stub_function(utils, "system")
# record
package_info = {}
package_info['type'] = 'rpm'
package_info['system... | .expect_call(input_package).and_return(package_info)
install_command = 'rpm %s -U %s' % ('', input_package)
utils.system.expect_call(install_command)
# run and test
package.install(input_package)
self.god.check_playback()
def test_convert(self):
os_dep.command.expe... |
unkyulee/elastic-cms | src/task/modules/CMD.py | Python | mit | 530 | 0.00566 | from subprocess import PIPE, Popen
from sqlalchemy import create_engine
def run(p):
try:
p["log"].info(p["action"]['query'])
proc = Popen(p["action"]['query'], shell=True,
stdin | =PIPE, stdout=PIPE, stderr=PIPE)
result = proc.communicate()
message = ''
fo | r r in result:
if r: message += r + '\n'
p["log"].success(message)
except Exception, e:
AllGood = False
p["log"].error("command line execution failed",e)
return True
|
benglard/Rhetorical-Analysis | ParallelismFinder.py | Python | mit | 2,891 | 0.012452 | from nltk import *
from nltk.corpus import brown
class ParallelismFinder:
def __init__(self):
self.f = ""
self.counter = 0
self.para = [] #array to hold instances of parallelism
self.tokenizer = RegexpTokenizer('\w+') #remove punctuation which could mess up finding parallelism
... | c = self.counter
self.counter = 0
self.para = [] #re-initialize to empty array
return c
#Returns the parallelism counter
def get_all_parallelism(self, line):
sent = self.tokenizer.tokenize(line)
tags = self.tagger.tag(sent)
self.get_phrase_parallelism(ta... | allelism(tags, 4) #Group of 4 words
#Get parallelism between n_para # of words
#Ex: the a
#Ex: the bird, the word
#Ex2: I came, I saw, I conquered
#Ex: Of the people, by the people, for the people
#Ex: the people are good, the people are bad
def get_phrase_parallelism(self, tags, n_para):
... |
martwo/ndhist | test/ndhist/log10_axis_test.py | Python | bsd-2-clause | 788 | 0.005076 | import unittest
import numpy as np
impo | rt ndhist
class Test(unittest.TestCase):
def test_log10_axis_1D(self):
"""Tests if the log10_axis works with the ndhist object for 1D
histograms.
"""
axis_0 = ndhist.axes.log10(0.1, 100, 0.1)
self.assertTrue(axis_0.nbins == 32)
h = ndhist.ndhist((axis_0,))
... | alse)
self.assertTrue(np.any(h.bincontent) == False)
h.fill([0.1, 0.2, 99.])
self.assertTrue(np.all(h.bincontent == np.array([
1., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., ... |
FlintHill/SUAS-Competition | UpdatedImageProcessing/UpdatedImageProcessing/TargetDetection/__init__.py | Python | mit | 668 | 0.002994 | from .settings import Settings
from .logger import Logger
from .detection_result_recorder import DetectionResultRecorder
from .color_operations import ColorOperations
from | .target_analyzer import TargetAnalyzer
from .background_color_nullifier import BackgroundColorNullifier
from .target_detectors import TargetDetectors
from .false_positive_eliminators | import FalsePositiveEliminators
from .integrated_target_detection_process import IntegratedTargetDetectionProcess
from .integrated_target_capturing_process import IntegratedTargetCapturingProcess
from .single_target_map_detector import SingleTargetMapDetector
from .mass_target_detector import MassTargetDetector
|
justinfx/AtomSplitter | ui/__init__.py | Python | gpl-3.0 | 776 | 0.005155 | """
Copyright (c) 2010 cmiVFX.com <info@cmivfx.com>
This file is part of AtomSplitter.
AtomSplitter 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, ei | ther version 3 of the License, or
(at your option) any later version.
AtomSplitter is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTI | CULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with AtomSplitter. If not, see <http://www.gnu.org/licenses/>.
Written by: Justin Israel
justinisrael@gmail.com
justinfx.com
""" |
KrisCheng/ML-Learning | archive/Model/sequence/time_series/transform.py | Python | mit | 938 | 0.00533 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# how to transform with pandas
from pandas import Series
from pandas import DataFrame
from scipy.stats import boxcox
from matplotlib import pyplot
series = Series.from_csv( "airline-passengers.csv" , header=0)
dataframe = DataFrame(series.values)
dataframe.columns = ['passeng... | sengers'], lam = boxcox(dataframe['passengers'])
print( "Lambda: %f" % lam)
pyplot.figure(1)
# line plot
pyplot.subplot(211)
pyplot.plot(dataframe['passengers'])
# histogram
pyplot.subplot(212)
pyplot.hist(dataframe['passengers'])
pyplot.show()
# dataframe = DataFrame(series.values)
# dataframe.columns = ["passenger... | t.plot(dataframe["passengers"])
# # histogram
# pyplot.subplot(212)
# pyplot.hist(dataframe["passengers"])
pyplot.show() |
ESS-LLP/frappe | frappe/desk/form/save.py | Python | mit | 1,963 | 0.030056 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe, json
from frappe.desk.form.load import run_onload
@frappe.whitelist()
def savedocs(doc, action):
"""save / submit / update doclist"""
try:
doc = frappe.get_doc... | workflow_state_fieldname, workflow_state)
doc.cancel()
send_updated_docs(doc)
exc | ept Exception:
frappe.errprint(frappe.utils.get_traceback())
frappe.msgprint(frappe._("Did not cancel"))
raise
def send_updated_docs(doc):
from .load import get_docinfo
get_docinfo(doc)
d = doc.as_dict()
if hasattr(doc, 'localname'):
d["localname"] = doc.localname
frappe.response.docs.append(d)
def set... |
hozblok/biodraw | draw/migrations/0007_auto_20160318_2122.py | Python | gpl-3.0 | 475 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-03-18 21:22
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('draw', '0006_auto_20160314_1817') | ,
]
| operations = [
migrations.AlterField(
model_name='physicalentity',
name='display_name',
field=models.CharField(blank=True, max_length=1000),
),
]
|
rebost/pybsd | src/pybsd/commands/ezjail_admin.py | Python | bsd-3-clause | 5,154 | 0.000582 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import logging
import lazy
from ..exceptions import InvalidOutputError, SubprocessError, WhitespaceError
from .base import BaseCommand
__logger__ = logging.getLogger('pybsd')
class EzjailAdmin(BaseCommand):
"""Pro... | >= len(lines[0]):
break
current = ''
else:
current = current + lines[0][pos]
if headers != ['STA', 'JID', 'IP', 'Hostname', 'Root Directory']:
raise InvalidOutputE | rror(self, self.env, u"output has unknown headers\n['{}']".format(u"', '".join(headers)), 'list')
return ('status', 'jid', 'ip', 'name', 'root')
def list(self):
headers = self.list_headers
rc, out, err = self.invoke('list')
if rc:
raise SubprocessError(self, self.env, er... |
codeback/openerp-cbk_company_web_discount | res_company.py | Python | agpl-3.0 | 1,385 | 0.003615 | # -*- encoding: utf-8 -*-
##############################################################################
#
# res_partner
# Copyright (c) 2013 Codeback Soft | ware S.L. (http://codeback.es)
# @author: Miguel García <miguel@codeback.es>
# @author: Javier | Fuentes <javier@codeback.es>
#
# 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 i... |
dana-i2cat/felix | optin_manager/src/python/openflow/optin_manager/sfa/rspecs/elements/pltag.py | Python | apache-2.0 | 161 | 0.012422 | from openflow.optin_man | ager.sfa.rspecs.elements.ele | ment import Element
class PLTag(Element):
fields = [
'tagname',
'value',
]
|
napalm-automation/napalm-yang | napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/isis/global_/igp_shortcuts/afi/__init__.py | Python | apache-2.0 | 25,266 | 0.001583 | # -*- coding: utf-8 -*-
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListTy... | lass(
base=state.state,
is_container="container",
yang_name="state",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True | ,
extensions=None,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="container",
is_config=True,
)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
... |
gotostack/iSwift | iswift/privatefiles/models.py | Python | apache-2.0 | 1,365 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permi | ssions and limitations
# under the License.
from django.db import models
class users_folder_tree(models.Model):
name = models.CharField(max_length=256)
type = models.IntegerField(max_length=128)
parentID = models.IntegerField(max_length=128)
isFile = models.BooleanField()
sizebyte = models.Int... |
HPPTECH/hpp_IOSTressTest | Refer/IOST_OLD_SRC/IOST_0.20/Libs/IOST_WMain/IOST_WMain_SATA.py | Python | mit | 7,573 | 0.007659 | #!/usr/bin/python
#======================================================================
#
# Project : hpp_IOStressTest
# File : Libs/IOST_WMain/IOST_WMainSATA.py
# Date : Oct 20, 2016
# Author : HuuHoang Nguyen
# Contact : hhnguyen@apm.com
# : hoangnh.hpp@gmail.com
# License : MIT License
# Copy... | def on_IOST_WMain_Config_SATA1_C_toggled(self, object, data=None):
""
Res = self.IOST_Objs[self.IOST_WMainSATA_WindowName]["_Config_SATA1_CB"].get_active()
self.IOST_Objs[sel | f.IOST_WMainSATA_WindowName]["_Config_SATA1_B"].set_sensitive(Res)
if (Res):
self.IOST_Data["SATA1"][0] = 'Enable'
else:
self.IOST_Data["SATA1"][0] = 'Disable'
if IOST_WMainSATA_DebugEnable:
iost_print(IOST_DBG_L06, self.IOST_Data["SATA1"][0], "IOST_Data->SA... |
yrahul3910/chatting-style-recognizer | classify.py | Python | mit | 2,888 | 0.009349 | import pandas as pd
import numpy
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
content = []
data = []
common = []
def remove_non_ascii(text):
return ''.join([i if ord(i) < 128 else ' ' for i in text])
def remove_words(array):
final = []
words = []
for... | ata for any person
with open("test_P1.txt", encoding="utf8") as f:
sample = f.readlines()
sample = [w.replace("\n", '') for w in sample]
sample = [remove_non_ascii(w) for w in sample]
sample = remove_words(sample)
sample_count = count_vectorizer.transform(sample)
predictions = classifier.predict(sample_count)
for i i... | predictions:
if i == "Person1":
success += 1
else:
fail += 1
print("Success="+str(success)+"\nFail="+str(fail))
print("Success%="+str(success*100/(fail+success))[0:5]) |
vivisect/synapse | synapse/tests/test_lib_datfile.py | Python | apache-2.0 | 360 | 0.002778 | import os
import unittest
import synapse
import synapse.li | b.datfile as s_datfile
from synapse.tests.common import *
syndir = os.path.dirname(synapse.__file__)
class DatFileTest(SynTest):
def test_datfile_basic(self):
with s_datfile.openDatF | ile('synapse.tests/test.dat') as fd:
self.nn(fd)
self.eq(fd.read(), b'woot\n')
|
dsm054/pandas | pandas/tests/series/methods/test_explode.py | Python | bsd-3-clause | 4,090 | 0.001467 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
def test_basic():
s = pd.Series([[0, 1, 2], np.nan, [], (3, 4)], index=list("abcd"), name="foo")
result = s.explode()
expected = pd.Series(
[0, 1, 2, np.nan, np.nan, 3, 4], index=list("aaabcdd"), dtype=object, name=... | .Series(
[[0, 1, 2 | ], np.nan, [], (3, 4)],
name="foo",
index=pd.MultiIndex.from_product([list("ab"), range(2)], names=["foo", "bar"]),
)
result = s.explode()
index = pd.MultiIndex.from_tuples(
[("a", 0), ("a", 0), ("a", 0), ("a", 1), ("b", 0), ("b", 1), ("b", 1)],
names=["foo", "bar"],
)
... |
twilio/twilio-python | twilio/rest/taskrouter/v1/workspace/task/reservation.py | Python | mit | 38,257 | 0.0046 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import... | but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up | to limit results
:rtype: list[twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(reservation_status=reservation_status, page_size=limits['page_size'], )
return self._version.stream(... |
segler-alex/kodi-radio-browser | main.py | Python | gpl-3.0 | 10,729 | 0.005313 | import sys
import urllib
import urllib2
import urlparse
import xbmcgui
import xbmcplugin
import xbmcaddon
import xbmcvfs
import json
import base64
addonID = 'plugin.audio.radiobrowser'
addon = xbmcaddon.Addon(id=addonID)
base_url = sys.argv[0]
addon_handle = int(sys.argv[1])
args = urlparse.parse_qs(sys.argv[2][1:])
... | '], station['bitrate'])
def readFile(filepath):
with open(filepath, 'r') as read_file:
return json.load(read_file)
def writeFile(filepath, data):
with open(filepath, 'w') as write_file:
ret | urn json.dump(data, write_file)
def addToMyStations(stationuuid, name, url, favicon, bitrate):
my_stations[stationuuid] = {'stationuuid': stationuuid, 'name': name, 'url': url, 'bitrate': bitrate, 'favicon': favicon}
writeFile(mystations_path, my_stations)
def delFromMyStations(stationuuid):
if stationuui... |
chrisspen/homebot | src/test/detect_voice/sphinxtrain_test/samples/make_fileids.py | Python | mit | 559 | 0.005367 | #!/usr/bin/env python
import os, sys
def touch(path):
with open(path, 'a'):
os.utime(path, None)
fout = open('sample.fileids', 'wb')
fout2 = open('sample.transcription', 'wb')
for fn in sorted(os.listdir('.')):
if not fn.endswith('.wav'):
continue
| base_fn = os.path.splitext(fn)[0]
txt_fn = base_fn + '.txt'
touch(txt_fn | )
text = open(txt_fn).read().strip()
if text and not text.startswith('#'):
fout.write('samples/%s\n' % base_fn)
fout2.write('<s> %s <s> (%s)\n' % (text, base_fn))
print 'Done.'
|
fau-fablab/kastenwesen | test_cron.py | Python | gpl-3.0 | 4,191 | 0.000954 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from cron_status import *
class TestChangeDetection(unittest.TestCase):
"""Test if the change detection is operational."""
# Please note that status_history_list is backwards,
# i.e., newest entry first.
def test_all_okay(self):
... | {'foo': (ContainerStatus.OKAY, 'no msg')}
] * (STATUS_HISTORY_LENGTH + 1)
changed, status = detect_flapping_and_changes(status_history_list)
self.assertFalse(changed)
self.assertEqual(changed, status[0].changed) # because there is only 1 container
self.assertEqual(status[0].ove... | self.assertEqual(status[0].current_status, ContainerStatus.OKAY)
self.assertTrue(status[0].container_name in status_history_list[0])
self.assertEqual(status[0].current_msg, status_history_list[0][status[0].container_name][1])
def test_all_failed(self):
status_history_list = [
... |
wiltonlazary/arangodb | 3rdParty/V8/gyp/generator/eclipse.py | Python | apache-2.0 | 16,471 | 0.010685 | # Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""GYP backend that generates Eclipse CDT settings files.
This backend DOES NOT generate Eclipse CDT projects. Instead, it generates XML
files that can be importe... | te_dir in shared_intermediate_dirs:
for include_dir in include_dirs:
include_dir = include_dir.replace('$SHARED_INTERMEDIATE_DIR',
| shared_intermediate_dir)
if not os.path.isabs(include_dir):
base_dir = os.path.dirname(target_name)
include_dir = base_dir + '/' + include_dir
include_dir = os.path.abspath(include_dir)
gyp_includes_set.add(include_dir)
# Generate a list that ha... |
flowersteam/SESM | SESM/scene.py | Python | gpl-3.0 | 953 | 0.005247 | import time
import threading
import subprocess
i | mport pygame.locals
vlc_path = 'C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe'
class Scene(threading.Thread):
def __init__(self, screen, games, games_manager):
threading.Thread.__init__(self)
self.screen = screen
self.games = games
self.games_manager = games_m | anager
class DummyScene(Scene):
def run(self):
time.sleep(5)
class VideoScene(Scene):
def __init__(self, screen, games, games_manager, filename):
Scene.__init__(self, screen, games, games_manager)
self.filename = filename
def run(self):
subprocess.call([vlc_path, self.f... |
Baguage/django-google-analytics-id | tests/test_settings.py | Python | mit | 612 | 0.001634 | import os
BASE_DIR = os.path.dirname(os.path.dirname(os | .path.abspath(__file__)))
SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'analytics',
'tests'
]
ROOT_URLCONF = 'tests.urls'
TEMPLATES = [
{
'B... | jangoTemplates',
'APP_DIRS': True,
},
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
} |
jenniferwx/Programming_Practice | Permutations.py | Python | bsd-3-clause | 365 | 0.016438 | '''
Generate all permutations | of a given string
'''
def permutations(str):
if(len(str)==1):
return str[0]
permutation = permutations(str[1:])
word = str[0]
result = []
for perm in permutation:
for i in range(len(perm)+1): # note: len+1
| result.append(perm[:i]+word+perm[i:])
return result
|
imxiaohui/django-todolist-1 | lists/migrations/0003_auto_20150308_2120.py | Python | mit | 1,229 | 0.001627 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('lists', '0002_auto_20150301_1937'),
]
operations = [
migrations.AlterModelOptions(
... | s.AlterField(
| model_name='todolist',
name='creator',
field=models.ForeignKey(to=settings.AUTH_USER_MODEL, null=True, related_name='todolists'),
preserve_default=True,
),
]
|
williamleif/histwords | representations/cooccurgen.py | Python | apache-2.0 | 944 | 0.002119 | from collections import Counter
import numpy as np
def run(word_gen, index, window_size, out_file):
context = []
pair_counts = Counter()
for word in word_gen:
context.append(index[word])
if len(context) > window_size * 2 + 1:
context.pop(0)
pair_counts = _process_context... | "include_dirs": np.get_include()})
from representations import sparse_io
sparse_io.export_mat_from_dict(pair_counts, out_file)
def _process_context(context, pair_counts, window_size):
if len(con | text) < window_size + 1:
return pair_counts
target = context[window_size]
indices = range(0, window_size)
indices.extend(range(window_size + 1, 2 * window_size + 1))
for i in indices:
if i >= len(context):
break
pair_counts[(target, context[i])] += 1
return pair_c... |
osiloke/Flumotion-Transcoder | flumotion/transcoder/admin/transbalancer.py | Python | lgpl-2.1 | 4,755 | 0.001682 | # vi:si:et:sw=4:sts=4:ts=4
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L.
# Copyright (C) 2010,2011 Flumotion Services, S.A.
# All rights reserved.
#
# This file may be distributed and/or modified under the terms of
# the GNU Lesser General Public License version 2.1... | return
for tasks in self._workerTasks.itervalues():
if task in tasks:
tasks.remove(task)
self._current -= 1
| return
def balance(self):
def getSortedWorkers():
"""
Return all the workers with at least 1 free slot
with the ones with the most free slots first.
"""
lookup = dict([(w, float(len(t)) / w.getWorkerContext().getMaxTask())
... |
pombredanne/pythran | pythran/tests/test_spec_parser.py | Python | bsd-3-clause | 3,994 | 0.008763 | import unittest
import pythran
import os.path
#pythran export a((float,(int,uintp),str list) list list)
#pythran export a(str)
#pythran export a( (str,str), int, intp list list)
#pythran export a( float set )
#pythran export a( bool:str dict )
#pythran export a( float )
#pythran export a( int8[] )
#pythran export a( i... | thran export a( uint16 [::][])
#pythran export a( uint16 [:,:,:])
#pythran export | a( uint16 [:,::,:])
#pythran export a( uint16 [,,,,])
#pythran export a( (int32, ( uint32 , int64 ) ) )
#pythran export a( uint64:float32 dict )
#pythran export a( float64, complex64, complex128 )
class TestSpecParser(unittest.TestCase):
def test_parser(self):
real_path = os.path.splitext(os.path.realpath... |
racker/cloud-init-debian-pkg | cloudinit/config/cc_puppet.py | Python | gpl-3.0 | 5,166 | 0.000387 | # vi: ts=4 expandtab
#
# Copyright (C) 2009-2010 Canonical Ltd.
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
#
# Author: Scott Moser <scott.moser@canonical.com>
# Author: Juerg Haefliger <juerg.haefliger@hp.com>
#
# This program is free software: you can redistribute it and/or modify
# ... | # Expand %i as the instance id
v = v.replace("%i", cloud.get_instance_id())
# certname needs to be downcased
v = v.lower()
puppet_config.set(cfg_name, o, v)
# We got all our config as wanted w... | NF_PATH))
util.write_file(PUPPET_CONF_PATH, puppet_config.stringify())
# Set it up so it autostarts
_autostart_puppet(log)
# Start puppetd
util.subp(['service', 'puppet', 'start'], capture=False)
|
canvasnetworks/canvas | website/apps/activity/jinja_tags.py | Python | bsd-3-clause | 444 | 0.009009 | from jinja2 import Markup, contextfunction
from canvas.templatetags.jinja_base import (global_tag, filter_tag, render_jinja_to_string,
| jinja_context_tag, update_context)
@global_tag
def activity_stream_item(acti | vity, viewer):
ctx = {
'activity': activity,
'viewer': viewer,
}
return Markup(render_jinja_to_string(u'activity/types/{0}.html'.format(activity.TYPE), ctx))
|
mlperf/training_results_v0.6 | Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/python/tvm/autotvm/__init__.py | Python | apache-2.0 | 794 | 0.001259 | """The auto-tuning module of tvm
This module includes:
* Tuning space definition API
* Efficient auto-tuners
* Tuning result and database support
* Distributed measurement to scale up tuning
"""
from . import database
from . import feature
from . import measure
from . import record
from . import task
from . impor... | der, LocalRunner, RPCRunner
from .tuner import callback
from .task import template, get_config, create, | ConfigSpace, ConfigEntity, \
register_topi_compute, register_topi_schedule, \
DispatchContext, FallbackContext, ApplyHistoryBest as apply_history_best
from .env import GLOBAL_SCOPE
|
JIMyungSik/uftrace | tests/t145_longjmp3.py | Python | gpl-2.0 | 1,447 | 0.001382 | #!/usr/bin/env python
from runtest import TestBase
class TestCase(TestBase):
def __init__(self):
TestBase.__init__(self, 'longjmp3', """
# DURATION TID FUNCTION
1.164 us [ 4107] | __monstartup();
0.657 us [ 4107] | __cxa_atexit();
[ 4107] | main() {
0.705 us [ 4107] | _setjmp... | getpid();
[ 4107] | bar() {
[ 4107] | baz() {
[ 4107] | __longjmp_chk(2) {
1.282 us [ 4107] | } = 2; /* _setjmp */
0.540 us [ 4107] | getpid();
[ 4107] | foo() {
[ 4107] | __longjmp_chk(3) {
0.578 us [ 4107] | } = 3; /* _set... | | baz() {
[ 4107] | __longjmp_chk(4) {
0.642 us [ 4107] | } = 4; /* _setjmp */
18.019 us [ 4107] | } /* main */
""")
def build(self, name, cflags='', ldflags=''):
return TestBase.build(self, name, cflags + ' -D_FORTIFY_SOURCE=2', ldflags)
def runcmd(self):
args = ... |
hltbra/openxmllib | tests/test_wordprocessing.py | Python | gpl-2.0 | 1,363 | 0.003679 | # -*- coding: utf-8 -*-
"""
Testing WordProcessingDocument
"""
# $Id: test_wordprocessing.py 6355 2007-09-20 17:16:21Z glenfant $
import unittest
import os
from fixures import *
import openxmllib
class WordProcessingTest(unittest.TestCase):
"""Testing querying properties from a document"""
def setUp(self):
... | for word in some_words:
self.failUnless(word in itext, "%s was expected" % word)
return
def test_indexableTextNoprop(self):
"""Indexable text without properties"""
itext = self.doc.indexableText(include_properties=False)
some_words = (u'A', u'full', u'chàractèr... | word)
return
# /class WordProcessingTest
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(WordProcessingTest))
return suite
if __name__ == '__main__':
unittest.TextTestRunner().run(test_suite())
|
zeke8402/codingame-puzzles | medium/apu-init-phase/solution.py | Python | mit | 1,508 | 0.002653 | import sys
import math
# Don't let the machines win. You are humanity's last hope...
width = int(input()) # the number of cells on the X axis
height = int(input()) # the number of cells on the Y axis
Matrix = [[0 for x in range(height)] for x in range(width)]
# Creating the matrix
for i in range(height):
l... | "
break
else:
coordinates = coordinates + "-1 -1 "
k += 1
# Find Next Node to the Bottom
k = j+1
while k != height+1:
if k != height:
if Matrix[i][k] == '... | inates + str(i)+" " +str(k)+" "
break
else:
coordinates = coordinates + "-1 -1 "
k += 1
cArray.append(coordinates)
for c in cArray:
print(c) |
Forage/Gramps | gramps/gui/editors/editpersonref.py | Python | gpl-2.0 | 6,336 | 0.004735 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2007 Donald N. Allingham
# 2009 Gary Burton
# Copyright (C) 2011 Tim G L Lyons
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published ... | notetype=NoteType.ASSOCIATION)
s | elf._add_tab(notebook, self.note_tab)
self.track_ref_for_deletion("note_tab")
self._setup_notebook_tabs(notebook)
notebook.show_all()
self.top.get_object('vbox').pack_start(notebook, True, True, 0)
def build_menu_names(self, obj):
return (_('Person Reference'),_('Person Ref... |
SeungGiJeong/SK_FastIR | memory/windows2012ServerR2Memory.py | Python | gpl-3.0 | 440 | 0.002273 | from __future__ import unicode_literals
from memory.mem import _Memory |
class Windows2012ServerR2Memory(_Memory):
def __init__(self, params):
super(Windows2012ServerR2Memory, self).__init__(params)
def csv_all_modules_dll(self):
super(Windows2012ServerR2Memory, self)._csv_all_modules_dll()
def csv_all_modules_opened_files(self):
| super(Windows2012ServerR2Memory, self)._csv_all_modules_opened_files() |
wrobell/geocoon | geocoon/tests/test_core.py | Python | gpl-3.0 | 9,461 | 0.003065 | #
# GeoCoon - GIS data analysis library based on Pandas and Shapely
#
# Copyright (C) 2014 by Artur Wroblewski <wrobell@pld-linux.org>
#
# 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 ve... | )
def test_fetch_attr(self):
"""
Test fetch GIS properties from GIS | series
"""
data = [Point(v, v * 2) for v in [1, 2]]
series = PointSeries(data)
y = fetch_attr(series, name='y')
self.assertTrue(all(y == [2, 4]))
def test_select(self):
"""
Test selecting from GIS series
"""
data = [Point(v, v * 2) for v in ... |
camptocamp/QGIS | python/plugins/processing/saga/SplitRGBBands.py | Python | gpl-2.0 | 3,715 | 0.005922 | # -*- coding: utf-8 -*-
"""
***************************************************************************
SplitRGBBands.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*************************... | temp = os.path.join(os.path.dirname(temp), safeBasename)
r = self.getOutputValue(SplitRGBBands.R)
g = self.getOutputValue(SplitRGBBands.G)
b = self.getOutputValue(SplitRGBBands.B) |
commands = []
if isWindows():
commands.append("io_gdal 0 -GRIDS \"" + temp + "\" -FILES \"" + input+"\"")
commands.append("io_gdal 1 -GRIDS \"" + temp + "_0001.sgrd\" -FORMAT 1 -TYPE 0 -FILE \"" + r + "\"");
commands.append("io_gdal 1 -GRIDS \"" + temp + "_0002.sgrd\... |
AndrewWalker/ccsyspath | ccsyspath/paths.py | Python | mit | 1,112 | 0.005396 | import subprocess
from subprocess import Popen, PIPE
import os
import re
def compiler_preprocessor_verbose(compiler, extraflags):
"""Capture the compiler preprocessor stage in verbose mode
"""
lines = []
with open(os.devnull, 'r') as devnull:
cmd = [compiler, '-E']
cmd += extraflags
... | .strip() for line in lines ]
start = lines.index('#include <...> search starts here:')
end = lines.index('End of search list.')
lines = lines[start+1:end]
paths = []
for line in lines:
line = li | ne.replace('(framework directory)', '')
line = line.strip()
paths.append(line)
return paths
|
Juanlu001/pfc | demo/aquaclient.py | Python | gpl-3.0 | 883 | 0.002265 | # coding: utf-8
"""Client program.
How to collect data:
1. Positions received | as a list of points
2. Interpolate function (probably unstructured grid, see scipy.interpolate.griddata)
3. Evaluate function on points coming from the FEniCS mesh
4. Restore the values onto the array of a FEniCS function in the proper order
Hint: http://fenicsproject.org/qa/3975/interpolating-vector-function-from-pyt... | ort pprint
# Socket to talk to server
context = zmq.Context()
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:5556")
print("Collecting data...")
dt = 0.1 # s
t_aim = 0.0 # s
# Collect all
while True:
# We first initialize the server
socket.send_pyobj({'time': t_aim})
t_aim += dt
... |
rsalmaso/django-allauth | allauth/socialaccount/providers/paypal/tests.py | Python | mit | 613 | 0 | from allauth.socialaccount.tests imp | ort OAuth2TestsMixin
from allauth.tests import MockedResponse, TestCase
from .provider import PaypalProvider
class PaypalTests(OAuth2TestsMixin, TestCase):
provider_id = PaypalProvider.id
def get_mocked_response(self):
return MockedResponse(
200,
"""
{
"us... | "family_name": "Doe",
"email": "janedoe@example.com"
}
""",
)
|
vahana/prf | prf/tests/test_exc.py | Python | mit | 2,450 | 0.015102 | import mock
import json
import pytest
import prf.exc
def fake_resp(code):
return mock.MagicMock(
code = str(code),
status_code = code,
headers = [],
title = 'title',
detail = 'detail',
expl | anation = 'explanation'
)
class TestExc(object):
@mock.patch('prf.exc.log_exception')
def test_create_response(self, fake_log_exception):
out = prf.exc.create_response(fake_resp(200), {})
assert fake_log_exception.call_count == 0
# Temporarily pop timestamp, we need to freeze time ... | 'code': '200',
'detail': 'detail',
'title': 'title'
} == d
assert out.content_type == 'application/json'
@mock.patch('prf.exc.add_stack')
@mock.patch('prf.exc.logger')
def test_log_exception(self, fake_logger, fake_add_stack):
request = mock.MagicMock(... |
AdaHeads/Coverage_Tests | disabled_tests/incoming_calls.py | Python | gpl-3.0 | 9,794 | 0.027159 | # -*- coding: utf-8 -*-
import logging
from pprint import pformat
from time import clock, sleep
try:
import unittest2 as unittest
except ImportError:
import un | ittest
import config
from event_stack import TimeOutReached
from database_reception import Database_Reception
from static_agent_pools import Receptionists, Customers
logging.basicConfig (level = logging.INFO)
class Test_Case (unittest.TestCase):
Caller | = None
Receptionist = None
Receptionist_2 = None
Callee = None
Reception_Database = None
Reception = None
Start_Time = None
Next_Step = 1
def Preconditions (self, Reception):
self.Start_Time = clock ()
self.Next_Step = ... |
ricrdo/puuch | puuch/wsgi.py | Python | mit | 1,416 | 0.000706 | """
WSGI config for puuch project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level varia | ble
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom | one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi pro... |
alirizakeles/zato | code/zato-server/src/zato/server/service/internal/security/vault/policy.py | Python | gpl-3.0 | 154 | 0 | # -*- coding: utf-8 -*-
|
"""
Copyright (C) 2016, Zato Source s.r.o. https://zato.io
Licensed under LGPLv3, see LICENSE.txt for terms and conditions.
"""
| |
Kazade/NeHe-Website | google_appengine/google/appengine/api/memcache/__init__.py | Python | bsd-3-clause | 52,152 | 0.004429 | #!/usr/bin/env python
#
# Copyright 2007 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 o... | pickle.PicklingError: If the value is not a string and could not be pickled.
RuntimeError: If a complicated data structure could not be pickled due to
too many levels of recursion in its composition.
"""
flags = 0
stored_value = value
if isinstance(value, str):
pass
elif isinstance(value, u... | PE_UNICODE
elif isinstance(value, bool):
stored_value = str(int(value))
flags |= TYPE_BOOL
elif isinstance(value, int):
stored_value = str(value)
flags |= TYPE_INT
elif isinstance(value, long):
stored_value = str(value)
flags |= TYPE_LONG
else:
stored_value = do_pickle(value)
f... |
jacquev6/Pynamixel | Pynamixel/instructions/bus_tests.py | Python | mit | 3,416 | 0.001464 | # coding: utf8
# Copyright 2015 Vincent Jacques <vincent@vincent-jacques.net>
import unittest
import MockMockMock
from ..bus import Bus
from .ping import Ping
from .read_data import ReadData
from .write_data import WriteData
from .reg_write import RegWrite
from .action import Action
from .reset import Reset
from .s... | rdware.expect.send([0xFF, 0xFF, 0x01, 0x04, 0x02, 0x2B, 0x01, 0xCC])
self.hardware.expect.receive(4).and_return([0xFF, 0xFF, 0x01, 0x03])
self.hardware.expect.receive(3).and_return([0x00, 0x20, 0xDB])
ident, error, response = self.bus.send(0x01, ReadData(0x2B))
self.assertEqual(response.... | 11, 0x12, 0x97])
self.hardware.expect.receive(4).and_return([0xFF, 0xFF, 0x07, 0x02])
self.hardware.expect.receive(2).and_return([0x00, 0xF6])
self.bus.send(0x01, WriteData(0x2B, [0x10, 0x11, 0x12]))
def test_reg_write(self):
self.hardware.expect.send([0xFF, 0xFF, 0x01, 0x06, 0x04, ... |
subeax/grab | test/case/selector_kit.py | Python | mit | 3,668 | 0.004635 | # coding: utf-8
from unittest import TestCase
#import os
#import sys
#root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
#sys.path.insert(0, root)
from test.util import GRAB_TRANSPORT, ignore_transport, only_transport
from test.server import SERVER
from grab.selector import KitSelector
from grab impo... | yquery='body')[0].select(pyquery='#6')[0].node.text)
def test_select_select(self):
root = KitSelector(self.qt_doc)
self.assertEquals(set(['one', 'yet one']),
set([x.text() for x in root.select('ul').select('li:first-child')]),
)
def test_text... | sertEquals(set(['one', 'yet one']),
set(root.select('ul > li:first-child').text_list()),
)
def test_attr_list(self):
root = KitSelector(self.qt_doc)
self.assertEquals(set(['li-1', 'li-2']),
set(root.select('ul[id=second-l... |
OpenMined/PySyft | packages/syft/tests/syft/lib/python/string/string_serde_test.py | Python | apache-2.0 | 780 | 0 | # syft absolute
import syft as sy
from syft.lib.python.string import String
from syft.proto.lib.python.string_pb2 import String as String_PB
def test_string_serde() -> None:
syft_string = String("Hello OpenMi | ned")
serialized = syft_string._object2proto()
assert isinstance(seri | alized, String_PB)
deserialized = String._proto2object(proto=serialized)
assert isinstance(deserialized, String)
assert deserialized.id == syft_string.id
def test_string_send(client: sy.VirtualMachineClient) -> None:
syft_string = String("Hello OpenMined!")
ptr = syft_string.send(client)
# ... |
ibc/MediaSoup | worker/deps/gyp/test/mac/gyptest-app-assets-catalog.py | Python | isc | 4,164 | 0.010567 | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that app bundles are built correctly.
"""
from __future__ import print_function
import TestGyp
import TestMac
import os
impo... | ath.join(dirpath, f)[len(path) + 1:])
return result
# Xcode supports for assets catalog was introduced in Xcode 6.0
if sys.platform == 'darwin' and TestMac.Xcode.Version() >= '0600':
test_gyp_path = 'test-assets-catalog. | gyp'
test_app_path = 'Test App Assets Catalog Gyp.app'
test = TestGyp.TestGyp(formats=['ninja', 'make', 'xcode'])
test.run_gyp(test_gyp_path, chdir='app-bundle')
test.build(test_gyp_path, test.ALL, chdir='app-bundle')
# Binary
test.built_file_must_exist(
os.path.join(test_app_path, 'Contents/MacOS/T... |
haphaeu/yoshimi | mth/MultiThread_ClientPool.py | Python | lgpl-3.0 | 1,065 | 0.019718 | import threading
import Queue
from random import random
theVar = 0
class MyThread ( threading.Thread ):
def run ( self ):
global theVar
while True:
client=myPool.get()
print '- iniciando thread-'
if client=='stop':
print 'Thread terminou <-'
... | threads
NUMTHREADS = 3
NUMPROCESSES=20
#create a pool manager
myPool = Queue.Queue(0)
#starts only 2 threads
for x in xrange (NUMTHREADS):
print '-> Iniciando thread', x
MyThread().start()
#pass data into thread pool
#and run thread a couple of times
for x in xrange(NUMPROCESSES):
print '- passando dados ... | a thread -'
myPool.put('dummy')
#stop the threads
for x in xrange(NUMTHREADS):
print '- Stopping thread -'
myPool.put('stop')
|
talon-one/talon_one.py | test/test_attributes_mandatory.py | Python | mit | 2,093 | 0.0043 | # coding: utf-8
"""
Talon.One API
The Talon.One API is used to manage applications and campaigns, as well as to integrate with your application. The operations in the _Integration API_ section are used to integrate with our platform, while the other operations are used to manage applications and campaigns. #... | y unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional):
"""Test AttributesMandatory
include_option is a boolean, when False only required
params are included, when True both required and
opt... | # model = talon_one.models.attributes_mandatory.AttributesMandatory() # noqa: E501
if include_optional :
return AttributesMandatory(
campaigns = [
'0'
],
coupons = [
'0'
]
... |
jawilson/home-assistant | tests/components/recorder/test_statistics.py | Python | apache-2.0 | 24,602 | 0.001179 | """The tests for sensor recorder platform."""
# pylint: disable=pro | tected-access,invalid-name
from datetime import timedelta
from unittest.mock import patch, sentinel
import pytest
from pytest import approx
from homeassistant.components.recorder import history
from homeassistant.components.recorder.const import DATA_INSTANCE
from homeassistant.components.re | corder.models import (
StatisticsShortTerm,
process_timestamp_to_utc_isoformat,
)
from homeassistant.components.recorder.statistics import (
async_add_external_statistics,
get_last_short_term_statistics,
get_last_statistics,
get_metadata,
list_statistic_ids,
statistics_during_period,
)
f... |
perryl/morph | morphlib/git.py | Python | gpl-2.0 | 10,923 | 0.000275 | # Copyright (C) 2011-2016 Codethink Limited
#
# 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; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but... | s found.'''
if 'GIT_AUTHOR_EMAIL' in os.environ:
return os.environ['GIT_AUTHOR_EMAIL'].strip()
try:
cfg = check_config_set(runcmd, keys={"user.email": "me@example.com"})
return cfg['user.email']
except ConfigNotSetException as e:
raise IdentityNotSetException(e.missing)
def ... | lue = gitcmd(runcmd, 'config', key, cwd=cwd,
print_command=False).strip()
found[key] = value
except cliapp.AppException:
missing.append(key)
if missing:
raise ConfigNotSetException(missing, keys)
return found
def copy_repository(runcmd, repo,... |
yishayv/lyacorr | mpi_helper.py | Python | mit | 2,068 | 0 | from __future__ import print_function
import time
import numpy as np
from mpi4py import MPI
from python_compat import range
comm = MPI.COMM_WORLD
def r_print(*args):
"""
print message on the root node (rank 0)
:param args:
:return:
"""
if comm.rank == 0:
print(' | ROOT:', end=' ')
for i in args:
print(i, end=' ')
# noinspection PyArgumentList
print()
def l_print(*args):
"""
print message on each node, synchronized
:param args:
:return:
"""
for rank in range(0, comm.size):
comm.Barrier()
if rank == comm... | "
print message on each node
:param args:
:return:
"""
print(comm.rank, ':', end=' ')
for i in args:
print(i, end=' ')
# noinspection PyArgumentList
print()
def get_chunks(num_items, num_steps):
"""
divide items into n=num_steps chunks
:param num_items:
:param n... |
YaleDHLab/image-segmentation | yale_daily_news/segment_ydn_images.py | Python | mit | 24,116 | 0.011403 | from __future__ import division
from multiprocessing import Pool
from collections import defaultdict
from skimage import io
from scipy import ndimage
from shutil import Error, move, rmtree
import numpy as np
import glob, os, codecs, sys, json
'''
## Processing notes
The Alto XML structure is as follows:
Each `root_d... | of the articles in that XML document
'''
articles = []
for i in xml_content.split('< | article')[1:]:
article_start = '>'.join(i.split('>')[1:])
article_content = article_start.split('</article')[0]
articles.append(article_content)
return articles
def get_article_clips(article, restrict_to_uc=1):
'''
Read in the xml content from an article and return an array of
the clips in that a... |
diefenbach-fz/lfs-downloadable-products | lfs_downloadable_products/templatetags/lfs_downloadable_products_tags.py | Python | bsd-3-clause | 954 | 0.002096 | # django imports
from django.contrib.sites.models import Site
from django.template import Library
from django.utils.safestring import mark_safe
from lfs_downloadable_products import views
register = Library()
@register.simple_tag(takes_context=True)
def manage_attachments(context, product):
request = context.get... | roductUrl
urls = []
exists = {}
for url in ProductUrl.objects.filter(order= | order).order_by("-creation_date"):
if url.attachment.id not in exists:
urls.append(url)
exists[url.attachment.id] = 1
return {
"urls": urls,
"domain": Site.objects.get_current().domain,
}
|
morenopc/edx-platform | lms/djangoapps/django_comment_client/forum/views.py | Python | agpl-3.0 | 18,118 | 0.004029 | import json
import logging
import xml.sax.saxutils as saxutils
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.core.context_processors import csrf
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from django.views.decor... | id)
with newrelic.agent.FunctionTrace(nr_transaction, "get_discussion_category_map"):
category_map = utils.get_discussion_category_map(course)
try:
unsafethreads, query_params = get_threads(request, course_id) # This might process a search query
threads = [utils.safe_content(thread) f... | unsafethreads]
except cc.utils.CommentClientMaintenanceError:
log.warning("Forum is in maintenance mode")
return render_to_response('discussion/maintenance.html', {})
user = cc.User.from_django_user(request.user)
user_info = user.to_dict()
with newrelic.agent.FunctionTrace(nr_transacti... |
moonbury/notebooks | github/MatplotlibCookbook/Chapter 6/06.py | Python | gpl-3.0 | 748 | 0.025401 | import numpy
from matplotlib import pyplot as plot
import matplotlib.cm as cm
def iter_count(C, max_iter):
X = C
for n in range(max_iter):
if abs(X) > 2.:
return n
X = X ** 2 + C
return max_iter
N = 512
max | _iter = 64
xmin, xmax, ymin, ymax = -0.32, -0.22, 0.8, 0.9
X = numpy.linspace(xmin, xmax, N)
Y = numpy.linspace(ymin, ymax, N)
Z = numpy.empty((N, N))
for i, y in enumerate(Y):
for j, x in enumerate(X):
Z[i, j] = iter_count(complex(x, y), max_iter)
plot.imshow(Z,
cmap = cm.binary,
interpol... | el(ct, fmt='%d')
plot.show()
|
Spirotot/py3status | py3status/modules/vnstat.py | Python | bsd-3-clause | 4,225 | 0.000237 | # -*- coding: utf-8 -*-
"""
Display vnstat statistics.
Coloring rules.
If value is bigger that dict key, status string will turn to color, specified
in the value.
Example:
coloring = {
800: "#dddd00",
900: "#dd0000",
}
(0 - 800: white, 800-900: yellow, >900 - red)
Format of s... | "
Get stati | stics from devfile in list of lists of words
"""
def filter_stat():
out = check_output(["vnstat", "--dumpdb"]).decode("utf-8").splitlines()
for x in out:
if x.startswith("{};0;".format(statistics_type)):
return x
try:
type, number, ts, rxm, txm, rxk, txk,... |
chilleo/ALPHA | CommandLineFiles/RunDGEN.py | Python | mit | 100,444 | 0.004888 | import re
import os
import itertools
import time
from string import upper
import ete3
import copy
import subprocess
from collections import defaultdict
from sys import platform
from scipy import stats
from ete3 import Tree
from natsort import natsorted
from Bio import AlignIO
"""
Functions:
~
Chabrielle Allen
Travis... | ting((alignments_to_DGEN, alignments_to_windows_to_DGEN), plot, meta)
|
return s
def calculate_windows_to_DGEN(alignments, taxa_order, outgroup, list_of_tree_and_net_invariants, window_size, window_offset,
verbose= False, alpha=0.01):
"""
Calculates the DGEN statistic for the given alignment
Input:
alignment --- a sequence alignment in phy... |
camilonova/django | tests/gis_tests/test_data.py | Python | bsd-3-clause | 2,588 | 0.000386 | """
This module has the mock object definitions used to hold reference geometry
for the GEOS and GDAL tests.
"""
import json
import os
from django.utils.functional import cached_property
# Path where reference test data is located.
TEST_DATA = os.path.join(os.path.dirname(__file__), 'data')
def tuplize(seq):
"T... | so coordinate test cases will match (JSON has no
# concept of tuple).
if coords:
self.coords = tuplize(coords)
if centroid:
self.centroid = tuple(centroid)
if ext_ring_cs:
ext_ring_cs = tuplize(ext_ring_cs)
self.ext_ring_cs = ext_ring_cs
... | _init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, [TestGeom(**strconvert(kw)) for kw in value])
class TestDataMixin:
"""
Mixin used for GEOS/GDAL test cases that defines a `geometries`
property, which returns and/or loads the reference geometry data.
"""... |
mbonix/yapr | android/PyLocale.py | Python | mit | 2,023 | 0.002472 | """ A location-aware script to manage ringer volume """
__author__ = 'Marco Bonifacio <bonifacio.marco@gmail.com>'
__license__ = 'MIT License'
impo | rt android
import time
# Parameters
SSID = {'bonix-lan': 'casa',
'ZENIT SECURED WPA': 'lavoro'}
RINGER = {'casa': 5,
'lavoro': 2,
'sconosciuto': 5}
# Functions
def check_ssid(droid):
""" Check if wireless network SSID is known.
Args:
droid: an Android instance.
Returns:... | environment. """
state = 'sconosciuto'
try:
lwifi = droid.wifiGetScanResults().result
lssid = [w['ssid']for w in lwifi]
for s in lssid:
if s in SSID:
state = SSID[s]
except Exception, e:
droid.notify('PyLocale', 'Errore: {}'.format(e))
finally... |
sociam/indx | apps/fitbit/bin/fitbit/fitbit_intraday.py | Python | agpl-3.0 | 3,324 | 0.007822 | from fitbit import Fitbit
from datetime import date, datetime, time, timedelta
import json
# '''merges two response dicts based on the keys'''
# def combine(a, b):
# c = {}
# for key in a.keys():
# if (key.endswith('-intraday')):
# c[key] = a[key]
# c[key]['dataset'].extend(b[ke... | out.append(self.get_day_time_series(resource_path, next, format))
next = next + delta
out.append(self.get_time_interval_time_series(resource_path, to_datetime.date(), time(0, 0), to_datetime.time(), format))
return out
def g | et_day_time_series(self, resource_path, date=date.today(), format='json'):
url = "/1/user/-/{0}/date/{1}/1d/1min.{2}".format(resource_path, date.isoformat(), format)
data = self.fitbit.call_get_api(url)
return json.loads(data)
def get_time_interval_time_series(self, resource_path, date=date... |
joelagnel/ns-3 | bindings/python/apidefs/gcc-LP64/ns3_module_energy.py | Python | gpl-2.0 | 54,425 | 0.016628 | from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers
def register_types(module):
root_module = module.get_root()
## device-energy-model-container.h: ns3::DeviceEnergyModelContainer [class]
module.add_class('DeviceEnergyModelContainer')
## energy-model-helper.h: ns3::De... | ule):
root_module = module.get_root()
def register_types_ns3_aodv(module):
root_module = module.get_root()
def register_types_ns3_dot11s(module):
root_module = module.get_root()
def register_types_ns3_dsdv(module):
root_module = module.get_root()
def register_types_ns | 3_flame(module):
root_module = module.get_root()
def register_types_ns3_internal(module):
root_module = module.get_root()
def register_types_ns3_olsr(module):
root_module = module.get_root()
def register_methods(root_module):
register_Ns3DeviceEnergyModelContainer_methods(root_module, ... |
Nikea/VisTrails | vistrails/db/versions/v0_9_3/persistence/xml/auto_gen.py | Python | bsd-3-clause | 66,772 | 0.005571 | ###############################################################################
##
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## "Redistribution and use in source and binary for... | =type,
spec=spec)
obj.is_d | irty = False
return obj
def toXML(self, portSpec, node=None):
if node is None:
node = ElementTree.Element('portSpec')
# set attributes
node.set('id',self.convertToStr(portSpec.db_id, 'long'))
node.set('name',self.convertToStr(portSpec.db_name, 'str')... |
jiadaizhao/LeetCode | 1401-1500/1451-Rearrange Words in a Sentence/1451-Rearrange Words in a Sentence.py | Python | mit | 513 | 0.001949 | import collections
class Solution:
def arrangeWords(self, text: str) -> str:
words = text.split()
table = collections.defaultdict(list)
for word in words:
table[len(word)].append(word)
result = []
for key in sorted(table):
result.extend(table[key])
|
return ' '.join(result).capitalize()
# Sort is stable
class Solution2:
def arrangeWords(self, text: str) -> str | :
return ' '.join(sorted(text.split(), key=len)).capitalize()
|
SoftwareDefinedBuildings/bw2-contrib | driver/emu2/driver.py | Python | gpl-3.0 | 2,380 | 0.007143 | # EMU code from https://github.com/rainforestautomation/Emu-Serial-API
from emu import *
import sys
import json
import msgpack
from xbos import get_client
from bw2python.bwtypes import PayloadObject
import time
with open("params.json") as f:
try:
params = json.loads(f.read())
except ValueError as e:
... | nt(d.Demand, 16)
print dir(emu_instance)
# handle current summation
if hasattr(emu_instance, "CurrentSummationDelivered"):
d = emu_instance.CurrentSummationDelivered
multiplier = int(d.Multiplier, 16)
divisor = float(int(d.Divisor, 16))
msg['current_summation_delivered'] = in... | or
msg['current_summation_received'] = int(d.SummationReceived, 16) * multiplier / divisor
send_message(msg)
emu_instance.stop_serial()
|
jolyonb/edx-platform | openedx/core/djangoapps/schedules/content_highlights.py | Python | agpl-3.0 | 4,066 | 0.000492 | """
Contains methods for accessing weekly course highlights. Weekly highlights is a
schedule experience built on the Schedules app.
"""
from __future__ import absolute_import
import logging
from courseware.model_data import FieldDataCache
from courseware.module_render import get_module_for_descriptor
from openedx.cor... |
def _get_course_descriptor(course_key):
course_descriptor = modulestore().get_course(course_key, depth=1)
if course_descriptor is None:
raise CourseUpdateDoesNotExist(
u"Course {} not found.".format(course_key)
)
return course_descriptor
def _get_course_module(course_descrip... |
# Now evil modulestore magic to inflate our descriptor with user state and
# permissions checks.
field_data_cache = FieldDataCache.cache_for_descriptor_descendents(
course_descriptor.id, user, course_descriptor, depth=1, read_only=True,
)
return get_module_for_descriptor(
user, req... |
TerryHowe/ansible-modules-hashivault | ansible/modules/hashivault/hashivault_approle_role_get.py | Python | mit | 1,659 | 0.001206 | #!/usr/bin/env python
from ansible.module_utils.hashivault import hashivault_argspec
from ansible.module_utils.hashivault import hashivault_auth_client
from ansible.module_ut | ils.hashivault import hashivault_init
from ansible.module_utils.hashivault import hashiwrapper
ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'community', 'version': '1.1'}
DOCUMENTATION = '''
---
module: hashivault_approle_role_get
version_added: "3.8.0"
short_description: Hashicorp Vault approle ... | e from Hashicorp Vault.
options:
name:
description:
- role name.
mount_point:
description:
- mount point for role
default: approle
extends_documentation_fragment: hashivault
'''
EXAMPLES = '''
---
- hosts: localhost
tasks:
- hashivault_approle_role_get:
... |
mattwaite/CanvasStoryArchive | stories/migrations/0001_initial.py | Python | mit | 1,746 | 0.001718 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
| dependencies = [
]
operations = [
migrations.CreateModel(
name='Entity',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('entity_name', models.CharField(max_length=255)),
... | migrations.CreateModel(
name='EntityType',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('entity_type', models.CharField(max_length=255)),
('entity_type_slug', models.SlugField()... |
xanthospap/chaos-ngpt | mipy/class-static-mths.py | Python | gpl-3.0 | 2,368 | 0.010557 | #! /usr/bin/python
class A1(object):
def method(*argv): return argv
a = A1()
print 'Call a.method() ->', a.method()
print 'Call a.method(1,2,3) ->', a.method(1,2,3)
print '''
!! Note that the \'a\' instance is passed (implicitely) as the first
!! function parameter (something like <__main__.A1 ob... | tance is ignored except for its class.
'''
class A2(object):
@staticmethod
def method(*argv): return argv
a = A2()
print 'Call a.method() ->', a.method()
print 'Call a.method(1,2,3) ->', a.method(1,2,3)
print 'Call A.method(1,2,3) | ->', A2.method(1,2,3) ## static call
print '''
!! Note that no class instance is is passed to the call
'''
''' So in a normal (class) bound method call, the instance is passed implicitely
as the first argument, whereas for a static method no implicit arguments are
passed; the method is invoked via ... |
haoyuchen1992/modular-file-renderer | tests/server/handlers/test_render.py | Python | apache-2.0 | 344 | 0 | import mfr
import json
from tests import utils
from tornado import testing
class TestRenderHandler(u | tils.HandlerTestCase):
@testing.gen_test
def test_options_skips_prepare(self):
# Would crash b/c lack of mocks
yield self.http_clie | nt.fetch(
self.get_url('/render'),
method='OPTIONS'
)
|
mitodl/bootcamp-ecommerce | applications/views.py | Python | bsd-3-clause | 9,919 | 0.001109 | """Views for bootcamp applications"""
from collections import OrderedDict
import re
from django.db.models import Count, Subquery, OuterRef, IntegerField, Prefetch, Q
from django.shortcuts import get_object_or_404
from django.views.generic import TemplateView
from django_filters.rest_framework import DjangoFilterBacken... | TP_201_CREATED if created else status.HTTP_200_OK),
)
class ReviewSubmissionPagination(LimitOffsetPagination):
"""Pagination class for ReviewSubmissionViewSet"""
default_limit = 10
max_limit = 1000
facets = {}
def paginate_queryset(self, queryset, request, view=None):
"""Paginate... | elf.facets = self.get_facets(queryset)
return super().paginate_queryset(queryset, request, view=view)
def get_paginated_response(self, data):
"""Return a paginationed response, including facets"""
return Response(
OrderedDict(
[
("count", self... |
b3j0f/utils | b3j0f/utils/ut.py | Python | mit | 5,685 | 0.000176 | # -*- coding: utf-8 -*-
# --------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2014 Jonathan Labéjof <jonathan.labejof@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation fi... | urn result
class UTCase(TestCase):
"""Class which enrichs TestC | ase with python version compatibilities."""
def __init__(self, *args, **kwargs):
super(UTCase, self).__init__(*args, **kwargs)
if PY2: # python 3 compatibility
if PY26: # python 2.7 compatibility
def assertIs(self, first, second, msg=None):
return self.assertTr... |
BiuroCo/mega | bindings/doc/java/sphinx/source/conf.py | Python | bsd-2-clause | 11,589 | 0.006385 | # -*- coding: utf-8 -*-
#
# javauserguide documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 21 21:46:23 2015.
#
# 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.... | time format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered ... | aps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST ... |
tzpBingo/github-trending | codespace/python/tencentcloud/tcm/v20210413/tcm_client.py | Python | mit | 3,255 | 0.002476 | # -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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... | :param request: Request instance for DescribeMesh.
:type request: :class:`tencentcloud.tcm.v20210413.models.DescribeMeshRequest`
:rtype: :class:`tencentcloud.tcm.v20210413.models.DescribeMeshResponse`
"""
try:
param | s = request._serialize()
body = self.call("DescribeMesh", params)
response = json.loads(body)
if "Error" not in response["Response"]:
model = models.DescribeMeshResponse()
model._deserialize(response["Response"])
return model
... |
cfelton/myhdl_exercises | support/mysigs.py | Python | mit | 2,461 | 0.002438 |
from __future__ import division
import myhdl
from myhdl import instance, delay
ClockList = []
class Clock(myhdl.SignalType):
def __init__(self, val, frequency=1, timescale='1ns'):
self._frequency = frequency
self._period = 1/frequency
self._timescale = timescale
self._htick... | timescale(self, t):
self._timescale = t
@property
def frequency(self):
return self._frequency
@frequenc | y.setter
def frequency(self, f):
self._frequency = f
self._period = 1/f
self._set_hticks()
@property
def period(self):
return self._period
def _set_hticks(self):
# self._nts = self._convert_timescale(self._timescale)
# self._hticks = int(round(se... |
doirisks/dori | models/10.1016:S0140-6736(09)60443-8/model.py | Python | gpl-3.0 | 3,494 | 0.010876 | """
model.py
by Ted Morin
contains a function to predict 10-year Atrial Fibrilation risks using beta coefficients from
10.1016:S0140-6736(09)60443-8
2010 Development of a Risk Score for Atrial Fibrillation in the Community
Framingham Heart Study
translated and optimized from FHS online risk calculator's javascript
... | nvert seconds to milliseconds as used in regression
pr_intv = pr_intv * 1000.0
# inexplicable conversion
pr_intv = pr_intv / 10.0
# this was done in the js, and the output seems much more realistic than otherwise, but it seems inexplicable!
# perhaps the coefficient shown in FHS's website is... | #gender
0.150520, #age
0.019300, #bmi Body Mass Index
0.00615, #sbp Systolic Blood Pressure
0.424100, #hrx Treatment for hypertension
0.070650, #pr_intv ... |
wbinventor/openmc | tests/unit_tests/test_universe.py | Python | mit | 2,900 | 0 | import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set... | iv.get_all_materials().values())
assert not (test_mats ^ set(mats))
def test_get_all_universes():
c1 = openmc.Cell()
u1 = openmc.Universe(cells=[c1])
c2 = openmc.Cell()
u2 = openmc.Universe(cells=[c2])
c3 = openmc.Cell(fill=u1)
c4 = openmc.Cell(fill=u2)
u3 = openmc.Universe(cells=[c3, ... | t(u3.get_all_universes().values())
assert not (univs ^ {u1, u2})
def test_create_xml(cell_with_lattice):
cells = [openmc.Cell() for i in range(5)]
u = openmc.Universe(cells=cells)
geom = ET.Element('geom')
u.create_xml_subelement(geom)
cell_elems = geom.findall('cell')
assert len(cell_ele... |
mne-tools/mne-tools.github.io | stable/_downloads/3d312e85f6ffa492419d3828dd31227d/dics_source_power.py | Python | bsd-3-clause | 3,552 | 0 | """
.. _ex-inverse-source-power:
==========================================
Compute source power using DICS beamformer
==========================================
Compute a Dynamic Imaging of Coherent Sources (DICS) :footcite:`GrossEtAl2001`
filter from single-trial activity to estimate source power across a frequency... | aw just for speed here
raw = mne.io.read_raw_fif(raw_fname)
raw.crop(0, 120) # one minute for speed (looks similar to using all ~800 sec)
# Read epochs
events = mne.find_events(raw)
epochs = mne.Epochs(raw, events, event_id=1, tmin=-1.5, tmax=2, preload=True)
del raw
# Paths to forward operator and FreeSurfer subje... | oin(data_path, 'derivatives', 'freesurfer', 'subjects')
# %%
# We are interested in the beta band. Define a range of frequencies, using a
# log scale, from 12 to 30 Hz.
freqs = np.logspace(np.log10(12), np.log10(30), 9)
# %%
# Computing the cross-spectral density matrix for the beta frequency band, for
# different ti... |
d15123601/geotinkering | make_shpfile.py | Python | mit | 1,216 | 0.005757 | """
This is for taking a json file and putting it into a shapefile.
It uses the generic functions written by mfoley.
"""
from geo_utils import get_data_f | rom_geoserver
import json
import six
from fiona import collection
import pyproj
from shapely.geometry import Point, mapping
op_file = "museums.shp"
server = "mf2.dit.ie:8080"
dbase = "dit:dublin_museums"
crs_from = pyproj.Proj("+init=EPSG:4326")
crs_to = pyproj.Proj("+init=EPSG:2157")
museums = get_data_from_geose... | ometry': 'Point', 'properties': { 'name': 'str' } }
with collection(
op_file, "w", "ESRI Shapefile", schema) as output:
for k, v in pts.items():
x, y = pyproj.transform(crs_from, crs_to, v[0], v[1])
point = Point(x, y)
output.write({'properties': {'name': k},'geometry': mapping(point)})
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.