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 |
|---|---|---|---|---|---|---|---|---|
psathyrella/partis-deprecated | python/compare.py | Python | gpl-3.0 | 2,531 | 0.003556 | #!/usr/bin/env python
import argparse
import json
import csv
import sys
sys.path.append('python')
import plotting
import utils
from opener import opener
parser = argparse.ArgumentParser()
parser.add_argument('-b', action='store_true') # passed on to ROOT when plotting
parser.add_argument('--outdir', required=True)
... | ion (TGG)
tryp_reader = csv.reader(csv_file)
args.tryp_positions = {row[0]:row[1] for row in tryp_reader} # WARNING: this doesn't filter out the | header line
plotting.compare_directories(args)
|
WatSat-ADCS/Comm | test/test_comm.py | Python | mit | 1,077 | 0.004643 | """
integration test for arduino
NOTE: requires the arduino to be plugged in
"""
import unittest
from comp.comm import ADCSArduino
class TestComm(unittest.TestCase):
def setUp(self):
self.ard = ADCSArduino(pr="/dev/ttyACM0")
def tearDown(self):
self.ard.close_arduino_port()
def ... | .assertIsNotNone(data)
self.ard.close_arduino_port()
def test_cont_sample(self):
self.ard.open_arduino_port()
for i in range (5):
data = self.ard.get_sensor_data()
print data
self.assertIsNotNone(data)
self.ard.close_arduino_port()
def test_p... | self.ard.post_change(7)
# def test_workflow(self):
# TODO: test full workflow
# pass
if __name__ == "__main__":
unittest.main()
|
openstack/barbican | barbican/hacking/checks.py | Python | apache-2.0 | 7,978 | 0 | # Copyright (c) 2016, GohighSec
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | e for the specific language governing permissions and limitations
# under the License.
import ast
import re
import six
from hacking import core
import pycodestyle
"""
Guide | lines for writing new hacking checks
- Use only for Barbican specific tests. OpenStack general tests
should be submitted to the common 'hacking' module.
- Pick numbers in the range B3xx. Find the current test with
the highest allocated number and then pick the next value.
- Keep the test method code in the so... |
easyw/kicad-3d-models-in-freecad | cadquery/FCAD_script_generator/Button_Switch_Nidec/cq_base_model.py | Python | gpl-2.0 | 23,507 | 0.005658 | #!/usr/bin/python
# -*- coding: utf8 -*-
#
#****************************************************************************
#* *
#* base classes for generating part models in STEP AP214 *
#* ... | f.y)
def addMoveTo(self, x, y):
r"""add a relative move (offset) from the current coordinate
.. note:: when issued as the first call after instatiating the class then the origin is moved accordingly
:param x: x distance from current position
:type x: ``float``
:param y: ... | rent position
:type y: ``float``
:rtype: self
"""
self.x += x
self.y += y
if len(self.commands) == 1:
self.commands = []
self.origin = (self.x, self.y)
self.commands.append((0, self.x, self.y))
return self
def addPoint(self... |
whiteclover/Medoly | medoly/config/hocon.py | Python | apache-2.0 | 38,051 | 0.000631 | #!/usr/bin/env python
#
# Copyright 2016 Medoly
#
# 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 agr... | turn value.get_int()
def get(self, path, default=None):
"""Gets the string data value, defaults not found returns the default value"""
value = self.get_node(path)
if value is None:
return default
return value.get_string()
get_string = get
def get_float(self, p... | e default value"""
value = self.get_node(path)
if value is None:
return default
return value.get_float()
def get_bool_list(self, path):
"""Gets the bool data value, defaults not found returns the default value"""
value = self.get_node(path)
return value... |
breznak/ALife | alife/experiments/behavior/random_walk_map.py | Python | gpl-2.0 | 6,062 | 0.032662 | #!/bin/env python2
from alife.worlds.world import World, Point
from alife.agents.UtilityAgent import SimpleAgent
from alife.utils.utils import dumpToArray, zeros
import math
import sys
import numpy
from nupic.encoders.extras.utility import SimpleUtilityEncoder
# common settings:
items=None
target=Point(4,9)
agent=Non... | t=[2], types=['food']) # world with some food
ag = SimpleAgent(actions={'go' : go}, targets=[reachedTarget], world=w)
ag.verbose = 2
ag.util = SimpleUtilityE | ncoder(length=2, minval=0, maxval=max(int(dimX),int(dimY)), scoreMin=0, scoreMax=100, scoreResolution=0.1)
ag.util.setEvaluationFn(euclDistance)
ag.start=ag.world._getRandomPos()
ag.me['hunger']=0 # not hungry
ag.mem = zeros(['score'],ag.mem,ag.world.dimX, ag.world.dimY, zero=-1)
ag.mem = zeros(['hunger'],ag.... |
m-lab/mlab-ns | server/mlabns/util/util.py | Python | apache-2.0 | 2,015 | 0.000993 | import json
import os
import jinja2
from mlabns.util import message
def _get_jinja_environment():
current_dir = os.path.dirname(__file__)
templates_dir = os.path.join(current_dir, '../templates')
return jinja2.Environment(loader=jinja2.FileSystemLoader(templates_dir),
exten... | request.error(404)
if output_type == message.FORMAT_JSON:
data = {}
data['status_code'] = '404 Not found'
json_data = json.dumps(data)
request.response.headers['Content-Type'] = 'application/json'
request.response.out.write(json_data)
else:
request.response.out.wr... | not_found.html').render(
))
def send_server_error(request, output_type=message.FORMAT_HTML):
request.error(500)
if output_type == message.FORMAT_JSON:
data = {}
data['status_code'] = '500 Internal Server Error'
json_data = json.dumps(data)
request.response.headers['Cont... |
PanDAWMS/panda-bigmon-core | core/reports/ObsoletedTasksReport.py | Python | apache-2.0 | 9,797 | 0.005818 | from django.template import RequestContext
from django.shortcuts import render_to_response
from django.db import connection
from collections import OrderedDict
from datetime import datetime
import time
import scipy.cluster.hierarchy as hcluster
import numpy as np
class ObsoletedTasksReport:
def __init__(self):
... | rion="distance")
clustersSummary = {}
i = 0
for dsEntry in statsDataSets:
clusterID = clusters[i]
if clusterID in clustersSummary:
currCluster = clustersSummary[clusterID]
currCluster["req"].append(dsEntry[3])
currCluste... | sets"][dsEntry[5]]=dsEntry[4]
currCluster["tasks"][dsEntry[0]]=dsEntry[2]
currCluster["obsoleteStart"] = dsEntry[1]
currCluster["leastParent"] = dsEntry[6] if dsEntry[6] < currCluster["leastParent"] else currCluster["leastParent"]
else:
currCl... |
shvets/etvnet-plex-plugin | test/test_helper.py | Python | mit | 302 | 0.013245 | import sys, os
sys.path.append( | os.path.abspath(os.path.join(os.path.dirname(__file__), '../src/lib/common')))
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../src/lib/etvnet')))
sys.path.ap | pend(os.path.abspath(os.path.join(os.path.dirname(__file__), '../src/lib/youtube')))
|
ilhamwk/accounting | view_major.py | Python | cc0-1.0 | 4,006 | 0.005741 | from flask import *
from playhouse.flask_utils import *
import string
from app import app
from model import Major, Minor, Stor | e, Transaction, Item
@app.route('/major', methods=['GET', 'POST'])
def major_list():
query = Major \
.select(Major, Minor) \
.join(Minor, on=(Major.id == Minor.major).alias('minor')) \
.order_by(Major.id)
last = None
minors = []
majors = []
for major in query:
... | name }
if last != None and major.id != last.id:
majors.append({'id': last.id, 'income': last.income,
'name': last.name, 'minors': minors})
minors = [minor]
else:
minors.append(minor)
last = major
if last != None:
majors.... |
JaapJoris/autodidact | autodidact/migrations/0003_auto_20170116_1142.py | Python | agpl-3.0 | 2,079 | 0.00337 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('autodidact', '0002_auto_20161004_1251'),
]
operations = [
migrations.CreateModel(
name='RightAnswer',
... | mary_key=True, auto_created=True, verbose_name='ID')),
('value', models.CharField(help_text='Supplying one or more wrong answers will turn this into a multi | ple choice question.', max_length=255)),
('step', models.ForeignKey(related_name='wrong_answers', to='autodidact.Step')),
],
options={
},
bases=(models.Model,),
),
migrations.AlterField(
model_name='course',
name='sl... |
rasbt/protein-science | scripts-and-tools/grab_atom_radius/grab_atom_radius.py | Python | gpl-3.0 | 2,978 | 0.014775 | # Sebastian Raschka 2014
# Script that extracts atoms within a radius from a PDB file
def grab_radius(file, radius, coordinates, include='ATOM,HETATM'):
"""
Grabs those atoms that are within a specified
radius of a provided 3d-coordinate.
Keyword arguments:
file: path to a PDB file
ra... | [float(line[30:38]),\
float(line[38:46]),\
float(line[46:54])]
distance = (sum([(coordinates[i]-xyz_coords[i])**2 for i in range(3)]))**0.5
if distance <= radius | :
in_radius.append(line)
return in_radius
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(
description='Extracts atoms within a radius from a PDB file.\n'\
'By default, all atoms in the PDB file are included in the calculati... |
bleepbloop/Pivy | scons/scons-local-1.2.0.d20090919/SCons/Scanner/Fortran.py | Python | isc | 14,448 | 0.002422 | """SCons.Scanner.Fortran
This module implements the dependency scanner for Fortran code.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation fil... | es)
return nodes
def FortranScan(path_variable="FORTRANPATH"):
"""Return a prototype Scanner instance for scanning source files
for Fortran USE & INCLUDE statements"""
# The USE statement regex matches the following:
#
# USE module_name
# USE :: module_name
# USE, INTRINSIC :: module_name
# ... | hem if they are commented out.
# In either of the following cases:
#
# ! USE mod_a ; USE mod_b [entire line is commented out]
# USE mod_a ! ; USE mod_b [in-line comment of second USE statement]
#
# the second module name (mod_b) will be picked up as a dependency
# ... |
nwokeo/supysonic | venv/lib/python2.7/site-packages/tests/wsgi.py | Python | agpl-3.0 | 4,317 | 0.001853 | import Queue
from unittest import TestCase
import threading
import time
from storm.wsgi import make_app
class TestMakeApp(TestCase):
def stub_app(self, environ, start_response):
if getattr(self, 'in_request', None):
self.in_request()
getattr(self, 'calls', []).append('stub_app')
... | ng_generator(self):
# If a timeline object is known, find_timeline finds it:
app, find_timeline = make_app(self.stub_app)
timeline = FakeTimeline()
self.in_generator = lambda:self.assertEqual(timeline, find_timeline())
list(app({'timeline.timeline': timeline}, self.stub | _start_response))
def test_timeline_is_replaced_in_subsequent_request(self):
app, find_timeline = make_app(self.stub_app)
timeline = FakeTimeline()
self.in_request = lambda:self.assertEqual(timeline, find_timeline())
list(app({'timeline.timeline': timeline}, self.stub_start_response... |
enableiot/iotanalytics-rule-engine | pydeps/db/dataDao.py | Python | apache-2.0 | 2,301 | 0.003911 | # Copyright (c) 2015 Intel 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 applicable law or agreed to in ... | sure_val"
}
key_conv = "org.apache.spark.examples.pythonconverters.ImmutableBytesWritableToStringConverter"
value_conv = "org.apache.spark.examples.pythonconverters.HBaseResultToStringConverter"
rdd = self.spark_context.newAPIHadoopRDD("org.apache.hadoop.hbase.mapreduce.TableInputForma... | "org.apache.hadoop.hbase.client.Result",
conf=conf, keyConverter=key_conv, valueConverter=value_conv)
return rdd
|
materials-commons/materialscommons.org | backend/tests/python_api_mulltiuser_check/DB.py | Python | mit | 1,380 | 0.001449 | from os import environ
import logging
import rethinkdb as r
from rethinkdb.errors import RqlDriverError, ReqlError
_MCDB = "materialscommons"
_MCDB_HOST = environ.get('MCDB_HOST') or 'localhost'
probe = environ.get('MCDB_PORT')
if not probe:
print("Unable to run without a setting for MCDB_PORT")
exit(-1)
_MCDB... | self.conn = None
def set_connection(self):
try:
if not self.conn:
self.conn = r.connect(host=_MCDB_HOST, port=_MCDB_PORT, db=_MCDB)
| except RqlDriverError as excp:
self.conn = None
message = "Database connection could not be established: host, port, db = " + \
_MCDB_HOST + ", " + str(_MCDB_PORT) + ", " + _MCDB
self.log.error(message)
raise excp
def connection(self):
... |
tvtsoft/odoo8 | addons/sale_stock/report/sale_report.py | Python | agpl-3.0 | 1,213 | 0.00742 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from openerp.osv import fields, osv
from openerp import tools
class sale_report(osv.osv):
_inherit = "sale.report"
_columns = {
'shipped': fields.boolean('Shipped', readonly=True),
'shipped_qty... | ),
'state': fields.selection([
('draft', 'Draft Quotation'),
('sent', 'Quotation Sent'),
('waiting_date', 'Waiting Schedule'),
('manual', 'Sale to Invoice'),
('progress', 'Sale Order'),
('shipping_except', 'Shipping Exception'),
... | }
def _select(self):
return super(sale_report, self)._select() + ", s.warehouse_id as warehouse_id, s.shipped, s.shipped::integer as shipped_qty_1"
def _group_by(self):
return super(sale_report, self)._group_by() + ", s.warehouse_id, s.shipped"
|
rero/reroils-app | tests/api/test_permissions_patron.py | Python | gpl-2.0 | 2,746 | 0 | # -*- coding: utf-8 -*-
#
# RERO ILS
# Copyright (C) 2019 RERO
#
# 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, version 3 of the License.
#
# Th | is program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTA | BILITY 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. If not, see <http://www.gnu.org/licenses/>.
"""Tests REST API patrons."""
from copy import deepcopy
from fl... |
t-brandt/acorns-adi | photometry/__init__.py | Python | bsd-2-clause | 32 | 0 | from | calc_phot import calc_ph | ot
|
botify-labs/python-simple-workflow | swf/querysets/workflow.py | Python | mit | 25,485 | 0.001295 | # -*- coding: utf-8 -*-
# Copyright (c) 2013, Theo Crevon
# Copyright (c) 2013, Greg Leclercq
#
# See the file LICENSE for copying permission.
from boto.swf.exceptions import SWFResponseError
from swf.constants import REGISTERED
from swf.querysets.base import BaseQuerySet
from swf.models import Domain
from swf.model... | n date of Workflo | wType
:type deprecation_date: float (timestamp)
:param task_list: task list to use for scheduling decision tasks for executions
of this workflow type
:type task_list: String
:param child_policy: policy to use for the child workflow executions
... |
GabrielBrascher/cloudstack | systemvm/debian/opt/cloud/bin/cs/__init__.py | Python | apache-2.0 | 1,000 | 0 | # Licensed to the Apache Software Founda | tion (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copy | right ownership. The ASF licenses this file
# to you 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 i... |
williamalu/mimo_usrp | scripts/pll.py | Python | mit | 3,454 | 0.001448 | #!/usr/bin/env python
""" Class that reads in data from decoder.py and uses a PLL to correct for
phase offset. """
import numpy as np
import matplotlib.pyplot as plt
import helper
#from decoder import Decoder
j = (0 + 1j)
class PLL(object):
def __init__(self, data, k_p, k_i, k_d):
""" Initialize d... | # Estimate error in phase for BPSK
err = -y.real * y.imag #if (np.absolute(x) > .004) else | 0.0
# Estimate error in phase for QPSK
# A = y.real * np.sign(y.imag)
# B = y.imag * np.sign(y.real)
# err = (-1/2) * (A - B)
# Calculate integral of error
err_sum += err
# Calculate derivative of error
err_diff = err - p... |
colaftc/webtool | top/api/rest/SubuserEmployeeUpdateRequest.py | Python | mit | 702 | 0.032764 | '''
Created by a | uto_sdk on 2013.01.22
'''
from top.api.base import RestApi
class SubuserEmployeeUpdateRequest(RestApi):
def __init__(self,domain='gw.api.taobao.com',port=80):
RestApi.__init__(self,domain, port)
self.depa | rtment_id = None
self.duty_id = None
self.employee_name = None
self.employee_nickname = None
self.employee_num = None
self.employee_turnover = None
self.entry_date = None
self.id_card_num = None
self.leader_id = None
self.office_phone = None
self.personal_email = None
self.personal_mobi... |
silly-wacky-3-town-toon/SOURCE-COD | toontown/town/DDTownLoader.py | Python | apache-2.0 | 951 | 0.002103 | import TownLoader
import DDStreet
from toontown.suit import Suit
class DDTownLoader(TownLoader.TownLoader):
def __init__(self, hood, parentFSM, doneEvent):
TownLoader.TownLoader.__init__(self, hood, parentFSM, doneEvent)
self.streetClass = DDStreet.DDStreet
self.musicFile = 'phase_6/audio/... | ds_dock_' + str(self.canonicalBranchZone) + '.pdna'
self.createHood(dnaFile)
def unload(self):
Suit.unloadSuits(2)
TownLoader.TownLoader.unload(self)
def enter(self, requestStatus):
TownLoader.TownLoader.en | ter(self, requestStatus)
def exit(self):
TownLoader.TownLoader.exit(self)
|
gazpachoking/Flexget | flexget/plugins/input/inputs.py | Python | mit | 2,537 | 0.001971 | from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import logging
from flexget import plugin
from flexget.eve | nt import event
log = logging.getLogger('inputs' | )
class PluginInputs(object):
"""
Allows the same input plugin to be configured multiple times in a task.
Example::
inputs:
- rss: http://feeda.com
- rss: http://feedb.com
"""
schema = {
'type': 'array',
'items': {
'allOf': [
{'$... |
MyRookie/SentimentAnalyse | src/Algorithm/ScoreCaculating.py | Python | mit | 1,593 | 0.041431 | import math
import sys
sys.path.append('..')
import Analyse.AFX as AFX
class State:
def __init__(self):
self.SenShifterState = True
self.MoodStrength = 1.0
self.positive = 0.0
self.negative = 0.0
def Process(self, score):
if self.SenShifterState is True:
self.positive += score
else:
self.negative ... | h('D'):
self.MoodStrength /= 2
def returnScore(self):
score = self.positive - self.negative
score *= self.MoodStrength
return score
#calulating the score pf specific sentence
def CaculateASentence(Sentence):
S = State()
for word in Sentence:
tag = AFX.GetWord(word,'Tag')
#if the word has no orient... | , change the state of Sentiment Shifter
S.SenShifterState = -S.SenShifterState
elif tag is "Inc" or tag is "Dow":
S.ChangeMood(tag)
else:
S.Process(tag)
return S.returnScore()
#caculating the score of the Document with specific rules
def Run(Data):
ScoreList = []
counter = 0
for Sen in Data:
if Se... |
land-pack/pyroom | pyroom/manage.py | Python | gpl-3.0 | 239 | 0 | from pyroom.app import P | yRoom
from options import options
from pyroom.urls import settings
from pyroom.urls import handlers
if __name__ == '__main__':
| pyroom = PyRoom(options=options, handlers=handlers, **settings)
pyroom.start()
|
google/jws | jws/jwt.py | Python | apache-2.0 | 9,120 | 0.005482 | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | string, the subject claim as defined at
https://tools.ietf.org/html/rfc7519#section-4.1.2.
audiences: list of string, the audiences claim as defined at
https://tools.ietf.org/html/rfc7519#section-4.1.3.
clock_skew_tolerance: integer, the clock skew that the verifier tolerates.
| Raises:
UnsupportedAlgorithm: if the algorihtm is not defined at
https://tools.ietf.org/html/rfc7518#section-3.1 or if jwk is not Rsa or
Ecdsa key.
"""
self.verifier = jws.JwsPublicKeyVerify(jwk_set)
self.issuer = issuer
self.subject = subject
self.audiences = audiences
self.cl... |
THM-TheoreM/Algorithm | tool/ImageProcessing/perspective/antialiased_do.py | Python | gpl-3.0 | 947 | 0.024287 | from PIL import Image
import numpy
from antialiased import antialiased
im=Image.open('C:/Users/linzz/Desktop/pic/image_processing/ImageProcessing/perspective/find/line.jpg')
im=numpy.array(im)
node_site_u2 = [165, 145, 557, 83, 564, 333, 137, 359]
node_site_u3 = [124, 150, 524, 113, 540, 246, 106, 272]
node_site_u4 =... | 423, 78, 423, 208, 171, 205]
node_site_12 = [634, 617, 1900, 431, 1896, 1161, 491, 1269]
x0,y0,x1,y1,x2,y2,x3,y3=node_site_u2
x0=122
y0=266
x1=429
y1=161
im=antialiased(im,x0,y0,x1,y1)
'''
im=antialiased(im,x0,y0,x3,y3)
im=antialiased(im,x3,y3,x0,y0)
im=antialiased(im,x1,y1,x2,y2)
im=antialiased(im,x2,y2,x1,y1)
im=... | nti_1.jpg')
|
jbassen/edx-platform | lms/djangoapps/dashboard/sysadmin.py | Python | agpl-3.0 | 38,209 | 0.001282 | """
This module creates a sysadmin dashboard for managing and viewing
courses.
"""
import csv
import json
import logging
import os
import subprocess
import time
import StringIO
from pymongo.errors import PyMongoError
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.aut... | port timezone
from django.utils.translation import ugettext as _
from django.views.decorators.cache import cache_control
from django.views.generic.base import TemplateView
from django.views.decorators.http import condition
from django.views.decorators.csrf import ensure_csrf_cookie
from edxmako.shortcuts import render_... | seware.courses import get_course_by_id
import dashboard.git_import as git_import
from django_comment_client.management_utils import rename_user as rename_user_util
from dashboard.git_import import GitImportError
from dashboard.models import CourseImportLog
from external_auth.models import ExternalAuthMap
from external_... |
hmoco/osf.io | admin/base/settings/defaults.py | Python | apache-2.0 | 6,690 | 0.001495 | """
Django settings for the admin project.
"""
import os
from urlparse import urlparse
from website import settings as osf_settings
from django.contrib import messages
from api.base.settings import * # noqa
# TODO ALL SETTINGS FROM API WILL BE IMPORTED AND WILL NEED TO BE OVERRRIDEN
# TODO THIS IS A STEP TOWARD INTEG... | 'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
}
}]
ROOT_URLCONF = 'admin.base.urls'
WSGI_APPLICATION = 'admin.base.wsgi.application'
ADMIN_BASE = ''... | ath.dirname(BASE_DIR), 'static_root')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
LANGUAGE_CODE = 'en-us'
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'public/js/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-s... |
uclouvain/OSIS-Louvain | base/models/enums/learning_container_year_types.py | Python | agpl-3.0 | 2,804 | 0.001784 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | IVE, _("Other collective")),
(OTHER_INDIVIDUAL, _("Other individual")),
(MASTER_THESIS, _("Thesis")),
)
class LearningContainerYearType(ChoiceEnum):
COURSE = _("Course")
INTERNSHIP = _("Internship")
DISSERTATION = _("Dissertation")
OTHER_COLLECTIVE = _("Other collective")
OTHER_INDIVIDUAL ... | "Other individual")
MASTER_THESIS = _("Thesis")
EXTERNAL = _("External")
@classmethod
def for_faculty(cls) -> tuple:
return cls.OTHER_COLLECTIVE.name, cls.OTHER_INDIVIDUAL.name, cls.MASTER_THESIS.name, cls.INTERNSHIP.name
LCY_TYPES_WITH_FIXED_ACRONYM = [COURSE, INTERNSHIP, DISSERTATION]
LEAR... |
Som-Energia/somenergia-tomatic | tomatic/pbx/pbxareavoip.py | Python | gpl-3.0 | 5,174 | 0.018748 | # -*- coding: utf-8 -*-
import requests
import json
from yamlns import namespace as ns
from .. import persons
class AreaVoip(object):
@staticmethod
def defaultQueue():
import dbconfig
return dbconfig.tomatic.get('areavoip',{}).get('queue', None)
def __init__(self):
import dbconfi... | key = persons.byExtension(extension),
extension = extension,
name = persons.name(persons.byExtension(extension)),
paused = status.get('1') == 'paused',
disconnected = status['2'] is None or status['2'] == 'UNAVAILABLE',
available = status... | secondsInCalls = int(status.get('3','0')),
secondsSinceLastCall = 0, # TODO
flags = [status['2']] if status['2'] and status['2'] not in (
'UNAVAILABLE', 'NOT_INUSE', 'RINGING', 'INUSE',
) else [],
)
for extension, statu... |
lsbardel/python-stdnet | covrun.py | Python | bsd-3-clause | 177 | 0 | import sys
import os
from runtests import run
if __name__ == '__main__':
if sys.version_info > (3, 3):
run(coverage=True, | coveralls=True)
| else:
run()
|
to266/hyperspy | hyperspy/tests/signal/test_signal_subclass_conversion.py | Python | gpl-3.0 | 2,881 | 0 | import nose.tools as nt
import numpy as np
from hyperspy.signal import Signal
from hyperspy import signals
from hyperspy.exceptions import DataDimensionError
class Test1d:
def setUp(self):
self.s = Signal(np.arange(2))
@nt.raises(DataDimensionError)
def test_as_image(self):
self.s.as_im... | t_EELS(self):
s = self.s.as_spectrum(0)
s.set_signal_type("EELS")
nt.assert_equal(s.metadata.Signal.signal_type, "EELS")
nt.assert_is_instance(s, signals.EELSSpectrum)
class Test2d:
def setUp(self):
self.s = Signal(np.random.random((2, 3)))
def test_as_image_T(self):
... | .as_image((0, 1)).data.shape)
def test_as_image(self):
nt.assert_equal(
self.s.data.shape, self.s.as_image((1, 0)).data.shape)
def test_as_spectrum_T(self):
nt.assert_equal(
self.s.data.T.shape, self.s.as_spectrum(0).data.shape)
def test_as_spectrum(self):
... |
gatgui/pygl | python/test_gl.py | Python | lgpl-3.0 | 6,380 | 0.025549 | # Copyright (C) 2009 Gaetan Guidet
#
# This file is part of pygl.
#
# luagl is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or (at
# your option) any later version.... | xture(gl.TEXTURE0)
gl.EnableClientState(gl.TEXTURE_COORD_ARRAY)
gl.TexCoordPointer(2, gl.FLOAT, stride, texcoords.rawPtr)
gl.VertexPointer(3, gl.FLOAT, stride, positions.rawPtr)
#gl.DrawArrays(gl.QUADS, 0, 4)
gl.DrawElements(gl.QUADS, 4, gl.UNSIGNED_SHORT, mesh_idx.rawPtr)
gl.DisableClientState(... | XTURE_COORD_ARRAY)
gl.DisableClientState(gl.VERTEX_ARRAY)
else:
gl.Begin(gl.QUADS)
for e in mesh:
gl.MultiTexCoord2f(gl.TEXTURE0, e.texcoord.s, e.texcoord.t);
gl.Color3f(1, 1, 1)
gl.Vertex3fv(e.position)
gl.End()
def initShaders():
global prog
vprog_src = [
"void main() {... |
toddpalino/kafka-tools | kafka/tools/protocol/responses/describe_acls_v0.py | Python | apache-2.0 | 1,614 | 0 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under | the Apache License, Version 2.0 (the
# "License"); you may not use this 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,
# s | oftware distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from kafka.tools.protocol.responses import BaseResponse
class ... |
wonder-sk/inasafe | safe/impact_functions/inundation/flood_raster_population/metadata_definitions.py | Python | gpl-3.0 | 5,408 | 0 | # coding=utf-8
"""InaSAFE Disaster risk tool by Australian Aid - Flood Raster Impact on
Population.
Contact : ole.moller.nielsen@gmail.com
.. note:: 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 Fou... | : layer_mode_continuous,
'layer_geometries': [layer_geometry_raster],
'hazard_categories': [hazard_category_single_event],
'hazard_types': [hazard_flood],
'continuous_hazard_units': [unit_feet, unit_metres],
'vector_haza... | ': {
'layer_mode': layer_mode_continuous,
'layer_geometries': [layer_geometry_raster],
'exposure_types': [exposure_population],
'exposure_units': [count_exposure_unit],
'exposure_class_fields': [],
'a... |
jesseengel/magenta | magenta/pipelines/pipeline_test.py | Python | apache-2.0 | 8,715 | 0.004246 | # Copyright 2019 The Magenta Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | ('hello')
stats = pipe.get_stats()
self.assertEqual(
set((stat.name, stat.count) for stat in stats),
set([('TestPipeline123_counter_1', 5),
('TestPipeline123_counter_2', 10)]))
def testInvalidStatisticsError(self):
class TestPipeline1(pipeline.Pipeline):
def __init__(... | ]
def transform(self, input_object):
self._set_stats([statistics.Counter('counter_1', 5), 12345])
return []
class TestPipeline2(pipeline |
ianawilson/BbQuick | docs/conf.py | Python | mit | 6,974 | 0.006739 | # -*- coding: utf-8 -*-
#
# BbQuick documentation build configuration file, created by
# sphinx-quickstart on Fri Feb 10 20:55:10 2012.
#
# 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.
#
# All... | title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#h... | ch as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime forma... |
edx/edx-platform | cms/djangoapps/contentstore/migrations/0001_initial.py | Python | agpl-3.0 | 1,882 | 0.004782 | import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='PushNot... | options={
| 'ordering': ('-change_date',),
'abstract': False,
},
),
migrations.CreateModel(
name='VideoUploadConfig',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('cha... |
Code4SA/umibukela | umibukela/migrations/0029_auto_20170226_0745.py | Python | mit | 1,763 | 0.002269 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import umibukela.models
class Migration(migrations.Migration):
dependencies = [
('umibukela', '0028_cyc | le_materials'),
]
operations = [
migrations.CreateModel(
name='ProgrammeKoboRefreshToken',
fields=[
('programme', models.OneToOneField(related_name='kobo_refresh_token', primary_key=True, serialize=False, to='umibukela.Progr | amme')),
('token', models.TextField()),
],
),
migrations.RenameModel(
old_name='KoboRefreshToken',
new_name='UserKoboRefreshToken',
),
migrations.AddField(
model_name='cycle',
name='auto_import',
fiel... |
gongleiarei/qemu | scripts/analyze-migration.py | Python | gpl-2.0 | 20,683 | 0.006479 | #!/usr/bin/env python
#
# Migration Stream Analyzer
#
# Copyright (c) 2015 Alexander Graf <agraf@suse.de>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the Lic... | .write_memory and fill_char != 0:
self.files[self.name].seek(addr, os.SEEK_SET)
self.files[self.name].write(chr(fill_char) * self.TARGET_PAGE_SIZE)
if self.dump_memory:
self.memory['%s (0x%016x)' % (self.name, addr)] = 'Filled with 0x%02x' % fi... | char
flags &= ~self.RAM_SAVE_FLAG_COMPRESS
elif flags & self.RAM_SAVE_FLAG_PAGE:
if flags & self.RAM_SAVE_FLAG_CONTINUE:
flags &= ~self.RAM_SAVE_FLAG_CONTINUE
else:
self.name = self.file.readstr()
if sel... |
kennyjoseph/identity_extraction_pub | python/utility_code/dependency_parse_handlers.py | Python | mit | 6,421 | 0.007164 | __author__ = 'kjoseph'
import itertools
import Queue
from collections import defaultdict
from dependency_parse_object import DependencyParseObject, is_noun, is_verb
def get_parse(dp_objs):
term_map = {}
map_to_head = defaultdict(list)
for parse_object in dp_objs:
if parse_object.head > 0:
... | head = term_map[head_id]
if len(children) == 0:
continue
for child_id in children:
child | = term_map[child_id]
if child.deprel == 'CONJ':
to_combine.append({child.id, head.id})
return get_combinations(to_combine)
def get_combinations(to_combine):
combination_found = True
while combination_found:
combination_found = False
combos = itertools.combinatio... |
axbaretto/beam | sdks/python/.tox/py27gcp/lib/python2.7/site-packages/google/oauth2/flow.py | Python | apache-2.0 | 9,887 | 0 | # Copyright 2016 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 writing,... | orization Flow`_ and acquiring user credentials.
Here's an example of using the flow with the installed application
authorization flow::
import googl | e.oauth2.flow
# Create the flow using the client secrets file from the Google API
# Console.
flow = google.oauth2.flow.Flow.from_client_secrets_file(
'path/to/client_secrets.json',
scopes=['profile', 'email'],
redirect_uri='urn:ietf:wg:oauth:2.0:oob')
# Tell the user to go to t... |
BinDigit1/EulerProjects | Problem 40/Champernownes_constant.py | Python | gpl-2.0 | 304 | 0.013158 | import time
output = ''
i=1
start_time = time.time()
while len(output)<1000001:
output +=str(i)
i + | = 1
print(int(output[9]) * int(output[99]) *
int(output[999]) * int(output[9999]) *
int(output[99999]) * int(output[999999 | ]))
print("--- %s seconds ---" % (time.time() - start_time)) |
destos/mfinstop | mfinstop/context_processors.py | Python | gpl-3.0 | 113 | 0 | from django.conf import settings
def google_ua(request):
return {'google_ua | ': settings.GOOGLE_TRACKING_ID | }
|
rwl/PyCIM | CIM14/IEC61970/OperationalLimits/ActivePowerLimit.py | Python | mit | 1,717 | 0.001747 | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... | lass ActivePowerLimit(OperationalLimit):
"""Limit on active power flow.
"""
def __init__(self, value=0.0, *args, **kw_args):
"""Initialises a new 'ActivePowerLimit' instance.
@param value: Value of active power limit.
"""
#: Value of active power limit.
self.value ... | value": 0.0}
_enums = {}
_refs = []
_many_refs = []
|
GooeyComps/gooey-dist | gooeydist/interpreter/matrix.py | Python | mit | 2,797 | 0.008223 |
from enum import Enum
# Takes string names or int indices of a type and an attribute.
# Returns None if that type does not have that attribute.
# Else returns the default value for that attribute.
def getDefault(typeName, attrName):
# Determine index of type
if type(typeName) == int:
typeIndex = typeN... | one, None, None, None, None, None, None, None],
[False, False, False, False, False, False, None, False, False, False, False, False],
["""Times New Roman""", None, None, None, None, None, """Tim | es New Roman""", None, None, None, None, None],
[12, None, None, None, None, None, 12, None, None, None, None, None],
['black', None, None, None, None, None, 'black', None, None, None, None, None],
[None, None, None, None, None, None, None, None, None, None, None, 'defaultIcon']]
NUM_ATTRIBUTES = len(matrix)
NUM_TYPES... |
Alwnikrotikz/marinemap | lingcod/manipulators/urls.py | Python | bsd-3-clause | 487 | 0.01232 | from django.conf.urls.defaults import *
urlpatterns = patterns('lingcod.manipulators.views',
(r'^test/$', 'testView' ),
(r'^list/([A-Za-z0-9_,]+)/([A-Za-z0-9_,]+)/$', 'mpaManipulatorList' ),
url(r'^([A-Za-z0-9_,]+)/$', 'multi_generic_manipulator_view', name='manipulate'),
url(r'^$', 'multi_generic_mani... | lators': None}, name='manipulate-blank'),
url(r'^/$', 'multi_generic_manipulator_view', {'manipulato | rs': None}, name='manipulate-blank'),
)
|
p2pu/mechanical-mooc | groups/tests.py | Python | mit | 2,657 | 0.006022 | from django.test import TestCase
from groups import models as group_model
class SimpleTest(TestCase):
def test_create_group(self):
"""
Test group creation
"""
group = group_model.create_group('ateam@mechmooc.com', 'The A team', 1)
self.assertTrue('address' in group)
... | p)
group_copy = group_model.get_group(group['uri'])
self.assertEqual(group, group_copy)
def test_add_group_member(self):
group = group_model.create_group('ateam@mechmooc.com', 'The A team', 1)
group_model.add_group_member(group['uri'], 'bob@mail.com')
group = group_model.ge... | ['members']), 1)
self.assertEqual(group['members'][0], 'bob@mail.com')
def test_remove_group_member(self):
group = group_model.create_group('ateam@mechmooc.com', 'The A team', 1)
group_model.add_group_member(group['uri'], 'bob@mail.com')
group_model.add_group_member(group['uri'], '... |
sfu-natlang/HMM-Aligner | src/support/proc_no_tag_to_clean.py | Python | mit | 510 | 0 | content =\
[line.strip().split() for | line in open("ut_align_no_tag.a")]
f = open("ut_align_no_tag_clean.a", "w")
for line in content:
for entry in line:
if entry.find('?') != -1:
l, rs = entry.split('?')
rs = rs.split(',')
for r in rs:
f.write(l + '?' + r + " ")
else:
l,... | r + " ")
f.write("\n")
f.close()
|
jamesaud/se1-group4 | jmatcher/job/migrations/0016_auto_20170411_0342.py | Python | mit | 2,381 | 0.00252 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-11 03:42
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('students', '0007_auto_20170410_0523'),
('job', '001... | ('updated_at', models.DateTimeField(auto_now_add=True)),
],
),
migrations.CreateModel(
name='Location',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('city', models.CharF... | |
hortonworks/hortonworks-sandbox | apps/pig/src/pig/migrations/0006_auto__del_logs__add_field_job_status__add_field_job_email_notification.py | Python | apache-2.0 | 9,272 | 0.00701 | # encoding: utf-8
# Licensed to Hortonworks, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Hortonworks, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ... | l_notification': ('django.db.models.fields.Boole | anField', [], {'default': 'True', 'blank': 'True'}),
'job_id': ('django.db.models.fields.CharField', [], {'max_length': '50', 'primary_key': 'True'}),
'script': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['pig.PigScript']"}),
'status': ('django.db.models.fields.Sma... |
motobyus/moto | module_django/tokenauth/jwtTest/urls.py | Python | mit | 277 | 0 | # -*- coding: utf-8 -*-
from django.conf.urls import include, url
from rest_framework imp | ort routers
from jwtTest import views
router = routers.DefaultRouter()
ro | uter.register(r'management', views.ProductAViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]
|
FedoraScientific/salome-paravis | test/VisuPrs/SWIG_scripts/B9.py | Python | lgpl-2.1 | 1,819 | 0.00055 | # Copyright (C) 2010-2014 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library ... | simple.Delete(med_reader)
# Clear views from scalar bar and update views
for rview i | n pvsimple.GetRenderViews():
rview.Representations.Clear()
pvsimple.Render(rview)
|
GNS3/gns3-server | gns3server/controller/__init__.py | Python | gpl-3.0 | 21,528 | 0.002276 | #!/usr/bin/env python
#
# Copyright (C) 2016 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
... | er
self._ssl_context = WebServer.instance(host=host, port=port).ssl_context()
protocol = server_config.get("protocol", "http")
if self._ssl_context and protocol != "https":
log.warning("Protocol changed to 'https' for local compute because SSL is enabled".format(port))
pr... | name=name,
protocol=protocol,
host=host,
console_host=console_host,
port=port,
... |
nddsg/SimpleDBMS | simple_dbms/comparison.py | Python | gpl-3.0 | 4,943 | 0.001618 | import re
from conditional_expression import ConditionalExpression
from compare_term import CompareTerm
class Comparison(ConditionalExpression, object):
"""
A class that represents a comparison appearing in a WHERE clause.
"""
EQ = 0
NOTEQ = 1
LT = 2
GT = 3
LTEQ = 4
GTEQ = 5
LI... | s None):
return False
if self.type == Comparison.EQ:
return left_arg == right_arg
elif se | lf.type == Comparison.NOTEQ:
return left_arg != right_arg
elif self.type == Comparison.LT:
return left_arg < right_arg
elif self.type == Comparison.GT:
return left_arg > right_arg
elif self.type == Comparison.LTEQ:
return left_arg <= right_arg
... |
bitcraft/firmata_aio | firmata_aio/protocol/commands.py | Python | gpl-3.0 | 1,998 | 0.001001 | """
Define command names and prove command/code mappings
"""
from collections import ChainMap
__all__ = [
'nibble_commands',
'byte_commands',
'sysex_commands',
'command_lookup',
'command_names',
]
INPUT, OUTPUT, ANALOG, \
PWM, SERVO, I2C, ONEWIRE, \
STEPPER, ENCODER = range(0, 9)
# do not combine... | 0x69: ('analog_mapping_query', ()),
0x6A: ('analog_mapping_response', ()),
0x6B: ('capability_query | ', ()),
0x6C: ('capability_response', ()),
0x6D: ('pin_state_query', ()),
0x6E: ('pin_state_response', ()),
0x6F: ('extended_analog', ()),
0x70: ('servo_config', ()),
0x71: ('string_data', ()),
0x72: ('stepper_data', ()),
0x73: ('onewire_data', ()),
0x75: ('shift_data', ()),
0x76... |
pisskidney/leetcode | easy/27.py | Python | mit | 449 | 0 | #!/usr/bin/python
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: in | t
:rtype: int
"""
i = 0
j = 0
while i < len(nums):
if nums[i] != val:
nums[j] = nums[i]
j += 1
i += 1
| return j
s = Solution()
x = [3, 3, 3, 3, 3, 3, 3]
print x
print s.removeElement(x, 3)
print x
|
RichardLMR/generic-qsar-py-utils | code/ml_input_utils.py | Python | gpl-2.0 | 21,062 | 0.033995 | #########################################################################################################
# ml_input_utils.py
# One of the Python modules written as part of the genericQSARpyUtils project (see below).
#
# ################################################
# #ml_input_utils.py: Key documentation :Contents#... | ave the following structure to each line:
molId\tFeatureB\tFeatureC\tFeatureA\tFeatureX....
Must - for now! - have a .txt extension!
(2) unique_features_file :
Must have the same format as feat2IndexFileName (see contents of self.match_all_unique_features_to_indices(...).
'''
id2string_fp_features ... | p_features(raw_fp_file,iSjCompoundMapperStringFeatures)
if unique_features_file is None:
feat2IndexFileName = re.sub('(\.txt$)','_fpFeat2InitialIndex.csv',raw_fp_file)#17/03/13: actually, it is useful to write this to the same directory as the fingerprints file! => Hopefully any associated errors can be deal... |
jkbrzt/django-settings-export | tests/settings.py | Python | bsd-3-clause | 688 | 0 | SECRET_KEY = 'spam'
D | EBUG = True
TEMPLATE_DEBUG = DEBUG
ROOT_URLCONF = 'tests.urls'
INSTALLED_APPS = ['tests']
DATABASES = {'default': {'NAME': 'db.sqlite',
'ENGINE': 'django.db.backends.sqlite3'}}
# Django < 1.8
TEM | PLATE_CONTEXT_PROCESSORS = [
'django_settings_export.settings_export'
]
# Django 1.8+
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django_settings_expo... |
ojarva/home-info-display | tea_reader_consumer/run.py | Python | bsd-3-clause | 1,217 | 0.002465 | from local_settings import BASE_URL
import datetime
import json
import redis
import requests
import requests.exceptions
class TeaReaderConsumer(object):
def __init__(self):
self.redis = redis.StrictRedis()
def run(self):
pubsub = self.redis.pubsub(ignore_subscribe_messages=True)
pubs... | _water"]:
self.redis.publish("kettle-commands", json.dumps({"on": tag_data["fields"]["boil_water"]}))
| requests.post(BASE_URL + "tea/get/" + data["id"])
def main():
runner = TeaReaderConsumer()
runner.run()
if __name__ == '__main__':
main()
|
repotvsupertuga/tvsupertuga.repository | script.module.streamtvsupertuga/lib/resources/lib/sources/en/glodls.py | Python | gpl-2.0 | 5,797 | 0.014145 | # -*- coding: UTF-8 -*-
#######################################################################
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @tantrumdev wrote this file. As long as you retain this notice you
# can do whatever you want wit... | self.tvsearch = 'search_results.php?search={0}&cat=41&incldead=0&inclexternal=0&lang=1&sort=seeders&order=desc'
self.moviesearch = 'search_results.php?search={0}&cat=1&incldead=0&inclexternal=0&lang=1&sort=size&order=desc'
def movie(self, imdb, title, localtitle, aliases, year):
try:
... | BaseException:
return
def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):
try:
url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'year': year}
url = urllib.urlencode(url)
return url
except BaseException:
... |
rdhyee/osf.io | website/addons/github/tests/test_models.py | Python | apache-2.0 | 12,663 | 0.001264 | # -*- coding: utf-8 -*-
import mock
import unittest
from nose.tools import * # noqa
from github3 import GitHubError
from github3.repos import Repository
from tests.base import OsfTestCase, get_default_metaschema
from tests.factories import ExternalAccountFactory, ProjectFactory, UserFactory
from framework.auth imp... | b')
self.user_settings = self.project.creator.get_addon('github')
self.node_settings.user_settings = self.user_settings
self.node_settings.user = 'Queen'
self.node_settings.repo = 'Sheer-Heart-At | tack'
self.node_settings.external_account = self.external_account
self.node_settings.save()
self.node_settings.set_auth
@mock.patch('website.addons.github.api.GitHubClient.repo')
def test_before_make_public(self, mock_repo):
mock_repo.side_effect = NotFoundError
result... |
vmprof/vmprof-server | webapp/wsgi.py | Python | mit | 280 | 0 | # import os
# os.environ.setde | fault("DJANGO_SETTINGS_MODULE", "settings")
# from vmprof import DjangoVMPROF
# vmprof = DjangoVMPROF("localhost", 8000, "token")
# app = vmprof(get_wsgi_application())
from django.core.wsgi import get_wsgi_application
app = get_wsgi_application | ()
|
dropbox/pep8squad | yapf/yapflib/subtype_assigner.py | Python | apache-2.0 | 10,019 | 0.007286 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | self._SetTokenSubtype(child, format_token.Subtype.BINARY_OPERATOR)
def Visit_factor(self, node): # pylint: disable=invalid-name
# factor ::= ('+'|'-'|'~') factor | power
for child in node.children:
self.Visit(child)
if isinstance(child, pytree.Leaf) and child.value in '+-~':
| self._SetTokenSubtype(child, format_token.Subtype.UNARY_OPERATOR)
def Visit_power(self, node): # pylint: disable=invalid-name
# power ::= atom trailer* ['**' factor]
for child in node.children:
self.Visit(child)
if isinstance(child, pytree.Leaf) and child.value == '**':
self._Set... |
google/gazoo-device | gazoo_device/utility/retry.py | Python | apache-2.0 | 3,404 | 0.004994 | # Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | d arguments to the function.
is_successful: Function which takes in the result of func() and returns
whether function execution should be considered successful. To indicate
success, return True. Defaults to always returning True.
timeout: If no run of func() succeeds in this time period, raise an er... | s from func(). If False, considers execution of
func() a failure if an Exception is raised. is_successful() will NOT be
called if an Exception occurs.
exc_type: Type of exception to raise when timeout is reached. Note that the
class constructor will be called with just 1 argument.
Returns:
Re... |
resmo/cloudstack | test/integration/plugins/nuagevsp/test_nuage_sharednetwork_vpc_vm_monitor.py | Python | apache-2.0 | 30,062 | 0 | # 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... | admin=False,
domainid=cls.domain_1.id
)
user = cls.generateKeysForUser(cls.api_client, cls.account_d1b)
cls.user_d1b_apikey = user.apikey
cls.user_d1b_secretkey = user.secretkey
# Create 1 admin and 2 user accounts for doamin_11
... | ccount_d11 = Account.create(
cls.api_client,
cls.sharednetworkdata["accountD11"],
admin=True,
domainid=cls.domain_11.id
)
user = cls.generateKeysForUser(cls.api_client, cls.account_d11)
cls.user_d11_apikey = user.apikey
... |
tornadomeet/mxnet | python/mxnet/contrib/__init__.py | Python | apache-2.0 | 1,006 | 0 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
| # to you under the Apache License, Version 2.0 (the
# "License"); you may not use this 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 L... | 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.
# coding: utf-8
"""Experimental contributions"""
from . import symbol
from . import ndarray
from . import symbol as sym
from . imp... |
oblalex/django-workflow | src/workflow/__init__.py | Python | mit | 58 | 0 | """
Transactional workflow | control for Django models.
"""
| |
globus/globus-cli | src/globus_cli/commands/_common.py | Python | apache-2.0 | 2,720 | 0.000735 | import sys
import click
from globus_cli.termio import FORMAT_SILENT, formatted_print
from ..services.transfer import CustomTransferClient
def transfer_task_wait_with_io(
transfer_client: CustomTransferClient,
meow,
heartbeat,
polling_interval,
timeout,
task_id,
timeout_exit_code,
) -> N... | )
# TODO: possibly update TransferClient.task_wait so that we don't
# need to do an extra fetch to get the | task status after completion
res = transfer_client.get_task(task_id)
formatted_print(res, text_format=FORMAT_SILENT)
status = res["status"]
if status == "SUCCEEDED":
click.get_current_context().exit(0)
else:
click.get_current_... |
alphagov/digitalmarketplace-api | migrations/versions/900_add_brief_is_a_copy.py | Python | mit | 461 | 0.006508 | """Add Brief.is_a_copy boolean, default False, nullable False
Revision ID: 890
Revises: 880
Create | Date: 2017-06-01 11:24:53.346954
"""
# revision identifiers, used by Alembic.
revision = '900'
down_revision = '890'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('briefs', sa.Column('is_a_copy', sa.Boolean(), server_default=sa.text(u'false'), nullable=False) | )
def downgrade():
op.drop_column('briefs', 'is_a_copy')
|
cryptapus/electrum-uno | lib/pem.py | Python | mit | 6,584 | 0.003493 | #!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without... | refix))
if end == -1:
raise SyntaxError("Missing PEM postfix")
s = s[start+len("-----BEGIN %s-----" % name) : end]
retBytes = a2b_base64(s) # May raise SyntaxError
return retBytes
def dePemList(s, name):
"""Decode a sequence of PEM blocks into a list of bytearrays.
The input must conta... | ame string, e.g. for
name="TACK BREAK SIG". Arbitrary text can appear between and before and
after the PEM blocks. For example:
" Created by TACK.py 0.9.3 Created at 2012-02-01T00:30:10Z -----BEGIN TACK
BREAK SIG-----
ATKhrz5C6JHJW8BF5fLVrnQss6JnWVyEaC0p89LNhKPswvcC9/s6+vWLd9snYTUv
YMEBdw69PU... |
malept/js-sphinx-inventory | sphinx_inventory/js/mdn.py | Python | apache-2.0 | 1,705 | 0 | # -*- coding: utf-8 -*-
from collections import defaultdict
import json
import logging
from ._compat import ElementTree, urlopen
MDN_SITEMAP = 'https://developer.mozilla.org/sitemaps/en-US/sitemap.xml'
SITEMAP_NS = 'http://www.sitemaps.org/schemas/sitemap/0.9'
log = logging.getLogger(__name__)
def parse():
"""... | ffix = url[81:]
parts = url_suffix.split('/')
if len(parts) == 1:
name = parts[0]
if name[0].isupper():
ref_type = 'class'
else:
ref_type = 'data'
| elif len(parts) == 2:
cls, attr = parts
with urlopen('{url}$json'.format(url=url)) as f:
metadata = json.loads(f.read().decode('utf-8'))
name = '{0}.{1}'.format(cls, attr)
if 'Method' in metadata['tags']:
ref_type = 'function'
... |
vintasoftware/tapioca-mandrill | testing.py | Python | bsd-3-clause | 299 | 0 |
from decouple import config
from tapioca_mandrill import Mandrill
from tapioca.exceptions import TapiocaException
api = Mandrill(key=config('KEY'))
try:
r = api.users(method='ping').post()
except TapiocaException as e:
print e.c | lient().data()
print e.client().respon | se().status_code
|
sjohannes/exaile | plugins/amazoncovers/__init__.py | Python | gpl-2.0 | 2,845 | 0.000351 | # Copyright (C) 2006 Adam Olsen
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 1, or (at your option)
# any later version.
#
# This program is distributed in the hope that it w... | '
def __init__(self):
self.starttime = 0
def find_covers(self, track, limit=-1):
"""
Searches amazon for album covers
"""
try:
artist = track.get_tag_raw('artist')[0]
album = track.get_tag_raw('album')[0]
except (AttributeError, TypeE... | []
# get the settings for amazon key and secret key
api_key = settings.get_option('plugin/amazoncovers/api_key', '')
secret_key = settings.get_option('plugin/amazoncovers/secret_key', '')
if not api_key or not secret_key:
logger.warning(
'Please enter your Am... |
braysia/CellTK | celltk/preprocess.py | Python | mit | 1,780 | 0.001685 | """
Any operations to make img from img.
python celltk/preprocess.py -f gaussian_laplace -i c0/img_00000000*
"""
# from scipy.ndimage import imread
import argparse
from utils.file_io import make_dirs, imsave
from utils.util import imread
from utils.parser import ParamParser, parse_image_files
import logging
from uti... | or function, param in zip(functions, params):
func = getattr(preprocess_operation, function)
img = func(img, **param)
imsave(img, output, holder.path)
logger.info("\tframe {0} done.".format(holder.frame))
| def main():
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input", help="images", nargs="*")
parser.add_argument("-o", "--output", help="output directory", type=str, default='temp')
parser.add_argument("-f", "--functions", help="functions", nargs="*")
parser.add_argument('-p', '--pa... |
Arceliar/bmwrapper | incoming.py | Python | mit | 9,110 | 0.010538 | import socket
import threading
import email.mime.text
import email.mime.image
import email.mime.multipart
import email.header
import bminterface
import re
import select
import logging
class ChatterboxConnection(object):
END = "\r\n"
def __init__(self, conn):
self.conn = conn
def __getattr__(self, na... | art.MIMEMultipart(' | mixed')
bodyText = email.mime.text.MIMEText(body[0], 'plain', 'UTF-8')
body = body[1:]
msg.attach(bodyText)
for item in body:
img = 0
itemType, itemData = [0], [0]
try:
itemType, itemData = item.split(';', 1)
itemType = itemType.split('/', 1)
e... |
mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/sklearn/cross_decomposition/cca_.py | Python | mit | 3,192 | 0 | from .pls_ import _PLS
__all__ = ['CCA']
class CCA(_PLS):
"""CCA Canonical Correlation Analysis.
CCA inherits from PLS with mode="B" and deflation_mode="canonical".
Read more in the :ref:`User Guide <cross_decomposition>`.
Parameters
----------
n_components : int, (default 2).
numb... | opy=True):
super(CCA, self).__init__(n_components=n_components, scale=scale,
deflation_mode= | "canonical", mode="B",
norm_y_weights=True, algorithm="nipals",
max_iter=max_iter, tol=tol, copy=copy)
|
Rosebotics/pymata-aio | pymata_aio/private_constants.py | Python | gpl-3.0 | 4,660 | 0.000215 | """
Copyright (c) 20115 Alan Yorinks All rights reserved.
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 library is dis... | porting for REPORT_ANALOG or REPORT_DIGITAL message
# sent to firmata
REPORTING_DISABLE = 0
# Stepper Motor Sub-commands
STEPPER_CONFIGURE = 0 # configure a stepper motor for operation
STEPPER_STEP = 1 # command a motor to move at the provided speed
STEPPER_LIBRARY_VERSION = 2 # used to get ... | set the max number of blocks to report
PIXY_SET_SERVOS = 1 # directly control the pan and tilt servo motors
PIXY_SET_BRIGHTNESS = 2 # adjust the brightness of the Pixy exposure
PIXY_SET_LED = 3 # control the color of the Pixy LED
# Pin used to store Pixy data
PIN_PIXY_MOSI = 11
|
davidam/python-examples | rdflib/rdflib-example.py | Python | gpl-3.0 | 1,020 | 0.004916 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2018 David Arroyo Menéndez
# Author: David Arroyo Menéndez <davidam@gnu.org>
# Maintainer: David Arroyo Menéndez <davidam@gnu.org>
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License ... | 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 GNU Emacs; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA,
import rdflib
g=rdflib.Graph()
g.load('... |
puttarajubr/commcare-hq | corehq/apps/hqpillow_retry/tasks.py | Python | bsd-3-clause | 1,845 | 0.002168 | from datetime import datetime, timedelta
from celery.schedules import crontab
from celery.task.base import periodic_task
from django.core.mail import mail_admins
from django.core.urlresolvers import reverse
from django.db.models.aggregates import Count
from django.template.loader import render_to_string
from dimagi.uti... | , html_message=html_message)
def for | mat_text_table(table):
col_width = [max(len(str(x)) for x in col) for col in zip(*table)]
output = []
for row in table:
inner = " | ".join("{0:{1}}".format(x, col_width[i]) for i, x in enumerate(row))
output.append("| {0} |".format(inner))
return output
|
cloudnull/tribble-api | tribble/engine/constructor.py | Python | gpl-3.0 | 13,205 | 0 | # =============================================================================
# Copyright [2013] [Kevin Carter]
# License Information :
# This software has no warranty, it is provided 'as is'. It is your
# responsibility to validate the behavior of the routines and its accuracy
# using the code provided. Consult the ... | self.user_specs = {
'max_tries': 15,
'timeout': 3600
}
self.zone_status = zone_status.ZoneState(cell=self.pa | cket)
def engine_setup(self):
"""Load connection engine.
this will set the driver user_data and deployment_methods.
"""
_engine = connection_engine.ConnectionEngine(
packet=self.packet
)
self.driver, self.user_data, self.deployment_methods = _engine.run(... |
jiadaizhao/LeetCode | 1301-1400/1376-Time Needed to Inform All Employees/1376-Time Needed to Inform All Employees.py | Python | mit | 524 | 0.005725 | import collections
class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[ | int], informTime: List[int]) -> int:
table = collections.defaultdict(list)
for i, m in enumerate(manager):
table[m].append(i)
Q = collections.deque([(headID, 0)])
mins = 0
while Q:
curr, time = Q.popleft()
mins = max(mins, time)
... | mins
|
hartym/bonobo | tests/util/test_objects.py | Python | apache-2.0 | 4,935 | 0.001621 | import operator
import pytest
from bonobo.util.objects import ValueHolder, Wrapper, get_attribute_or_create, get_name
from bonobo.util.testing import optional_contextmanager
class foo:
pass
class bar:
__name__ = "baz"
def test_get_name():
assert get_name(42) == "int"
assert get_name("eat at joe.... | apper("eat at joe.")) == "str"
assert get_name(Wrapper(str)) == "str"
assert get_name(Wrapper(object)) == "object"
assert get_name(Wrapper(foo)) == "foo"
assert get_name(Wrapper(foo())) == "foo"
assert get_name(Wrapper(bar)) == "bar"
assert get_name(Wrapper(bar())) == "baz"
assert get_name(W... | e)) == "get_name"
def test_valueholder():
x = ValueHolder(42)
assert x == 42
x += 1
assert x == 43
assert x + 1 == 44
assert x == 43
y = ValueHolder(44)
assert y == 44
y -= 1
assert y == 43
assert y - 1 == 42
assert y == 43
assert y == x
assert y is not x
... |
ag-sc/QALD | 4/scripts/XMLGenerator.py | Python | mit | 22,039 | 0.021877 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import xml.dom.minidom as dom
import xml.dom
import os
import socket
import re
import sys
import datetime
import codecs
from SPARQLWrapper import SPARQLWrapper, JSON
endpoint = "http://vtentacle.techfak.uni-bielefeld.de:443/sparql/"
sparql = SPARQLWrapper(endpoint)
# Doku... | end array with keywords and all language questions
| d[english_question_text] = [query,id,answertype,fusion,aggregation, onlydbo, questions, keywords, onlyesdbp]
except Exception as inst:
d[error_string] = ["error",id,answertype,fusion,aggregation, onlydbo, questions, keywords, onlyesdbp] |
cisco-openstack/tempest | tempest/api/compute/admin/test_floating_ips_bulk.py | Python | apache-2.0 | 3,760 | 0 | # Copyright 2014 NEC Technologies India Ltd.
# 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
#
# Unle... | super(FloatingIPsBulkAdminTestJSON, cls).resource_setup()
cls.ip_range = CONF.validation.floating_ip_range
cls.verify_unallocated_floating_ip_range(cls.ip_range)
@classmethod
| def verify_unallocated_floating_ip_range(cls, ip_range):
# Verify whether configure floating IP range is not already allocated.
body = cls.client.list_floating_ips_bulk()['floating_ip_info']
allocated_ips_list = map(lambda x: x['address'], body)
for ip_addr in netaddr.IPNetwork(ip_range... |
tobegit3hub/cinder_docker | cinder/zonemanager/fc_zone_manager.py | Python | apache-2.0 | 9,631 | 0 | # (c) Copyright 2014 Brocade Communications Systems Inc.
# All Rights Reserved.
#
# Copyright 2014 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
#
# ... | the target list
fabric_map = self.get_san_context(target_list)
LOG.debug("Fabric Map after context lookup: %s", fabric_map)
# iterate over each SAN and apply connection control
for fabric in fabric_map.keys():
connected_fabric = fabric... | t_list = fabric_map[fabric]
# get valid I-T map to add connection control
i_t_map = {initiator: t_list}
valid_i_t_map = self.get_valid_initiator_target_map(
i_t_map, True)
LOG.info(_LI("Final filtered map ... |
SNU-sunday/fisspy | fisspy/cm.py | Python | bsd-2-clause | 19,011 | 0.011993 | from __future__ import absolute_import, print_function, division
import numpy as np
from matplotlib.colors import LinearSegmentedColormap,ListedColormap
import sys
__author__ = "Juhyeong Kang "
__email__ = "jhkang@astro.snu.ac.kr"
def create_cdict(r, g, b):
i = np.linspace(0, 1, 256)
cdict = dict(
... | 127, 129,
130, 131, 133, 134, 135, 137, 138, 139, 140, 142, 143, 144, 146,
147, 148, 150, 151, 152, 153, 155, 156, 157, 159, 160, 161, 162,
164, 165, 166, 168, 169, 170, 172, 173, 174, 175, 177, 178, 179,
181, 182, 183, 185, 186, 187, 188, 190 | , 191, 192, 194, 195, 196,
197, 199, 200, 201, 203, 204, 205, 207, 208, 209, 210, 212, 213,
214, 216, 217, 218, 220, 221, 222, 223, 225, 226, 227, 229, 230,
231, 232, 234, 235, 236, 238, 239, 240, 242, 243, 244, 245, 247,
248, 249, 251, 252, 253, 255])... |
s-maj/integrations-core | postgres/check.py | Python | bsd-3-clause | 31,953 | 0.005164 | # (C) Datadog, Inc. 2010-2016
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
"""PostgreSQL check
Collects database-wide metrics and optionally per-relation metrics, custom metrics.
"""
# stdlib
import socket
# 3rd party
try:
import psycopg2
except ImportError:
psycopg2 = None
im... | AULT = {
'descriptors': [
('datname', 'db')
],
'metrics': {},
'query': """
SELECT datname,
%s
FROM pg_stat_database
WHERE datname not ilike 'template%%'
AND datname not il | ike 'rdsadmin'
""",
'relation': False,
}
COMMON_METRICS = {
'numbackends' : ('postgresql.connections', GAUGE),
'xact_commit' : ('postgresql.commits', RATE),
'xact_rollback' : ('postgresql.rollbacks', RATE),
'blks_read' : ('postgresql.disk_read', R... |
nataddrho/DigiCue-USB | Python3/src/bgapi.py | Python | mit | 13,154 | 0.002585 | #!/usr/bin/env python
# Nathan Rhoades 4/13/2021
import platform
import math
import bglib
import serial
import time
import datetime
import optparse
import signal
import sys
import struct
import importlib
class Bluegiga():
def __init__(self, dcb, ser, debugprint=False):
self.dcb = dcb
self.ser ... | -1]])
self.dprint("Connected to %s" % self.remoteAddressString)
self.connection_handle = args['connection']
self.ble.send_command(self.ser, self.ble.ble_cmd_attclient_read_by_group_type(
args['connection'], 0x0001, 0xFFFF, list(reversed(self.uuid_service))))
... | , sender, args):
# found "service" attribute groups (UUID=0x2800), check for CRP service
#if args['uuid'] == list(reversed(self.uuid_crp_service)):
if args['uuid'] == bytearray(self.uuid_crp_service)[::-1]:
self.dprint(
"Found attribute group for CRP service: start=%... |
safwanrahman/linuxdesh | kitsune/users/migrations/0006_add_migration_user.py | Python | bsd-3-clause | 7,501 | 0.007466 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from django.contrib.auth.hashers import make_password
class Migration(DataMigration):
def forwards(self, orm):
"""Adds a user to be used for migrations."""
# ``make_passw... | utoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
| u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.mo... |
billyhunt/osf.io | website/addons/base/serializer.py | Python | apache-2.0 | 7,369 | 0.000679 | import abc
from framework.auth.decorators import collect_auth
from website.util import api_url_for, web_url_for
class AddonSerializer(object):
__metaclass__ = abc.ABCMeta
# TODO take addon_node_settings, addon_user_settings
def __init__(self, node_settings=None, user_settings=None):
self.node_se... | perty
def serialized_accounts(self):
return [
self.serialize_account(each)
for each in self.user_settings.external_accounts
]
@property
def serialized_user_settings(self):
retval = super(OAuthAddonSerializer, self).serialized_user_set | tings
retval['accounts'] = []
if self.user_settings:
retval['accounts'] = self.serialized_accounts
return retval
def serialize_account(self, external_account):
if external_account is None:
return None
return {
'id': external_account._id,
... |
mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/sklearn/mixture/gaussian_mixture.py | Python | mit | 27,687 | 0 | """Gaussian Mixture Model."""
# Author: Wei Xue <xuewei4d@gmail.com>
# Modified by Thierry Guillemot <thierry.guillemot.work@gmail.com>
# License: BSD 3 clause
import numpy as np
from scipy import linalg
from .base import BaseMixture, _check_shape
from ..externals.six.moves import zip
from ..utils import check_arra... |
X : array-like, shape (n_samples, n_features)
The input data array.
resp : array-like, shap | e (n_samples, n_components)
The responsibilities for each data sample in X.
reg_covar : float
The regularization added to the diagonal of the covariance matrices.
covariance_type : {'full', 'tied', 'diag', 's |
andrewjrobinson/SportsReview | sportsreview/support/qtlib/pyside.py | Python | lgpl-3.0 | 1,959 | 0.009188 | # /*******************************************************************************
# * (c) Andrew Robinson (andrewjrobinson@gmail.com) 2014 *
# * *
# * This file is part of SportsReview. ... | *
# *******************************************************************************/
'''
Standardisation of PySide symbols
Created on 19/04/2014
@author: Andrew Robinson
'''
__all__ = ['QtCore', 'QtGui', 'Slot', 'Signal', '__implementation__', '__version__']
... | ementation__ = 'PySide'
__version__ = PySide.__version__
|
initOS/odoo-addons | website_product_gross_net/__openerp__.py | Python | agpl-3.0 | 468 | 0 | {
'name': 'Website Gross/Net Price (B2B | /B2C)',
'summary': 'Website Product Gross/Net Price (B2B/B2C)',
'category': 'Website',
'version': '1.0',
"sequence": 10,
'website': 'http://wt-io-it.at',
'author': 'WT-IO-IT GmbH',
'depends': ['website_sale_options', 'account_product_gross_net'],
'data': [
'views/templates.xml',
... | ation': True,
'installable': True,
}
|
fengxiaoiie/volatility | volatility/plugins/overlays/windows/win2003.py | Python | gpl-2.0 | 6,956 | 0.010926 | # Volatility
# Copyright (c) 2008-2013 Volatility Foundation
#
# This file is part of Volatility.
#
# Volatility is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your o... | e):
overlay = {'VOLATILITY_MAGIC': [ None, {
'DTBSignature': [ None, ['VolatilityMagic', dict(value = "\x03\x00\x1b\x00")]]}
]}
profile.merge_overlay(overlay)
class Win2003x86DTB(obj.ProfileModification):
before = ['WindowsOverlay']
... | 'minor': lambda x: x == 2}
def modification(self, profile):
overlay = {'VOLATILITY_MAGIC': [ None, {
'DTBSignature': [ None, ['VolatilityMagic', dict(value = "\x03\x00\x1e\x00")]]}
]}
profile.merge_overlay(overlay)
class Win2003x... |
endlessm/chromium-browser | tools/origin_trials/check_token.py | Python | bsd-3-clause | 8,056 | 0.01142 | #!/usr/bin/env python
# Copyright (c) 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utility for validating and inspecting origin trial token | s
usage: check_token.py [-h] [--use-chrome-key |
--use-test-key |
--private-key-file KEY_FILE]
"base64-encoded token"
Run "check_token.py -h" for more help on | usage.
"""
from __future__ import print_function
import argparse
import base64
from datetime import datetime
import json
import os
import struct
import sys
import time
script_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(script_dir, 'third_party', 'ed25519'))
import ed25519
# Ver... |
xzturn/tensorflow | tensorflow/python/framework/op_callbacks_test.py | Python | apache-2.0 | 33,617 | 0.004194 | # Copyright 2019 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... | ut.shape)
instrumented_outputs.append(instrumented_output)
return instrumented_outputs
def reset(self):
self.eager_op_types = []
self.eager_op_names = | []
self.eager_attrs = []
self.eager_graphs = []
self.eager_inputs = []
self.graph_op_types = []
self.graph_op_names = []
self.graph_attrs = []
self.graph_graphs = []
self.graph_graph_versions = []
self.graph_inputs = []
# A dict mapping tensor name (e.g., "MatMut_10") to a list ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.