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 |
|---|---|---|---|---|---|---|---|---|
stuart-warren/django-s3-proxy | proxy/urls.py | Python | apache-2.0 | 214 | 0.004673 | from django.conf.ur | ls import patterns, url
from proxy import views
urlpatterns = patterns('',
url(r'^$', views.search, name='search'),
url(r'^(?P<bucket_name>\S+?)(?P<key>/\S*)', views.get, name= | 'get')
)
|
Manexware/medical | oemedical/oemedical_medicament_category/oemedical_medicament_category.py | Python | gpl-2.0 | 589 | 0.011885 | from openerp import models,fields
class OeMedicalMedicamentCategory(models.Model):
_name = 'oemedical.medicament.category'
childs = fields.One2many('oemedical.medicament.category',
'parent_id', string='Children', )
name = fields.Char(size=256, string='Name', requ | ired=True)
parent_id = fields.Many2one('oemedical.medicament.category',
string='Parent', select=True)
_c | onstraints = [
(models.Model._check_recursion, 'Error ! You cannot create recursive \n'
'Category.', ['parent_id'])
] |
andyneff/voxel-globe | voxel_globe/task/views.py | Python | mit | 1,192 | 0.026846 | from django.shortcuts import render, HttpResponse
import os
# Create your views here.
def status(request, task_id):
from celery.result import AsyncResult
task = AsyncResult(task_id);
task.traceback_html = tracebackToHtml(task.traceback)
return render(request, 't | ask/html/task_status.html',
{'t | ask': task,
'celery_url':'%s:%s' % (os.environ['VIP_FLOWER_HOST'],
os.environ['VIP_FLOWER_PORT'])})
def tracebackToHtml(txt):
html = str(txt).replace(' '*2, ' '*4)
html = html.split('\n')
html = map(lambda x: '<div style="text-indent: -4em; padding... |
devilry/trix2 | trix/trix_core/tests/test_trix_markdown.py | Python | bsd-3-clause | 421 | 0 | from django.test import TestCase
from trix.trix_core import trix_markdown
class TestTrix | Markdown(TestCase):
def test_simple(self):
self.assertEqual(
| trix_markdown.assignment_markdown('# Hello world\n'),
'<h1>Hello world</h1>')
def test_nl2br(self):
self.assertEqual(
trix_markdown.assignment_markdown('Hello\nworld'),
'<p>Hello<br>\nworld</p>')
|
samyoyo/3vilTwinAttacker | 3vilTwin-Attacker.py | Python | mit | 1,843 | 0.01465 | #!/usr/bin/env python2.7
#The MIT License (MIT)
#Copyright (c) 2015-2016 mh4x0f P0cL4bs Team
#Permission is hereby granted, free of charge, to any perso | n obtaining a copy of
#this software and associated documentation f | iles (the "Software"), to deal in
#the Software without restriction, including without limitation the rights to
#use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
#the Software, and to permit persons to whom the Software is furnished to do so,
#subject to the following conditions:
#The ab... |
SINGROUP/pycp2k | pycp2k/classes/_implicit_psolver1.py | Python | lgpl-3.0 | 709 | 0.002821 | from pycp2k.inputsection import InputSection
from ._dielectric_cube1 import _dielectric_cube1
from ._dirichlet_bc_cube1 import _dirichlet_bc_cube1
from ._dirichlet_cstr_charge_cube1 import _dirichlet_cstr_charge_cube1
class _implicit_psolver1(InputSection):
def __init__(self):
InputSe | ction.__init__(self)
self.DIELECTRIC_CUBE = _dielectric_cube1()
self.DIRICHLET_BC_CUBE = _dirichlet_bc_cube1()
self.DIRICHLET_CSTR_CHARGE_CUBE = _dirichlet_cstr_charge_cube1()
self._name = "IMPLICIT_PSOLVER"
self._subsections = {'DIRICHLET_BC_CUBE': 'DIRIC | HLET_BC_CUBE', 'DIRICHLET_CSTR_CHARGE_CUBE': 'DIRICHLET_CSTR_CHARGE_CUBE', 'DIELECTRIC_CUBE': 'DIELECTRIC_CUBE'}
|
rain1024/underthesea | underthesea/classification/model_fasttext.py | Python | gpl-3.0 | 2,185 | 0 | import random
from os.path import join, dirname
import numpy as np
from sklearn.base import ClassifierMixin, BaseEstimator
import fasttext as ft
from underthesea.util.file_io import write
import os
from underthesea.util.singleton import Singleton
class FastTextClassifier(ClassifierMixin, BaseEstimator):
def __i... | if label == 0:
label = 1
score = 1 - score
return [label, score]
output_ = [transform_item(item) for item in output_]
output1 = np.array(output_)
return output1
@Singleton
class FastTextPredictor:
def __init__(self):
filepath = ... | asttext.model")
self.estimator = ft.load_model(filepath)
def tranform_output(self, y):
y = y[0].replace("__label__", "")
y = y.replace("-", " ")
return y
def predict(self, X):
X = [X]
y_pred = self.estimator.predict(X)
y_pred = [self.tranform_output(item... |
open-o/nfvo | lcm/lcm/ns/vls/urls.py | Python | apache-2.0 | 1,036 | 0.000965 | # Copyright 2016 ZTE 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 ... | 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 django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
from lcm.ns.vls.... | url(r'^openoapi/nslcm/v1/ns/vls$', VlView.as_view()),
url(r'^openoapi/nslcm/v1/ns/vls/(?P<vl_inst_id>[0-9a-zA-Z_-]+)$', VlDetailView.as_view()),
)
urlpatterns = format_suffix_patterns(urlpatterns)
|
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/markdown/extensions/nl2br.py | Python | agpl-3.0 | 765 | 0.002614 | """
NL2BR Extension
===============
A Python-Markdown extension to treat newlines as hard breaks; like
GitHub-flavored Markdown does.
Usage:
>>> import markdown
>>> print markdown.markdown('line 1\\nline 2', extensions=['nl2br'])
<p>line 1<br />
line 2</p>
Copyright 2011 [Brian Neal](http://deathofa... | br_tag = markdown | .inlinepatterns.SubstituteTagPattern(BR_RE, 'br')
md.inlinePatterns.add('nl', br_tag, '_end')
def makeExtension(configs=None):
return Nl2BrExtension(configs)
|
feuervogel/django-taggit-templatetags | taggit_templatetags/tests/models.py | Python | bsd-3-clause | 379 | 0.015831 | fro | m django.db import models
from taggit.managers import TaggableManager
class BaseModel(models.Model):
name = models.CharField(max_length=50, unique=True)
tags = TaggableManager()
def __unicode__(self):
return self.name
class Meta(object):
abstract = True
class AlphaModel(Bas... | l(BaseModel):
pass
|
micumatei/learning-goals | Probleme/Solutii/Find_Cost_of_Tile_to_Cover_WxH_Floor/mmicu/python/main.py | Python | mit | 1,283 | 0.000779 | #!/usr/bin/env python3
"""
Calculate the total cost of tile it would take to cover a floor
plan of width and height, using a cost entered by the user.
"""
from __future__ import print_function
import argparse
import sys
class App(object):
"""Application."""
def __init__(self, args):
self._raw_args =... | f get_cost(widht, height, cost):
"""Compute the cost."""
| return (widht * height) * float(cost)
if __name__ == "__main__":
App(sys.argv[1:]).run()
|
csherwood-usgs/landlab | landlab/ca/examples/diffusion_in_gravity.py | Python | mit | 5,014 | 0.01077 | #!/usr/env/python
"""
diffusion_in_gravity.py
Example of a continuous-time, stochastic, pair-based cellular automaton model,
which simulates diffusion by random particle motion in a gravitational field.
The purpose of the example is to demonstrate the use of an OrientedRasterLCA.
GT, September 2014
"""
from __future... | '%)')
next_report = current_real_time + report_interval
# Run the model forward in time until the next output step
ca.run(current_time+plot_interval, ca.node_state,
plot_each_transition=False) #, plotter=ca_plotter)
current_time += plot_interval
# Plot the cu... | of_node_rows):
for c in range(ca.grid.number_of_node_columns):
n -= 1
print('{0:.0f}'.format(ca.node_state[n]), end=' ')
print()
# FINALIZE
# Plot
ca_plotter.finalize()
if __name__ == "__main__":
main()
|
mmnelemane/nova | nova/tests/functional/test_extensions.py | Python | apache-2.0 | 1,588 | 0 | # Copyright 2011 Justin Santa Barbara
# 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 requ... | S" 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 oslo_config import cfg
from oslo_log import log as logging
# Import extensions to pull in osapi_compute_extension CO... | __name__)
class ExtensionsTest(integrated_helpers._IntegratedTestBase):
_api_version = 'v2'
def _get_flags(self):
f = super(ExtensionsTest, self)._get_flags()
f['osapi_compute_extension'] = CONF.osapi_compute_extension[:]
f['osapi_compute_extension'].append(
'nova.tests.un... |
alexmorozov/templated-docs | example/invoices/views.py | Python | mit | 643 | 0.001555 | #--coding: utf8--
from django.shortcuts import render
f | rom templated_docs import fill_template
from templated_docs.http import FileResponse
from invoices.forms import InvoiceForm
def invoice_view(request):
form = InvoiceForm(request.POST or None)
if form.is_valid():
doctype = form.cleaned_data['format']
filename = fill_template(
'inv... | eaned_data,
output_format=doctype)
visible_filename = 'invoice.{}'.format(doctype)
return FileResponse(filename, visible_filename)
else:
return render(request, 'invoices/form.html', {'form': form})
|
stephenjelfs/aws-iot-gddev2016 | controlUnit.py | Python | mit | 3,371 | 0.00445 | #!/usr/bin/env python
import argparse
import json
import time
import logging
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient
import RPi.GPIO as GPIO
parser = argparse.ArgumentParser(description='Lightbulb control unit.')
parser.add_argument('-e', '--endpoint', required=True, help='The AWS Iot endpoint.')
... | e shadow JSON doc
ControlUnit.shadowDelete(lightBulbShadowCallback_Delete, 5)
# Update shadow
def updateShadow(color):
JSONPayload = '{"state":{"desired":{"color":"' + color + '"}}}'
ControlUnit.shadowUpdate(JSONPayload, lightbulbShadowCallback_Update, 5)
RED = 9
GREEN = 10
BLUE = 11
GPIO.setmode(GPIO.BCM)
G... | )
lastButton = None
while True:
if (lastButton != RED and GPIO.input(RED) == False):
lastButton = RED
updateShadow("red")
if (lastButton != GREEN and GPIO.input(GREEN) == False):
lastButton = GREEN
updateShadow("green")
if (lastButton != BLUE and GPIO.input(BLUE)== False):
... |
laurentb/weboob | modules/lyricsdotcom/module.py | Python | lgpl-3.0 | 1,693 | 0.000591 | # -*- coding: utf-8 -*-
# Copyright(C) 2016 Julien Veyssier
#
# This file is part of a weboob module.
#
# This weboob module 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 Lice... | ols.backend import Module
from weboob.tools.compat import quote_plus
from .browser import LyricsdotcomBrowser
__all__ = ['LyricsdotcomModule']
class LyricsdotcomModule(Module, CapLyrics):
NAME = 'lyricsdotcom'
MAINTAINER = u'Julien Veyssier'
EMAIL = 'eneiluj@gmx.fr'
VERSION = '2.1'
DESCRIPTION ... | LICENSE = 'AGPLv3+'
BROWSER = LyricsdotcomBrowser
def get_lyrics(self, id):
return self.browser.get_lyrics(id)
def iter_lyrics(self, criteria, pattern):
return self.browser.iter_lyrics(criteria, quote_plus(pattern.encode('utf-8')))
def fill_songlyrics(self, songlyrics, fields):
... |
bmazin/SDR | Projects/FirmwareTests/darkDebug/phaseStreamTest.py | Python | gpl-2.0 | 17,347 | 0.022655 | """
File: phaseStreamTest.py
Author: Matt Strader
Date: Feb 18, 2016
Firmware: pgbe0_2016_Feb_19_2018.fpg
This script inserts a phase pulse in the qdr dds table and sets up the fake adc lut. It checks snap blocks for each stage of the channelization process. In the end the phase pulse should be recover... | e(0,len(liSample))
ax.plot(ddcTimes,liSample,'k.-',label='ddcOut')
ax. | set_title('I')
ax.legend(loc='best')
return {'bin':(bi+1.j*bq),'chan':(ci+1.j*cq),'dds':(di+1.j*dq),'mix':(mi+1.j*mq),'ddcOut':(li+1.j*lq),'chanCtr':ctr,'ddsCtr':dctr,'expectedMix':expectedMix,'rawPhase':rawPhase,'filtPhase':filtPhase,'trig':trig,'trig2':trig2,'basePhase':basePhase}
def setSingleChanSel... |
OCA/stock-logistics-warehouse | stock_move_auto_assign/models/__init__.py | Python | agpl-3.0 | 55 | 0 | from . import stock_move
fr | om . impo | rt product_product
|
trabucayre/gnuradio | gr-blocks/python/blocks/qa_max.py | Python | gpl-3.0 | 5,142 | 0.00739 | #!/usr/bin/env python
#
# Copyright 2007,2010,2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
from gnuradio import gr, gr_unittest, blocks
import math
class test_max(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()... | _data1 = [1, 1, 1, 1, 1, 1]
expected_result = [max(x,y) for x,y in zip(src_data0, src_data1)]
src0 = blocks.vector_source_s(src_data0)
src1 = blocks.vector_source_s(src_data1)
op = blocks.max_ss(1)
dst = blocks.vector_sink_s()
self.tb.connect(src0, | (op, 0))
self.tb.connect(src1, (op, 1))
self.tb.connect(op, dst)
self.tb.run()
result_data = dst.data()
self.assertEqual(expected_result, result_data)
def stest_s004(self):
dim = 2
src_data0 = [0, 2, -3, 0, 12, 0]
src_data1 = [1, 1, 1, 1, 1, 1]
... |
guandalf/projecteuler | pe0001.py | Python | mit | 155 | 0.012903 | def pe0001(upto):
total = 0
for i in range(upto):
if i % 3 == 0 or i % 5 == 0:
total += i
return total
print(pe0001(10 | 00)) | |
mozilla/caseconductor-ui | ccui/environments/views.py | Python | gpl-3.0 | 1,892 | 0.002643 | # Case Conductor is a Test Case Management system.
# Copyright (C) 2011 uTest Inc.
#
# This file is part of Case Conductor.
#
# Case Conductor 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... | TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public Licens | e for more details.
#
# You should have received a copy of the GNU General Public License
# along with Case Conductor. If not, see <http://www.gnu.org/licenses/>.
from django.shortcuts import redirect
from django.template.response import TemplateResponse
from ..core.util import get_object_or_404
from ..users.decorat... |
SteveViss/readthedocs.org | readthedocs/core/middleware.py | Python | mit | 6,904 | 0.001593 | import logging
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.core.cache import cache
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from django.http import Http404
from readthedocs.projects.models import Project, Domain
log = logg... | TE.format(
msg='X-RTD-Slug header detetected: %s' % request.slug, **log_kwargs))
# Try header first, then DNS
elif not hasattr(request, 'domain_object'):
try:
slug = cache.get(host)
if not slug:
f... | omain = answer.target.to_unicode().lower()
slug = domain.split('.')[0]
cache.set(host, slug, 60 * 60)
# Cache the slug -> host mapping permanently.
log.debug(LOG_TEMPLATE.format(
msg='CNAME cached... |
illicium/ccss2edr | ccss2edr/dumpedr.py | Python | mit | 1,581 | 0 | #!/usr/bin/env python3
import argparse
import dataclasses
| from array import array
from .edr import (EDRHeader, EDRDisplayDataHeader, EDRSpectralDataHeader)
def parse_args():
parser = argparse.ArgumentParser(description='Print .edr file')
parser.add_argument('edr',
| type=argparse.FileType('rb'),
help='.edr input filename')
return parser.parse_args()
def main():
args = parse_args()
print('EDR Header:')
edr_header = EDRHeader.unpack_from(args.edr.read(EDRHeader.struct.size))
print_dataclass(edr_header, indent=1)
for set_n... |
Cheaterman/kivy | kivy/input/provider.py | Python | mit | 1,082 | 0 | '''
Motion Event Provider
=====================
Abstract class for the implementation of a
:class:`~kivy.input.motionevent.MotionEvent`
provider. The implementation must support the
:meth:` | ~MotionEventProvider.start`, :meth:`~MotionEventProvider.stop` and
:meth:`~MotionEventProvider.update` methods.
'''
__all__ = ('MotionEventProvider', )
class MotionEventProvider(object):
'''Base class for a provider.
'''
def __init__(self, device, args):
self.device = device
| if self.__class__ == MotionEventProvider:
raise NotImplementedError('class MotionEventProvider is abstract')
def start(self):
'''Start the provider. This method is automatically called when the
application is started and if the configuration uses the current
provider.
... |
samitnuk/online_shop | apps/orders/migrations/0002_auto_20170317_2119.py | Python | mit | 1,976 | 0.002614 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-17 19:19
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_depende... | migrations.AddField(
model_name='order',
name='carrier',
field=models.CharField(default='Нова пошта', max_length=250, verbose_name='Перевізник'),
preserve_default=False,
),
migrations.AddField(
model_name='order',
name='phone_... | ose_name='Номер телефону'),
preserve_default=False,
),
migrations.AddField(
model_name='order',
name='user',
field=models.ForeignKey(default='1', on_delete=django.db.models.deletion.CASCADE, related_name='orders', to=settings.AUTH_USER_MODEL),
... |
OmegaDroid/quokka | utils/templatetags/utils.py | Python | mit | 767 | 0.005215 | from django import | template
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def img_tag(obj, cls=""):
if hasattr(obj, "img"):
if obj.img:
return mark_safe("<img class='" + cls + "' src='" + obj.img.url + "'/>")
return mark_safe("<span class='glyphicon glyphicon-... | :
return ""
@register.filter
def object_link(obj):
try:
return ("/" + type(obj).__name__ + "/" + str(obj.id) + "/").lower()
except:
return ""
@register.filter
def object_anchor(obj):
return mark_safe("<a href='" + object_link(obj) + "'>" + str(obj) + "</a>")
|
xapharius/mrEnsemble | Engine/src/jobs/validation_job.py | Python | mit | 746 | 0.00134 | '''
Created on Mar 19, 2014
@author: Simon
'''
from engine.engine_job import EngineJob
class ValidationJob(EngineJob):
'''
M/R job for validating a trained model.
'''
def mapper(self, key, values):
data_processor = self.get_data_processor()
data_processor.set_data(values)
dat... | yield 'validation', validator.validate(alg, data_set)
def reducer(self, key, values):
vals = list(values)
yield key, self.get_validator().aggregate(vals)
if __name__ == '__m | ain__':
ValidationJob.run()
|
t3dev/odoo | odoo/addons/test_testing_utilities/models.py | Python | gpl-3.0 | 6,753 | 0.002962 | # -*- coding: utf-8 -*-
from __future__ import division
from odoo import api, fields, models
class A(models.Model):
_name = 'test_testing_utilities.a'
_description = 'Testing Utilities A'
f1 = fields.Char(required=True)
f2 = fields.Integer(default=42)
f3 = fields.Integer()
f4 = fields.Integer(... | ties.sub', 'parent_id')
@api.onchange('val | ue', 'subs')
def _onchange_values(self):
self.v = self.value + sum(s.value for s in self.subs)
class O2MSub(models.Model):
_name = 'test_testing_utilities.sub'
_description = 'Testing Utilities Subtraction'
name = fields.Char(compute='_compute_name')
value = fields.Integer(default=2)
v... |
dcrankshaw/clipper | integration-tests/deploy_xgboost_models.py | Python | apache-2.0 | 4,355 | 0.000459 | import os
import sys
if sys.version_info >= (3, 0):
sys.exit(0)
import requests
import json
import numpy as np
import time
import logging
import xgboost as xgb
cur_dir = os.path.dirname(os.path.abspath(__file__))
from test_utils import (create_docker_connection, BenchmarkException, headers,
... | nfig(
format='%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
datefmt='%y-%m-%d:%H:%M:%S',
level=logging.INFO)
logger = logging.getLogger(__name__)
app_name = "xgboost-test"
model_name = "xgboost-model"
def deploy_and_test_model(clipper_conn,
| model,
version,
predict_fn,
link_model=False):
deploy_python_closure(
clipper_conn,
model_name,
version,
"integers",
predict_fn,
pkgs_to_install=['xgboost'])
time.s... |
piMoll/SEILAPLAN | lib/reportlab/graphics/charts/doughnut.py | Python | gpl-2.0 | 19,476 | 0.011861 | #Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
#history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/graphics/charts/doughnut.py
# doughnut chart
__version__='3.3.0'
__doc__="""Doughnut chart
Produces a circular chart like the doughnut charts produced by Excel.
C... | ,
slices = AttrMapValue(None, desc="collection of sector descriptor objects"),
simpleLabels = AttrMapValue(isBoolean, desc="If true(default) use String not super duper WedgeLabel"),
# advanced usage
checkLabelOverlap = AttrMapValue(isBoolean, desc="If true check and attempt | to fix\n standard label overlaps(default off)",advancedUsage=1),
sideLabels = AttrMapValue(isBoolean, desc="If true attempt to make chart with labels along side and pointers", advancedUsage=1),
innerRadiusFraction = AttrMapValue(isNumberOrNone,
desc='None or the fraction of the radius t... |
r-alex-hall/fontDevTools | scripts/imgAndVideo/color_growth.py | Python | gpl-3.0 | 45,584 | 0.005484 | # DESCRIPTION
# Renders a PNG image li | ke bacteria that mutate color as they spread. TRY IT. The output is awesome.
# DEPENDENCIES
# python 3 with numpy, queue, and pyimage modules installed (and others--see the import statements).
# USAGE
# Run this script through a Python interpreter without any parameters, and it will use a default set of parameters:
#... | h/to_this_script/ --help
# NOTES
# - GitHub user `scribblemaniac` sped up this script (with a submitted pull request) by orders of magnitute vs. an earlier version of the script. An image that took seven minutes to render took 5 seconds after speedup.
# - Output file names are based on the date and time and random char... |
OpenCMISS-Dependencies/slepc | config/packages/petsc.py | Python | lgpl-3.0 | 6,234 | 0.022137 | #
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | -
# SLEPc - Scalable Library for Eigenvalue Problem Computations
# Copyrigh | t (c) 2002-2015, Universitat Politecnica de Valencia, Spain
#
# This file is part of SLEPc.
#
# SLEPc is free software: you can redistribute it and/or modify it under the
# terms of version 3 of the GNU Lesser General Public License as published by
# the Free Software Foundation.
#
# SLEPc is distributed in the... |
ghwatson/SpanishAcquisitionIQC | spacq/gui/display/table/generic.py | Python | bsd-2-clause | 4,604 | 0.03258 | from numpy import array, compress, zeros
import wx
from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin
from spacq.interface.list_columns import ListParser
"""
Embeddable, generic, virtual, tabular display.
"""
class VirtualListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin):
"""
A generic virtual list.
"""
ma... | elf.display_data[:,i] = [str(x)[:self.max_value_len] for x in data[:,i]]
self.Refresh()
def apply_filter(self, f, afresh=False):
"""
Set the data to be the | old data, along with the application of a filter.
f is a function of two parameters: the index of the row and the row itself.
f must return True if the row is to be kept and False otherwise.
If afresh is True, all old filtered data is discarded.
Otherwise, a new filter can be quickly applied.
"""
if afre... |
daboross/screeps-warreport | warreport/constants.py | Python | mit | 280 | 0 | ranged_attacker = "ranged attacker" |
melee_attacker = "melee attacker"
healer = 'healer'
dismantling_attacker = 'dismantler'
general_attacker = 'general attacker'
tough_attacker = 'tough guy'
work_and_carry_attacker = 'multi-purpose attacker'
civilian = 'civilian'
scout = | 'scout'
|
Raag079/self-driving-car | Term01-Computer-Vision-and-Deep-Learning/Labs/05-CarND-Alexnet-Feature-Extraction/feature_extraction.py | Python | mit | 1,499 | 0.002668 | import time
import tensorflow as tf
import numpy as np
import pandas as pd
from scipy.misc import imread
from alexnet import AlexNet
sign_names = pd.read_csv('signnames.csv')
nb_classes = 43
x = tf.placeholder(tf.float32, (None, 32, 32, 3))
resized = tf.image.resize_images(x, (227, 227))
# NOTE: By setting `feature_... | ` below.
shape = (fc7.get_shape | ().as_list()[-1], nb_classes) # use this shape for the weight matrix
fc8W = tf.Variable(tf.truncated_normal(shape, stddev=1e-2))
fc8b = tf.Variable(tf.zeros(nb_classes))
logits = tf.nn.xw_plus_b(fc7, fc8W, fc8b)
probs = tf.nn.softmax(logits)
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
# R... |
svinota/pyrouted | pyrouted/api.py | Python | gpl-2.0 | 2,803 | 0 | import json
import bottle
from pyrouted.util import make_spec
def route(method, path):
def decorator(f):
f.http_route = path
f.http_method = method
return f
return decorator
class APIv1(object):
prefix = '/v1'
def __init__(self, ndb, config):
self.ndb = ndb
... | 'routes',
'neighbours',
| 'vlans',
'bridges'))
def view(self, name):
ret = []
obj = getattr(self.ndb, name)
for line in obj.dump():
ret.append(line)
return bottle.template('{{!ret}}', ret=json.dumps(ret))
@route('GET', '/query/<name:re... |
Statoil/libecl | python/tests/legacy_tests/test_test.py | Python | gpl-3.0 | 358 | 0.002793 | from ert.test imp | ort TestRun
from ert.test i | mport path_exists
from ert.test import SourceEnumerator
from ert.test import TestArea , TestAreaContext
from ert.test import ErtTestRunner
from ert.test import PathContext
from ert.test import LintTestCase
from ert.test import ImportTestCase
from tests import EclTest
class ErtLegacyTestTest(EclTest):
pass
|
vpodzime/lvm-dubstep | lvmdbus/automatedproperties.py | Python | gpl-3.0 | 6,035 | 0 | # 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 program is distributed in the hope that it will be useful,
# bu... | 15, Tony Asleson <tasleson@redhat.com>
import dbus
import cfg
from utils import get | _properties, add_properties, get_object_property_diff
from state import State
# noinspection PyPep8Naming
class AutomatedProperties(dbus.service.Object):
"""
This class implements the needed interfaces for:
org.freedesktop.DBus.Properties
Other classes inherit from it to get the same behavior
"""... |
asydorchuk/robotics | python/robotics/robots/factory.py | Python | mit | 1,253 | 0.000798 | from RPi import GPIO as gpio
from robotics.actors.redbot_motor_actor import RedbotMotorActor
from robotics.interfaces.spi.mcp3008_spi_interface import MCP3008SpiInterface
from robotics.robots.aizek_robot import AizekRobot
from robotics.sensors.redbot_wheel_encoder_sensor import RedbotWheelEncoderSensor
from robotics.s... | rsensor = SharpIrDistanceSensor(spi, 3)
wheel_radius = 0.032
wheel_distance = 0.1
robot = AizekRobot(
left_motor=lmotor,
right_motor=rmotor,
wheel_encoder=wenc | oder,
left_distance_sensor=lsensor,
front_distance_sensor=fsensor,
right_distance_sensor=rsensor,
wheel_radius=wheel_radius,
wheel_distance=wheel_distance,
)
return robot
|
tynn/numpy | numpy/polynomial/tests/test_chebyshev.py | Python | bsd-3-clause | 20,348 | 0.000934 | """Tests for chebyshev module.
"""
from __future__ import division, absolute_import, print_function
import numpy as np
import numpy.polynomial.chebyshev as cheb
from numpy.polynomial.polynomial import polyval
from numpy.testing import (
assert_almost_equal, assert_raises, assert_equal, assert_,
)
def trim(x... | assert_equal(cheb.chebval(x, [1, 0]).shape, dims)
assert_equal(cheb.chebval(x, [1, 0, 0]).shape, dims)
def test_chebval2d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
#test exceptions
assert_raises(ValueError, cheb.chebval2d, x1, x2[:2], self.c2d)
#te... | x2, self.c2d)
assert_almost_equal(res, tgt)
#test shape
z = np.ones((2, 3))
res = cheb.chebval2d(z, z, self.c2d)
assert_(res.shape == (2, 3))
def test_chebval3d(self):
x1, x2, x3 = self.x
y1, y2, y3 = self.y
#test exceptions
assert_raises(V... |
uw-it-aca/course-dashboards | coursedashboards/migrations/0006_auto_20170918_1954.py | Python | apache-2.0 | 2,064 | 0.001938 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-09-18 19:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('coursedashboards', '0005_auto_20170915_2036'),
]
operations = [
migrations.Create... | ther(
name='courseofferingmajor',
unique_together=set([( | 'major', 'term', 'course')]),
),
]
|
juanpex/django-model-deploy | test_project/wsgi.py | Python | bsd-3-clause | 1,153 | 0.000867 | """
WSGI config for django_model_deploy project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_AP... | ustom 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
os.envi | ron.setdefault("DJANGO_SETTINGS_MODULE", "test_project.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_applic... |
sony/nnabla | python/test/function/test_div2.py | Python | apache-2.0 | 1,404 | 0 | # Copyright 2019,2020,2021 Sony 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... | and
# limitations under the License.
import pytest
im | port numpy as np
import nnabla.functions as F
from nbla_test_utils import list_context
ctxs = list_context('Div2')
@pytest.mark.parametrize("ctx, func_name", ctxs)
@pytest.mark.parametrize("seed", [313])
@pytest.mark.parametrize("inplace", [False, True])
def test_div2_double_backward(inplace, seed, ctx, func_name):
... |
mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/scipy/_lib/_version.py | Python | mit | 4,793 | 0.000209 | """Utility to compare (Numpy) version strings.
The NumpyVersion class allows properly comparing numpy version strings.
The LooseVersion and StrictVersion classes that distutils provides don't
work; they don't recognize anything like alpha/beta/rc/dev versions.
"""
import re
from scipy._lib.si | x import string_types
__all__ = ['NumpyVersion']
class NumpyVersion():
"""Parse and compare numpy version strings.
Numpy has the following versioning scheme (numbers given are examples; they
can be >9) in principle):
- Released version: '1.8.0', '1.8.1', etc.
- Alpha: '1.8.0a1', '1.8.0a2', etc... | dates: '1.8.0rc1', '1.8.0rc2', etc.
- Development versions: '1.8.0.dev-f1234afa' (git commit hash appended)
- Development versions after a1: '1.8.0a1.dev-f1234afa',
'1.8.0b2.dev-f1234afa',
'1.8.1rc1.dev-f1234afa', etc.
- Development v... |
acasadoquijada/bares | practica4/settings.py | Python | gpl-3.0 | 4,257 | 0.003993 | """
Django settings for practica4 project.
Generated by 'django-admin startproject' using Django 1.9.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os,... | ddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'practica4.urls'
TEMPLATES = [
{
'BACKEND | ': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_PATH],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.cont... |
loafbaker/django_launch_with_code | joins/forms.py | Python | mit | 211 | 0.018957 | from django im | port forms
from .models import Join
class EmailForm(forms.Form):
email = forms.EmailField()
class JoinForm(forms.ModelForm):
class Meta:
model = Join
fields = [ | "email",]
|
npuichigo/ttsflow | third_party/tensorflow/tensorflow/python/kernel_tests/string_to_hash_bucket_op_test.py | Python | apache-2.0 | 4,034 | 0.010659 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | -> 11430444447143000872 -> mod 10 -> 2
# Fingerprint64('d') -> 4470636696479570465 -> mod 10 -> 5
self.assertAllEqual([9, 2, 2, 5], result)
def testStringToOneHashBucketLegacyHash(self):
with self.test_session():
input_string = array_ops.placeholder(dtypes.string)
output = string_ops.stri... | HashBucketsLegacyHash(self):
with self.test_session():
input_string = array_ops.placeholder(dtypes.string)
output = string_ops.string_to_hash_bucket(input_string, 10)
result = output.eval(feed_dict={input_string: ['a', 'b', 'c']})
# Hash64('a') -> 2996632905371535868 -> mod 10 -> 8
# ... |
m3wolf/orgwolf | setup.py | Python | gpl-3.0 | 1,198 | 0 | import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='orgwolf',
version='0... | tended Audience :: Developers',
'License :: OSI Approved :: BSD License', # example license
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Internet :: WWW... | WWW/HTTP :: Dynamic Content',
],
)
|
aleksandarmilicevic/pygments-red | setup.py | Python | mit | 1,246 | 0 | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='pygments-red',
version='0.2',
description='Pygments lexer for Ruby + Red.',
keywords='pygments ruby red lexer',
license='MIT',
author='Aleksandar Milicevic',
author_email='aleks@csail.mit.edu',
url='https:... | nts >= 1.4'],
entry_points='''[pygments.lexers]
ruby193=pygments_red:Ruby193Lexer
arby=pygments_red:ARbyLexer
red=pygments_red:RedLexer
sunny=pygments_red:SunnyLexer
| handlebars=pygments_red:HandlebarsLexer
html+handlebars=pygments_red:HandlebarsHtmlLexer
slang=pygments_red:SlangLexer
errb=pygments_red:ErrbLexer
ered=pygments_red:EredLexer
redhtml=pygments_red:RedHtml... |
Julian/cardboard | cardboard/cards/sets/stronghold.py | Python | mit | 26,294 | 0.000038 | from cardboard import types
from cardboard.ability import (
AbilityNotImplemented, spell, activated, triggered, static
)
from cardboard.cards import card, common, keywords, match
@card("Crovax the Cursed")
def crovax_the_cursed(card, abilities):
def crovax_the_cursed():
return AbilityNotImplemented
... | ef shard_phoenix():
return AbilityNotImplemented
def shard_phoenix():
return AbilityNotImplemented
def shard_phoenix():
return AbilityNotImplemented
return shard_phoenix, shard_phoenix, shard_phoenix,
@card("Skyshroud Archer")
def skyshroud_archer(card, abilities):
def skys... | Mimic")
def mask_of_the_mimic(card, abilities):
def mask_of_the_mimic():
return AbilityNotImplemented
def mask_of_the_mimic():
return AbilityNotImplemented
return mask_of_the_mimic, mask_of_the_mimic,
@card("Provoke")
def provoke(card, abilities):
def provoke():
return Abil... |
wateraccounting/wa | Collect/JRC/__init__.py | Python | apache-2.0 | 647 | 0.003091 | # -*- coding: utf-8 -*-
"""
Authors: Tim Hessels
UNESCO-IHE 2017
Contact: t.hessels@unesco-ihe.org
Repository: http | s://github.com/wateraccounting/wa
Module: Collect/JRC
Description:
This module downloads JRC water occurrence data from http://storage.googleapis.com/global-surface-water/downloads/.
Use the JRC.Occurrence function to
download and create a water occurrence image in Gtiff format.
The data represents the period 1984-20... | Examples:
from wa.Collect import JRC
JRC.Occurrence(Dir='C:/Temp3/', latlim=[41, 45], lonlim=[-8, -5])
"""
from .Occurrence import main as Occurrence
__all__ = ['Occurrence']
__version__ = '0.1'
|
the-zebulan/CodeWars | katas/kyu_7/supernatural.py | Python | mit | 1,003 | 0 | drunkenDoodling = {
'ghost': "Salt and iron, and don't forget to burn the corpse",
'wendigo': | 'Burn it to death',
'phoenix': 'Use the colt',
'angel': 'Use the angelic blade',
'werewolf': 'Silver knife or bullet to the heart',
'shapeshifter': 'Silver knife or bull | et to the heart',
'rugaru': 'Burn it alive',
'reaper': "If it's nasty, you should gank who controls it",
'demon': "Use Ruby's knife, or some Jesus-juice",
'vampire': 'Behead it with a machete',
'dragon': 'You have to find the excalibur for that',
'leviathan': 'Use some Borax, then kill Dick',
... |
Oksisane/RSS-Bot | Trolly-master/trolly/trelloobject.py | Python | gpl-3.0 | 3,944 | 0.000761 | """
Created on 9 Nov 2012
@author: plish
"""
class TrelloObject(object):
"""
This class is a base object that should be used by all trello objects;
Board, List, Card, etc. It contains methods needed and used by all those
objects and masks the client calls as methods belonging to the object.
"""
... | self.get_boards_json(base_uri)
def getBoardJson(self, base_uri):
return self.get_board_json(base_uri)
def getListsJson(self, base_uri):
return self.get_lists_json(base_uri)
def getListJson(self, base_uri):
return self.get_list_json(base_uri)
def getCardsJson(self, base_uri):... | n self.get_checklist_json(base_uri)
def getMembersJson(self, base_uri):
return self.get_members_json(base_uri)
def createOrganisation(self, organisation_json, **kwargs):
return self.create_organisation(organisation_json, **kwargs)
def createBoard(self, board_json, **kwargs):
retur... |
phasis/phasis | phasis/base/srctblcf.py | Python | gpl-2.0 | 5,891 | 0.016466 | # -*- coding: iso-8859-1 -*-
#
# Copyright (C) 2001 - 2020 Massimo Gerardi all rights reserved.
#
# Author: Massimo Gerardi massimo.gerardi@gmail.com
#
# Copyright (c) 2020 Qsistemi.com. All rights reserved.
#
# Viale Giorgio Ribotta, 11 (Roma)
# 00144 Roma (RM) - Italy
# Phone: (+39) 06.87.163
#
#
# Si veda ... | in rows:
for rowlc in range(1):
row_lc = self.lc.GetItemCount()
t_cpart = str(row[0])
cod = str(row[1])
ragsoc1 = str(row[3]).title()
ragsoc2 = str(row[4]).title | ()
indiriz = str(row[6]).title()
tel_abi = str(row[12])
tel_uff = str(row[13])
fax = str(row[14])
self.lc.InsertStringItem(rowlc, cod)
self.lc.SetStringItem(rowlc, 1, ragsoc1)
... |
sysadminmatmoz/ingadhoc | multi_store/__openerp__.py | Python | agpl-3.0 | 2,617 | 0.003821 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar)
# All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Pu... | plied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#####################... |
'name': 'Multi Store',
'version': '8.0.1.0.0',
'category': 'Accounting',
'sequence': 14,
'summary': '',
'description': """
Multi Store
===========
The main purpose of this module is to restrict journals access for users on different stores.
This module add a new concept "stores" in some point... |
janglapuk/xiongmai-cam-api | example.py | Python | mit | 660 | 0 | from xmcam import *
from xmconst import *
from time import sleep
CAM_IP = '192.168.1.10'
CAM_PORT = 34567
| if __name__ == '__main__':
xm = XMCam(CAM_IP, CAM_PORT, 'admin', 'admin')
login = xm.cmd_login()
print(login)
print(xm.cmd_system_function())
print(xm.cmd_system_info())
print(xm.cmd_channel_title())
print(xm.cmd_OEM_info())
print(xm.cmd_storage_info())
print(xm.cmd_users())
pr... | ol(PTZ_LEFT))
sleep(1)
print(xm.cmd_ptz_control(PTZ_LEFT, True))
cfg = xm.cmd_config_export('export.cfg')
print('Config ==>', cfg)
snap = xm.cmd_snap('test.jpg')
print('SNAP ==>', snap)
|
ahmadiga/min_edx | common/djangoapps/status/models.py | Python | agpl-3.0 | 2,090 | 0.002871 | """
Store status messages in the database.
"""
from django.db import models
from django.contrib import admin
from django.core.cache import cache
from xmodule_django.models import CourseKeyField
from config_models.models import ConfigurationModel
from config_models.admin import ConfigurationModelAdmin
class GlobalS... | """
cache_key = "status_message.{course_id}".format(course_id=unicode(course_key))
if cache.get(cache_key):
return cache.get(cache_key)
msg = self.message
if course_key:
try:
course_message = self.coursemessage_set.get(course_key=course_key)
... | except CourseMessage.DoesNotExist:
# We don't have a course-specific message, so pass.
pass
cache.set(cache_key, msg)
return msg
def __unicode__(self):
return "{} - {} - {}".format(self.change_date, self.enabled, self.message)
class CourseMessage(mod... |
kevin-intel/scikit-learn | benchmarks/bench_20newsgroups.py | Python | bsd-3-clause | 3,292 | 0 | from time import time
import argparse
import numpy as np
from sklearn.dummy import DummyClassifier
from sklearn.datasets import fetch_20newsgroups_vectorized
from sklearn.metrics import accuracy_score
from sklearn.utils.validation import check_array
from sklearn.ensemble import RandomForestClassifier
from sklearn.en... | ame] = time() - t0
accuracy[name] = accuracy_score(y_test, y_pred)
print("done")
print()
print("Classification performance:")
print("===========================")
print()
print("%s %s %s %s" % ("Classifier ", "train-time", "test-time",
| "Accuracy"))
print("-" * 44)
for name in sorted(accuracy, key=accuracy.get):
print("%s %s %s %s" % (name.ljust(16),
("%.4fs" % train_time[name]).center(10),
("%.4fs" % test_time[name]).center(10),
("%.4f... |
clarkerubber/irwin | modules/queue/IrwinQueue.py | Python | agpl-3.0 | 1,421 | 0.004222 | """Queue item for deep analysis by irwin"""
from default_imports import *
from modules.queue.Origin import Origin
from modules.game.Game import PlayerID
from datetime import datetime
import pymongo
from pymongo.collection import Collection
IrwinQueue = NamedTuple('IrwinQueue', [
| ('id', PlayerID),
('origin', Origin)
])
class IrwinQueueBSONHandler:
@staticmethod
def reads(bson: Dict) -> IrwinQueue:
return IrwinQueue(
id=bson['_id'],
origin=bson['origin'])
@staticmethod
def writes(irwinQueue: IrwinQueue) -> Dict | :
return {
'_id': irwinQueue.id,
'origin': irwinQueue.origin,
'date': datetime.now()
}
class IrwinQueueDB(NamedTuple('IrwinQueueDB', [
('irwinQueueColl', Collection)
])):
def write(self, irwinQueue: IrwinQueue):
self.irwinQueueColl.update_one(... |
nlapalu/SDDetector | tests/test_GffGeneParser.py | Python | gpl-3.0 | 1,549 | 0.020013 | #!/usr/bin/env python
import unittest
from SDDetector.Entities.Gene import Gene
from SDDetector.Entities.Transcript import Transcript
from SDDetector.Entities.CDS import CDS
from SDDetector.Parser.Gff.GffGeneParser import GffGeneParser
class TestGffGeneParser(unittest.TestCase):
def setUp(self):
pass
... | ds_1','Chr1',23988,24083, -1, 'G00001.1'),CDS('G00001.1_cds_1','Chr1',24274,24427,-1,'G00001.1'),CDS('G00001.1_cds_1','Chr1',24489,24919,-1,'G00001.1')])])]
# self.assertEqual(iGffG | eneParser.getAllGenes()[0],lGenes[0])
if __name__ == "__main__":
suite = unittest.TestLoader().loadTestsFromTestCase(TestGffGeneParser)
unittest.TextTestRunner(verbosity=2).run(suite)
|
cupy/cupy | cupy/_padding/pad.py | Python | mit | 29,422 | 0 | import numbers
import numpy
import cupy
###############################################################################
# Private utility functions.
def _round_if_needed(arr, dtype):
"""Rounds arr inplace if the destination dtype is an integer.
"""
if cupy.issubdtype(dtype, cupy.integer):
arr.... | ndefined values.
Args:
array(cupy.ndarray): Array to grow.
pad_width(sequence of tuple[int, int]): Pad width on both sides for each
dimension in `arr`.
fill_value(scalar, optional): I | f provided the padded area is
filled with this value, otherwise the pad area left undefined.
(Default value = None)
"""
# Allocate grown array
new_shape = tuple(
left + size + right
for size, (left, right) in zip(array.shape, pad_width)
)
order = 'F' if array.flag... |
dimagi/commcare-hq | corehq/ex-submodules/pillowtop/management/commands/update_es_settings.py | Python | bsd-3-clause | 2,244 | 0.003119 | from django.core.management.base import BaseCommand, CommandError
from corehq.elastic import get_es_new
from corehq.pillows.utils import get_all_expected_es_indices
class Command(BaseCommand):
help = "Update dynamic settings for existing elasticsearch indices."
def add_arguments(self, parser):
parse... | mapping_res = es.indices.put_settings(index=index_info.index, body=settings)
if mapping_res.get('acknowledged', False):
print("{} [{}]:\n Index settings successfully updated".format(
index_info.alias, index_info.index))
... | nt(mapping_res)
def _confirm(message):
if input(
'{} [y/n]'.format(message)
).lower() == 'y':
return True
else:
raise CommandError('abort')
|
deepmind/dm_control | dm_control/entities/manipulators/kinova/__init__.py | Python | apache-2.0 | 848 | 0 | # Copyright 2019 The dm_control 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 i... | ANTIES OR CONDITIONS OF ANY KIND, either express or | implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Composer models of Kinova robots."""
from dm_control.entities.manipulators.kinova.jaco_arm import JacoArm
from dm_control.e... |
dlazz/ansible | lib/ansible/modules/cloud/google/gcp_compute_target_vpn_gateway.py | Python | gpl-3.0 | 11,232 | 0.003205 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License | v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# | ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
# ----------------------------------------------------------------------------
#
# This file is automatically generated by Magic Modules and manual
# changes ... |
yencarnacion/jaikuengine | .google_appengine/google/appengine/api/modules/modules_stub.py | Python | apache-2.0 | 5,933 | 0.007079 | #!/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... | s and
# limitations under the License.
#
"""Stub implementation of the modules service."""
from google.appengine.api import apiproxy_stub
from google.appengine.api import request_info
from google.appengine.api.modules import modules_service_pb
from google.appengine.runtime import apiproxy_errors
class Mod | ulesServiceStub(apiproxy_stub.APIProxyStub):
_ACCEPTS_REQUEST_ID = True
THREADSAFE = True
def __init__(self, request_data):
super(ModulesServiceStub, self).__init__('modules',
request_data=request_data)
def _GetModuleFromRequest(self, request, request_id):
... |
msghens/pyADAP | adlib.py | Python | mit | 8,216 | 0.041504 | # -*- coding: utf-8 -*-
#
# adlib.py
#
# A lot of help from:
# http://marcitland.blogspot.com/2011/02/python-active-directory-linux.html
# import sys is my friend!
import sys
import logging
import ldap
from person import Person
#import netrc
import base64,zlib
import ldap.modlist as modlist
from secure import AD... | errec = imsperson
#Base dn. Outside config????
self.base_dn = 'dc=sbcc,dc=local'
self.dn = None
self.inADFlag = None
def inAD(self,cn=None):
if cn is None:
cn=self.perrec.userid
#instatiate class. Why? Who knows...
ad = ADconnection()
with ad as ldapconn:
try:
searchfilter = ... | ults[0][0]
if dn is None:
return False
except ldap.LDAPError, error_message:
#print "error finding username: %S" % error_message
self.inADFlag = False
return False
except:
self.inADFlag = False
return False
self.inADFlag = True
return True
def chgPwd(self,cn=None):
if cn i... |
django-stars/dash2011 | presence/apps/vote/views.py | Python | bsd-3-clause | 684 | 0 | from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.contrib import messages
from models import UserVote
from forms import UserVoteForm
def vote(request):
if request.method ... | (request.user, vote.vote)
messages.info(request, "Your mood is %s" % vote.get_vote_display())
else:
form = UserVoteForm()
return HttpResponseRedi | rect(reverse('dashboard'))
|
PyFilesystem/pyfilesystem2 | fs/opener/memoryfs.py | Python | mit | 808 | 0 | # coding: utf-8
"""`MemoryFS` opener definit | ion.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import typing
from .base import Opener
from .registry import registry
if typing.TYPE_CHECKING:
from typing import Text
from .parse import ParseResult
from ..memoryfs import Memor... | en_fs(
self,
fs_url, # type: Text
parse_result, # type: ParseResult
writeable, # type: bool
create, # type: bool
cwd, # type: Text
):
# type: (...) -> MemoryFS
from ..memoryfs import MemoryFS
mem_fs = MemoryFS()
return mem_fs
|
jayinton/FlaskDemo | simple/index.py | Python | mit | 269 | 0 | #!/usr/bin/env python
# coding=utf-8
__ | author__ = 'Jayin Ton'
from flask import Flask
app = Flask(__name__)
host = '127.0.0.1'
port = 8000
@app.route('/')
def index():
return 'welcome'
if __name__ == '__main__':
a | pp.run(host=host, port=port, debug=True)
|
BaroboRobotics/libbarobo | PyMobot/setup_win32.py | Python | gpl-3.0 | 855 | 0.016374 | #!/usr/bin/env python
from distutils.core import setup,Extension
from distutils.command.build_py import build_py
dist = s | etup(name='PyMobot',
version='0.1',
description='Mobot Control Python Library',
author='David Ko',
author_email='david@barobo.com',
url='http://www.barobo.com',
packages=['barobo'],
ext_modules= | [Extension('barobo._mobot',
['barobo/mobot.i'],
swig_opts=['-c++', '-I../'],
include_dirs=['../', '../BaroboConfigFile', '../BaroboConfigFile/mxml-2.7'],
define_macros=[('NONRELEASE','1')],
extra_compile_args=['-fpermissive'],
library_dirs=['../', '../BaroboConfigFile', '../BaroboCo... |
nozuono/calibre-webserver | src/tinycss/media3.py | Python | gpl-3.0 | 4,645 | 0.003229 | #!/usr/bin/env python
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>'
from tinycss.css21 import CSS21Parser
from tinycss.parsing import remove_whit... | , media_type='all', expressions=(), negated=False):
self.media_type = media_type
self.expressions = expressions
self.negated = negated
def __repr__(self):
return '<MediaQuery type=%s negated=%s expressions=%s>' % (
self.media_type, self.negated, self.expressions)
de... | ssions == getattr(other, 'expressions', None)
class MalformedExpression(Exception):
def __init__(self, tok, msg):
Exception.__init__(self, msg)
self.tok = tok
class CSSMedia3Parser(CSS21Parser):
''' Parse media queries as defined by the CSS 3 media module '''
def parse_media(self, token... |
fmaschler/networkit | networkit/scd.py | Python | mit | 62 | 0.016129 | # extension im | ports
from _NetworKit imp | ort PageRankNibble, GCE |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.4/Lib/test/test_copy.py | Python | mit | 17,174 | 0.002678 | """Unit tests for the copy module."""
import sys
import copy
import copy_reg
import unittest
from test import test_support
class TestCopy(unittest.TestCase):
# Attempt full line coverage of copy.py from top to bottom
def test_exceptions(self):
self.assert_(copy.Error is copy.error)
self.ass... | __getinitargs__(self):
return (self.foo,)
def __cmp__(self, other):
return cmp(self.foo, | other.foo)
x = C(42)
self.assertEqual(copy.copy(x), x)
def test_copy_inst_getstate(self):
class C:
def __init__(self, foo):
self.foo = foo
def __getstate__(self):
return {"foo": self.foo}
def __cmp__(self, other):
... |
peppelinux/pyDBsync | src/main.py | Python | bsd-3-clause | 3,261 | 0.029745 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import argparse
#import imp
from validator import *
from settings import *
from utils import *
parser = argparse.ArgumentParser(description='Sync two Databases', epilog="Es: python main.py -run test --db-master=mysql://root:remotepasswd@192.168.0.21... | , args.master)
| slave = SessionManager('slave', args.slave)
for table in args.tables.split(','):
if args.run == 'test': args.run = None
g = pyTableSyncManager(master, slave, table, args.run)
g.InspectTable()
if g.ProposedUpdates:
g.CommitUpdates()
if g.ProposedInsertions:
g.CommitInsertions()
if g.ProposedD... |
jm66/vsphere_inventory_report | vsphere_inventory_report.py | Python | gpl-2.0 | 17,553 | 0.014357 | #!/usr/bin/python
import logging, sys, re, getpass, argparse, pprint, csv, time
from pysphere import MORTypes, VIServer, VITask, VIProperty, VIMor, VIException
from pysphere.vi_virtual_machine import VIVirtualMachine
from pysphere.resources import VimService_services as VI
def sizeof_fmt(num):
for x in ['bytes','K... | .writerow([val['Folder'], val['vm'], val['numCPU'], val['MBmemory'], val['storageUsed'], val['storageCommitted'],val['ESX | ihost'], val['datastores'],
val['vmConfig'], val['networks'], val['netids'], val['vmOS'], val['vmTools'], val['vmPower'], val['vmDNS'], val['Note'],
val['cpuReservationMhz'], val['cpuLimitMhz'], val['memReservationMB'], val['memLimitMB'], val['HardDisks'],
va... |
anjesh/pdf-processor | run.py | Python | mit | 2,284 | 0.007005 | from PdfProcessor import *
import argparse
from datetime import datetime
import ConfigParser
import ProcessLogger
import traceback
from urllib2 import HTTPError, URLError
parser = argparse.ArgumentParser(description='Processes the pdf and extracts the text')
parser.add_argument('-l','--language', help='Language of inp... | wed_languages = ["english", "french", "spanish", "portuguese", "arabic"]
pdfProcessor = ""
try:
logger = ProcessLogger.getLogger('run')
logger.info("Processing started at %s ", str(datetime.now()))
logger.info("input: %s", results.infile)
logger.info("outdir: %s", results.outdir)
if results.langua... | allowed_languages:
raise Exception("language should be one of english, french, spanish, portuguese or arabic")
if results.language.lower() == "portuguese":
results.language = "portuguesestandard"
configParser = ConfigParser.RawConfigParser()
configParser.read(os.path.join(os.path.dirname(os... |
5610110083/Safety-in-residential-project | cgi-bin/any/setCookies.py | Python | apache-2.0 | 447 | 0.029083 | #!/usr/bin/python
import requests
import time, Cookie
# Instantiate a SimpleCookie | object
cookie = Cookie.SimpleCookie()
# The SimpleCookie instance is a mapping
cookie['lastvisit'] = str(time.time())
s = requests.session()
s. | cookies.clear()
# Output the HTTP message containing the cookie
print cookie
print 'Content-Type: text/html\n'
print '<html><body>'
print 'Server time is', time.asctime(time.localtime())
print '</body></html>' |
DevicePilot/synth | synth/devices/commswave.py | Python | mit | 3,252 | 0.006458 | """
commswave
=========
Takes device communications up and down according to a timefunction.
Comms will be working whenever the timefunction returns non-zero.
Configurable parameters::
{
"timefunction" : A timefunction definition
"threshold" : (optional) Comms will only work when the timefunction ... | ansmit(the_id, ts, properties, force_comms)
def external_event(self, event_name, arg):
super(Commswave, self).external_event(event_name, arg)
def close(self):
super(Commswave,self).close()
logging.info("Comms report for " + str(self.properties["$id"]) + " " +
str(self.messa... | tr(self.messages_attempted) + " total")
# Private methods
## (we don't actually need to tick, as we can instantaneously look up timefunction state whenever we need to)
## def tick_commswave(self, _):
## self.ok_commswave = self.comms_timefunction.state()
## self.engine.register_event_at(self.... |
aluminiumgeek/goodbye-mihome | apps/sound_when_door_is_open.py | Python | bsd-2-clause | 608 | 0 | import json
from plugins import gateway_speaker
from plugins. | magnet import MAGNET_STORE_KEY
DOOR_SENSOR_SID = '158d0001837ec2'
def run(store, conn, cursor):
"""Play sound on the Gateway when somebody opens the door"""
p = store.pubsub(ignore_subscribe_messages=True)
p.subscribe(MAGNET_STORE_KEY)
for message in p.listen():
if message.get('type') != 'me... | d') == DOOR_SENSOR_SID and data.get('status') == 'open':
gateway_speaker.play(3) # Standard alarm sound
|
CloudVLab/professional-services | tools/ml-auto-eda/ml_eda/reporting/recommendation.py | Python | apache-2.0 | 4,289 | 0.007694 | # Copyright 2019 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 ... | b2
from ml_eda.reporting import template
# Thresholds
MISSING_THRESHOLD = 0.1
CARDINALITY_THRESHOLD = 100
CORRELATION_COEFFICIENT_THRESHOLD = 0.3
P_VALUE_THRESHOLD = 0.05
def check_missing(attribute_name: str,
analysis: run_metadata_pb2.Analysis
) -> Union[None, str]:
"""Check w... | eed threshold
Args:
attribute_name: (string),
analysis: (run_metadata_pb2.Analysis), analysis that contain the result
of number of missing values
Returns:
Union[None, string]
"""
metrics = analysis.smetrics
total = 0
missing = 0
for item in metrics:
if item.name == run_metadat... |
odoousers2014/odoo-development | modules/development_tools/wizard/development_tools_config_settings.py | Python | agpl-3.0 | 12,322 | 0.000081 | # -*- coding: utf-8 -*-
###############################################################################
# License, author and contributors information in: #
# __openerp__.py file at the root folder of this module. #
########################################################... | '
filter_set = self.env.ref('{}.{}'.format(self._module, name))
filter_set.domain = unicode([('id', 'in', ids or [-1])])
except Exception as ex:
msg = self._not_set('developing_module_ids', ex)
_lo | gger.error(msg)
def get_search_default_app(self):
value = None
try:
action_set = self.env.ref('base.open_module_tree')
context = self._safe_eval(action_set.context, dict)
if 'search_default_app' in context:
value = context['search_default_app'] i... |
feelobot/compose | compose/cli/main.py | Python | apache-2.0 | 19,689 | 0.001727 | from __future__ import print_function
from __future__ import unicode_literals
from inspect import getdoc
from operator import attrgetter
import logging
import re
import signal
import sys
from docker.errors import APIError
import dockerpty
from .. import __version__
from .. import legacy
from ..const import DEFAULT_TI... | iew output from containers
port Print the public port for a port binding
ps List containers
pull Pulls service images
restart Restart services
rm Remove stopped containers
run Run a one-off command
... | Set number of containers for a service
start Start services
stop Stop services
up Create and start containers
migrate-to-labels Recreate containers to add labels
version Show the Docker-Compose version information
"""
... |
OCA/l10n-italy | l10n_it_vat_statement_split_payment/models/account_config.py | Python | agpl-3.0 | 520 | 0 | # Copyright 2018 Silvio Gregorini (silviogregorini@openforce.it)
# Copyright (c) 2018 Openforce Srls Unipersonale (www.openforce.it)
# Copyright (c) 2019 Matteo Bilotta
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
... | ion = fields.Char(
related="company_id.sp_description",
string="Description for period end stateme | nts",
readonly=False,
)
|
garyd203/flying-circus | src/flyingcircus/service/applicationautoscaling.py | Python | lgpl-3.0 | 424 | 0.002358 | """General-use classes to interact with the ApplicationAutoScaling service through CloudFor | mation.
See Also:
`AWS developer guide for ApplicationAutoScaling
<https://docs.aws.amazon.com/autoscaling/application/APIReference/Welcome.html>`_
"""
# noinspection PyUnresolvedReferences
from | .._raw import applicationautoscaling as _raw
# noinspection PyUnresolvedReferences
from .._raw.applicationautoscaling import *
|
fokusov/moneyguru | qt/controller/transaction/filter_bar.py | Python | gpl-3.0 | 843 | 0.005931 | # Created By: Virgil Dupras
# Created On: 2009-11-27
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/g... | (tr("Income"), FilterType.Income),
(tr("Expenses"), FilterType.Expense),
(tr("Transfers"), | FilterType.Transfer),
(tr("Unassigned"), FilterType.Unassigned),
(tr("Reconciled"), FilterType.Reconciled),
(tr("Not Reconciled"), FilterType.NotReconciled),
]
|
kawashiro/dewyatochka2 | src/dewyatochka/core/plugin/subsystem/message/py_entry.py | Python | gpl-3.0 | 2,198 | 0.002275 | # -*- coding: UTF-8
""" Entry decorators for python plugins
Functions
=========
chat_message -- Decorator for chat message plugin
chat_command -- Decorator for chat command plugin
chat_accost -- Decorator for chat accost plugin
"""
from dewyatochka.core.plugin.loader.internal import entry_point
from dew... | at_message(fn=None, *, services=None, regular=False, system=False, own=False) -> callable:
""" Decorator to mark function as message handler entry point
:param callable fn: Function if decorator is invoked direct | ly
:param list services: Dependent services list
:param bool regular: Register this handler for regular messages
:param bool system: Register this handler for system messages
:param bool own: Register this handler for own messages
:return callable:
"""
return entry_point(PLUGIN_TYPE_MESSAGE,... |
TheWardoctor/Wardoctors-repo | plugin.video.uncoded/uncoded.py | Python | apache-2.0 | 12,280 | 0.003746 | # -*- coding: utf-8 -*-
'''
Uncoded Add-on
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 progr... | m resources.lib.modules import control |
control.openSettings(query)
elif action == 'artwork':
from resources.lib.modules import control
control.artwork()
elif action == 'addView':
from resources.lib.modules import views
views.addView(content)
elif action == 'moviePlaycount':
from resources.lib.modules import playcount
playcoun... |
jonashaag/gpyconf | gpyconf/backends/_xml/__init__.py | Python | lgpl-2.1 | 1,161 | 0.002584 | # %FILEHEADER%
from ..filebased import FileBasedBackend
from .. import NONE, MissingOption
from xmlserialize import serialize_to_file, unserialize_file
from lxml.etree import XMLSyntaxErro | r
class XMLBackend(dict, FileBasedBackend):
ROOT_ELEMENT = 'configuration'
initial_file_content = '<{0}></{0}>'.format(ROOT_ELEMENT)
def __init__(self, backref, extension='xml', filename=None):
dict.__init__(self)
FileBasedBackend.__init__(self, backr | ef, extension, filename)
def read(self):
try:
return unserialize_file(self.file)
except XMLSyntaxError, err:
self.log('Could not parse XML configuration file: %s' % err,
level='error')
def save(self):
serialize_to_file(self, self.file, root_... |
TheWardoctor/Wardoctors-repo | plugin.video.metalliq/resources/lib/meta/play/live.py | Python | apache-2.0 | 3,977 | 0.005029 | import re
import urllib
from xbmcswift2 import xbmc
from meta import plugin, LANG
from meta.gui import dialogs
from meta.utils.text import to_unicode
from meta.library.live import get_player_plugin_from_library
from meta.navigation.base import get_icon_path, get_background_path
from meta.play.players import get_needed_... | action_cancel()
return
# Get parameters
params = {}
for lang in get_needed_langs(channelers):
params[lang] = get_channel_parameters(channel, program, language)
params[lang] = to_unicode(params[lang])
# Go for it
link = on_play_video(mode, channelers, params)
if link | :
action_play({
'label': channel,
'path': link,
'is_playable': True,
'info_type': 'video',
})
def get_channel_parameters(channel, program, language):
channel_regex = re.compile("(.+?)\s*(\d+|one|two|three|four|five|six|seven|eight|nine|ten)\s*.*?(\d*)... |
suutari/shoop | shuup/notify/models/notification.py | Python | agpl-3.0 | 4,222 | 0.002605 | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from django.conf import se... | h.models.AbstractUser
"""
if not user or user.is_anonymous():
return self.none()
q = (Q(recipient_type=RecipientType.S | PECIFIC_USER) & Q(recipient=user))
if getattr(user, 'is_superuser', False):
q |= Q(recipient_type=RecipientType.ADMINS)
return self.filter(q)
def unread_for_user(self, user):
return self.for_user(user).exclude(marked_read=True)
class Notification(models.Model):
"""
A... |
EdDev/vdsm | lib/vdsm/storage/check.py | Python | gpl-2.0 | 12,176 | 0 | #
# Copyright 2016-2017 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed ... | anty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110... | able storage
health monitoring:
CheckService entry point for starting and stopping path checkers.
DirectioChecker checker using dd process for file or block based
volumes.
CheckResult result object provided to user callback on each check.
"""
from __future__ import absolute_import
import... |
eklochkov/gitinspector | gitinspector/extensions.py | Python | gpl-3.0 | 1,635 | 0.015912 | # coding: utf-8
#
# Copyright © 2012-2015 Ejwa Software. All rights reserved.
#
# This file is part of gitinspector.
#
# gitinspector 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 Lic... | the GNU General Public License
# along with gitinspector. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
DEFAULT_EXTENSIONS = {"java":"java", "c":"c", "cc":"c", "cpp":"cpp", "h":"cpp", "hh":"cpp", "hpp":"cpp", "py":"python",
"glsl":"opengl", "rb":"ruby", "js"... | l","txt":"text", "drt":"drools", "drl":"drools", "bpmn":"processes", "kt":"kotlin"}
__extensions__ = DEFAULT_EXTENSIONS.keys()
__extensions_dict__ = DEFAULT_EXTENSIONS
__located_extensions__ = set()
def get():
return __extensions__
def get_dict():
return __extensions_dict__
def define(string):
global... |
os2webscanner/os2webscanner | scrapy-webscanner/scanners/processors/xml.py | Python | mpl-2.0 | 2,214 | 0.002258 | # The contents of this file are subject to the Mozilla Public 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://ww | w.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# OS2Webscanner was developed by Magenta in collaboration with O... | s2web.dk/).
#
# The code is currently governed by OS2 the Danish community of open
# source municipalities ( http://www.os2web.dk/ )
"""HTML Processors."""
from .processor import Processor
from .text import TextProcessor
import logging
import os
import xmltodict
import json
from xml.parsers.expat import ExpatError
... |
GoogleCloudPlatform/jupyter-extensions | jupyterlab_gitsync/setup.py | Python | apache-2.0 | 1,836 | 0.003268 | # Copyright 2020 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, ... | lab_gitsync", "version.py")) as f:
for l in f:
if l.startswith("VERSION"):
version = l.rstrip().split(" = ")[1].replace("'", "")
if not version:
raise RuntimeError("Unable to determine version")
npm_package = "jupyterlab_gitsync-{}.tgz".format(version)
if not os.path.exists(os.path.join(os.getcwd(), npm... | `npm pack`?")
data_files = [
("share/jupyter/lab/extensions", (npm_package,)),
("etc/jupyter/jupyter_notebook_config.d",
("jupyter-config/jupyter_notebook_config.d/jupyterlab_gitsync.json",)),
]
setup(
name="jupyterlab_gitsync",
version=version,
description="JupyterLab Git Sync",
long_de... |
loult-elte-fwere/termiloult | tests/test_multiple_play.py | Python | mit | 559 | 0.001789 | import logging
from time import sleep
from tools.audiosink import AudioSink
demo = logging.getLogger('Demo')
logging.basicConfig(level=logging.DEBUG)
p = AudioSink()
with open("sample.wav", 'rb') as f:
a = f.read()
demo.info("add the first track")
p.add(a, "a")
sleep(2)
with open("sample.wav", 'rb') as f:
... | k")
p.add(b,"b")
sleep(5)
demo.info("remove the first track")
p.remove("a")
sleep(5)
demo.info("lower the volume to 40%")
p.volume = 40
sleep(15)
demo.info("close the AudioSink")
p. | close()
|
nfrechette/acl | tools/graph_generation/gen_bit_rate_stats.py | Python | mit | 2,309 | 0.020788 | import numpy
import os
import sys
# This script depends on a SJSON parsing package:
# https://pypi.python.org/pypi/SJSON/1.1.0
# https://shelter13.net/projects/SJSON/
# https://bitbucket.org/Anteru/sjson/src
import sjson
if __name__ == "__main__":
if sys.version_info < (3, 4):
print('Python 3.4 or higher needed to... | t_data_type_def, skiprows=1, usecols=columns_to_extract)
filter = entry.get('filter', None)
if filter != None:
best_variable_data_mask = csv_data['algorithm_names'] == bytes(entry['filter'], encoding | = 'utf-8')
csv_data = csv_data[best_variable_data_mask]
# Strip algorithm name
output_csv_data.append(csv_data[0].tolist()[1:])
output_csv_headers.append(entry['header'])
output_csv_data = numpy.column_stack(output_csv_data)
with open(output_csv_file_path, 'wb') as f:
header = bytes('{}\n'.format(','.j... |
blstream/myHoard_Python | myhoard/settings/dev.py | Python | apache-2.0 | 1,018 | 0.001965 | from common import *
DEBUG = True
MONGODB_SETTINGS = {
'HOST': '127.0.0.1',
'PORT': 27017,
'DB': 'myhoard_dev',
'USERNAME': 'myhoard',
'PASSWORD': 'myh0@rd',
}
# Logging
LOGGING = {
'version': 1,
'disable_existin | g_loggers': False,
'root': {
'level': 'NOTSET',
'handlers': ['console', 'file'],
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'level': 'INFO',
'formatter': 'standard',
'stream': 'ext://sys.stdout',
},
... | {
'class': 'logging.handlers.RotatingFileHandler',
'level': 'INFO',
'formatter': 'standard',
'filename': '/home/pat/logs/dev/myhoard.log',
'mode': 'a',
'maxBytes': 2 * 1024 * 1024, # 2MiB
'backupCount': 64,
},
},
'forma... |
Mlieou/leetcode_python | leetcode/python/ex_689.py | Python | mit | 1,077 | 0.007428 | class Solution(object):
def maxSumOfThreeSubarrays(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
window = []
c_sum = 0
for i, v in enumerate(nums):
c_sum += v
if i >= k: c_sum -= nums[i-k]
... | en(window) - 1
for i in range(len(window)-1, -1, -1):
if window[i] > window[best]:
best = i
right[i] = best
ans = None
for b in range(k, len(window) | - k):
a, c = left[b-k], right[b+k]
if ans is None or (window[a] + window[b] + window[c] >
window[ans[0]] + window[ans[1]] + window[ans[2]]):
ans = a, b, c
return ans |
rbuffat/pyidf | tests/test_exteriorfuelequipment.py | Python | apache-2.0 | 1,733 | 0.003462 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.exterior_equipment import ExteriorFuelEquipment
log = logging.getLogger(__name__)
class TestExteriorFuelEquipment(unittest.TestCase):
def setUp(self):
self.fd, self... | me"
obj.name = var_name
# alpha
var_fuel_use_type = "Electricity"
obj.fuel_use_type = var_fuel_use_type
# object-list
var_schedule_name = "object-list|Schedule Name"
obj.schedule_name = var_schedule_name
# real
var_design_level = 0.0
obj.de... | egory = "End-Use Subcategory"
obj.enduse_subcategory = var_enduse_subcategory
idf = IDF()
idf.add(obj)
idf.save(self.path, check=False)
with open(self.path, mode='r') as f:
for line in f:
log.debug(line.strip())
idf2 = IDF(self.path)
... |
abhijo89/sphinxit | sphinxit/core/constants.py | Python | bsd-3-clause | 1,436 | 0 | """
sphinxit.core.constants
~~~~~~~~~~~~~~~~~~~~~~~
Defines some Sphinx-specific constants.
:copyright: (c) 2013 by Roman Semirook.
:license: BSD, see LICENSE for more details.
"""
from collections import namedtuple
RESERVED_KEYWORDS = (
'AND',
'AS',
'ASC',
'AVG',
'BEGIN',
... | ',
'SELECT',
'SET',
'SHOW',
'START',
'STATUS',
'SUM',
'TABLES',
'TRANSACTION',
'TRUE',
'UPDATE',
'VALUES',
'VARIABLES',
'WARNINGS',
'WEIGHT',
'WHERE',
'WITHIN'
)
ESCAPED_CHARS = namedtuple('EscapedChars', ['single_escape', 'double_escape'])(
| single_escape=("'", '+', '[', ']', '=', '*'),
double_escape=('@', '!', '^', '(', ')', '~', '-', '|', '/', '<<', '$', '"')
)
NODES_ORDER = namedtuple('NodesOrder', ['select', 'update'])(
select=(
'SelectFrom',
'Where',
'GroupBy',
'OrderBy',
'WithinGroupOrderBy',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.