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 |
|---|---|---|---|---|---|---|---|---|
eHealthAfrica/ureport | ureport/translation.py | Python | agpl-3.0 | 646 | 0.00774 | from modeltranslation. | translator import translator, TranslationOptions
from nsms.text.models import *
from django.utils.translation import ugettext as _
from django.utils.translation import get_language as _get_language
from modeltranslation import utils
class TextTranslationOptions(TranslationOptions):
fields = ('text',)
translator.... | ng for django translations to kick in
_("Something to trigger localizations")
# monkey patch a version of get_language that isn't broken
def get_language():
lang = _get_language()
return lang
utils.get_language = get_language
|
nigelb/SerialGrabber | examples/MqttXBeeStream/MqttXBee.py | Python | gpl-2.0 | 668 | 0.007485 | import logging
from serial_grabber.reader import MessageVerifier
class XBeeMessageVerifier(MessageVerifier):
logger = logging.getLogger("MessageVerifier")
def verify_message(self, transaction):
t | ry:
data = transaction.split("\n")
if int(data[-2]) == len("\n".join(data[1:-2])):
| return True, "OK"
else:
self.logger.error("Reported length: %s, Actual length: %s"%(int(data[-2]), len("\n".join(data[1:-2]))))
raise ValueError()
except ValueError, e:
self.logger.error("Could not convert %s to an integer."%data[-2])
r... |
Nick-Hall/gramps | gramps/plugins/lib/libtreebase.py | Python | gpl-2.0 | 34,876 | 0.004014 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2008-2010 Craig J. Anderson
# Copyright (C) 2014 Paul Franklin
#
# 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... | Keywords
from gramps.gen.plug.docgen import (IndexMark, INDEX_TYPE_TOC)
PT2CM = utils.pt2cm
#------------------------------------------------------------------------
#
# Class Calc_Lines
#
#------------------------------------------------------------------------
class CalcLines:
""" wrapper for libsubstk | eyword and added functionality for
replacements.
Receive: Individual and family handle, and display format [string]
return: [Text] ready for a box.
"""
def __init__(self, dbase, repl, locale, name_displayer):
self.database = dbase
self.display_repl = repl
#self.default_stri... |
sinotradition/meridian | meridian/acupoints/shuidao34.py | Python | apache-2.0 | 236 | 0.034783 | #!/usr/bin/python
#coding=utf-8
'''
@ | author: sheng
@license:
'''
SPELL=u'shuǐdào'
CN=u'水道'
NAME=u'shuidao34'
CHANNEL='stomach'
CHANNEL_FULLNAME='StomachChannelofFoot-Yangming'
| SEQ='ST28'
if __name__ == '__main__':
pass
|
PetrPPetrov/beautiful-capi | source/ExtensionSemantic.py | Python | gpl-3.0 | 2,815 | 0.001066 | #!/usr/bin/env python
#
# Beautiful Capi generates beautiful C API wrappers for your C++ classes
# Copyright (C) 2015 Petr Petrovich Petrov
#
# This file is part of Beautiful Capi.
#
# Beautiful Capi is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publis... | for lifecycle_extension in cur_class.lifecycle_extensions:
new_extension_class = deepcopy(cur_class)
new_extension_class.name = lifecycle_extension.name
new_extension_class.lifecycle = lifecycle_extension.lifecycle
new_extension_class.lifecycle_filled = True
... | e
new_extension_class.wrap_name_filled = lifecycle_extension.wrap_name_filled
new_extension_class.cast_tos = deepcopy(lifecycle_extension.cast_tos)
new_extension_class.lifecycle_extensions = []
new_extension_class.lifecycle_extension = lifecycle_extension
new_... |
giantas/elibrary | todo/urls.py | Python | mit | 885 | 0.018079 | from django.conf.urls import include, url
from . import views
app_name = 'todo'
urlpatterns = [
url(r'^lists/$', views.todolists, name='todo_lists'),
url(r'^lists/(?P<list_id>[\w\d]+)/update/$', views.UpdateTodoList.as_view(), name='update_list'),
url(r'^lists/card/(?P<card_id>[\w\d]+)/$', views.cards, name='cards'... | ew_l | ist'),
url(r'^lists/card/new/(?P<list_id>[\w\d]+)/$', views.CreateCard.as_view(), name='new_card'),
url(r'^lists/card/(?P<card_id>[\w\d]+)/update/$', views.UpdateCard.as_view(), name='update_card'),
url(r'^lists/card/(?P<card_id>[\w\d]+)/move/$', views.move_card, name='move_card'),
url(r'^lists/card/(?P<card_id>[\w... |
NIRALUser/FiberViewerLight | FiberLengthCleaning.py | Python | apache-2.0 | 11,548 | 0.015674 | from __main__ import vtk, qt, ctk, slicer
#
# LengthStat
#
class FiberLengthCleaning:
def __init__(self, parent):
parent.title = "Fiber Length Cleaning"
parent.categories = ["Diffusion"]
parent.contributors = ["Jean-Baptiste Berger and Martin Styner"]
self.parent = paren... | t.QLabel("Min: ",self.thresholdFrame)
self.thresholdFrame.layout().addWidget(self.thresholdMinLabel)
self.thresholdMin = qt.QSpinBox(self.thresholdFrame)
self.thresholdMin.setSingleStep(1)
self.thresholdMin.setRange(0,1000)
self.thresholdMin.setValue(0)
self.thr... | x: ",self.thresholdFrame)
self.thresholdFrame.layout().addWidget(self.thresholdMaxLabel)
self.thresholdMax = qt.QSpinBox(self.thresholdFrame)
self.thresholdMax.setSingleStep(1)
self.thresholdMax.setRange(0,1000)
self.thresholdMax.setValue(1)
self.thresholdMax.en... |
wursm1/eurobot-hauptsteuerung | eurobot/tests/__init__.py | Python | gpl-3.0 | 235 | 0.008511 | """
This package cont | ains different `unittests <https://docs.python.org/3/library/unittest.html>`_ for the project.
Those tests help to validate difficult pieces of the software.
"""
__author | __ = 'Wuersch Marcel'
__license__ = "GPLv3" |
mjm159/sunpy | sunpy/util/sysinfo.py | Python | bsd-2-clause | 3,403 | 0.006465 | from __future__ import absolute_import
import platform
import datetime
import sunpy
__all__ = ['system_info']
def system_info():
"""Prints system information.
Prints information about the runtime environment that SunPy lives in.
Information about the OS, architecture, Python, and all major dependen... | roc))
else:
print ("Unknown OS (%s)" % proc)
# Python version
arch = platform.architecture()[0]
print("Python: %s (%s)\n" % (platform.python_version(), arch))
# Dependencies
try:
from numpy import __version__ as numpy_version
except ImportError:
numpy_ve... | from matplotlib import __version__ as matplotlib_version
except ImportError:
matplotlib_version = "NOT INSTALLED"
try:
from pyfits import __version__ as pyfits_version
except ImportError:
pyfits_version = "NOT INSTALLED"
try:
from pandas import __version__ ... |
hitchtest/hitchhttp | hitchhttp/main_request_handler.py | Python | agpl-3.0 | 7,882 | 0.011799 | from hitchhttp import http_request
from ruamel.yaml import dump
from ruamel.yaml.dumper import RoundTripDumper
from ruamel.yaml.comments import CommentedMap
from hitchhttp.models import Database
from os import path
import tornado.web
import tornado
import requests
import random
import json
import time
import sys
clas... | #)
else:
self.set_status(404)
self.set_header('Content-type', 'text/html')
self.write(
self.default_response.format(self.request.path).encode('utf8')
)
#self.log_json(
#None,
... | lf.response_content = {}
def on_finish(self):
if self.settings['record']:
yaml_snip = {}
yaml_snip['request'] = {}
yaml_snip['request']['path'] = self.request.uri
yaml_snip['request']['method'] = self.request.method
yaml_snip['request']['heade... |
naterh/chipsec | source/tool/chipsec/modules/common/secureboot/keys.py | Python | gpl-2.0 | 5,186 | 0.021597 | #CHIPSEC: Platform Security Assessment Framework
#Copyright (c) 2010-2015, Intel Corporation
#
#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; Version 2.
#
#This program is distributed in t... | self._uefi.set_EFI_variable( name, guid, orig_var )
else:
self.logger.log_good( "Could not modify EFI variable %s {%s}" % (name, guid) )
return ok
# checks authentication of Secure Boot EFI variables
def check_secureboot_key_variables(self):
sts = 0
... | KEK, EFI_VARIABLE_DICT[EFI_VAR_NAME_KEK] )
sts |= self.check_EFI_variable_authentication( EFI_VAR_NAME_db, EFI_VARIABLE_DICT[EFI_VAR_NAME_db] )
sts |= self.check_EFI_variable_authentication( EFI_VAR_NAME_dbx, EFI_VARIABLE_DICT[EFI_VAR_NAME_dbx] )
st... |
MSLNZ/msl-equipment | msl/examples/equipment/picotech/picoscope/acquire_AWG_custom.py | Python | mit | 2,306 | 0.002602 | """
This example outputs a custom waveform and records the waveform on Channel A.
The output of the AWG must be connected to Channel A.
"""
import os
import numpy as np
# if matplotlib is available then plot the results
try:
import matplotlib.pyplot as plt
except ImportError:
plt = None
from msl.equipment i... | mentRecord,
ConnectionRecord,
Backend,
)
record = EquipmentRecord(
manufacturer='Pico Technology',
model='5244B', # update for your PicoScope
serial='DY135/055', # update for your PicoScope
connection=ConnectionRecord(
backend=Backend.MSL,
address='SDK::ps5000a.dll', # update... | a ps5000a series PicoScope
'auto_select_power': True, # for PicoScopes that can be powered by an AC adaptor or a USB cable
},
)
)
# optional: ensure that the PicoTech DLLs are available on PATH
os.environ['PATH'] += os.pathsep + r'C:\Program Files\Pico Technology\SDK\lib'
print('Example :: A... |
PyCQA/baron | tests/test_grammator_operators.py | Python | lgpl-3.0 | 293,854 | 0.000163 | #!/usr/bin/python
# -*- coding:Utf-8 -*-
import pytest
from baron.parser import ParsingError
from .test_utils import parse_simple
def test_simple_power():
"a**b"
parse_simple([
('NAME', 'a'),
('DOUBLE_STAR', '**'),
('NAME', 'b')
], [
{
"type": "binary_operator",... | [('SPACE', ' ')]),
('NAME', 'b'),
('DOUBLE_STAR', '**', [('SPACE', ' ')], [('SPACE', ' ')]),
('NAME', | 'c')
], [
{
"type": "binary_operator",
"value": '**',
"first": {
"type": "name",
"value": 'a'
},
"second": {
"type": "binary_operator",
"value": '**',
"first": {
... |
mrcodehang/cqut-chat-server | test/test_http.py | Python | mpl-2.0 | 75 | 0.013333 | from others import sms_request
print(sms_reques | t('15683000435', '12345 | 6')) |
kesara/tetrapy | tetrapy.py | Python | gpl-3.0 | 3,480 | 0.005747 | ###############################################################################
# tetrapy.py
# Tetrapy
#
# Copyright (C) 2013 Kesara Rathnayake
#
# Tetrapy 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, eithe... | elif (self.collied(matrix)):
r | eturn True
return False
def getMatrix(self):
matrix = []
for i in range(0, 4):
matrix.append((self.x, self.y+20*i))
return matrix
def collied(self, matrix):
for i in range(0, 4):
if (self.x, self.y+20*i) in matrix:
return True
... |
SaintlyVi/DLR_DB | evaluation/calibration.py | Python | mit | 5,511 | 0.01869 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 15 14:09:59 2017
@author: SaintlyVi
"""
import pandas as pd
import numpy as np
from support import writeLog
def uncertaintyStats(submodel):
"""
Creates a dict with statistics for observed hourly profiles for a given year.
Use evaluati... | alidmodels.set_index('submodel_name', drop=True, inplace=True)
return validmodels
def modelSimilarity(ex_submodel, ex_ts, valid_new_submodel, new_ts, submod_type):
"""
This | function calcualtes the evaluation measure for the run.
ex_submodel = (DataFrame) either existing/expert demand_summary or hourly_profiles submodel
valid_new_submodel = (DataFrame) output from dataIntegrity function
-> only want to compare valid data
submod_type = (str) one... |
tylertian/Openstack | openstack F/python-keystoneclient/tests/test_memcache_crypt.py | Python | apache-2.0 | 3,163 | 0 | import testtools
from keystoneclient.middleware import memcache_crypt
class MemcacheCryptPositiveTests(testtools.TestCase):
def _setup_keys(self, strategy):
return memcache_crypt.derive_keys('token', 'secret', strategy)
def test_constant_time_compare(self):
# make sure it works as a compare,... | ))
def test_derive_keys(self):
keys = memcache_crypt.derive_keys('token', 'secret', 'strategy')
self.assertEqual(len(keys['ENCRYPTION']),
len(keys['CACHE_KEY']))
self.assertEqual(len(keys['CACHE_KEY']),
len(keys['MAC']))
self.assertN... | .assertIn('strategy', keys.keys())
def test_key_strategy_diff(self):
k1 = self._setup_keys('MAC')
k2 = self._setup_keys('ENCRYPT')
self.assertNotEqual(k1, k2)
def test_sign_data(self):
keys = self._setup_keys('MAC')
sig = memcache_crypt.sign_data(keys['MAC'], 'data')
... |
flavour/eden | modules/templates/historic/ARC/config.py | Python | mit | 84,335 | 0.008044 | # -*- coding: utf-8 -*-
from collections import OrderedDict
from gluon import current
from gluon.storage import Storage
def config(settings):
"""
Template settings for American Red Cross
Demo only, not in Production
"""
T = current.T
# ==============================================... | able[link_table.link_key] == row.id).select(table.id,
# limitby=(0, 1))
# if rows:
# # Update not Create
# row = rows.first()
# Check if there is a FK to inherit the realm_entity
realm_entity = 0
... | fault_fk in table.fields:
fk = default_fk
# Inherit realm_entity from parent record
if fk == EID:
ftable = s3db.pr_person
query = (ftable[EID] == row[EID])
else:
ftablename = table[fk].type[10:] #... |
johnchen902/toyoj | judge/toyojjudge/checker/exact.py | Python | agpl-3.0 | 259 | 0.003861 | from . import Checker
class ExactChecker(Checker):
async def check(self, san | dbox, task):
output = await sandbox.read("/tmp/output | .txt")
task.accepted = output == task.testcase.output
task.verdict = "AC" if task.accepted else "WA"
|
I2Cvb/data_balancing | src/data_conversion/datasets/arrhythmia.py | Python | mit | 6,789 | 0.001326 | """ Cardiac Arrhythmia Database
The original dataset and further information can be found here:
https://archive.ics.uci.edu/ml/datasets/Arrhythmia
Brief description
-----------------
This data contains 452 observations on 279 variables (206 linear valued
+ 73 nominal) on ECG readings. The data was collected to... | fter R
20 S' wave
21 Number of intrinsic deflections, linear
22 Existence of ragged R wave, nominal
23 Existence of diphasic derivation of R wave, nominal
24 Existence of ragged P wave, nominal
25 Existence of diphasic derivation of P wave, nominal
2 | 6 Existence of ragged T wave, nominal
27 Existence of diphasic derivation of T wave, nominal
Of channel DII:
28 .. 39 (similar to 16 .. 27 of channel DI)
Of channels DIII:
40 .. 51
Of channel AVR:
52 .. 63
Of channel AVL:
64 .. 75
Of channel AVF:
76 .. 87
... |
lmazuel/azure-sdk-for-python | azure-cognitiveservices-vision-face/azure/cognitiveservices/vision/face/models/__init__.py | Python | mit | 3,118 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | est
from .similar_face import SimilarFace
from .group_request import GroupRequest
from .group_result import GroupResult
from .identify_request import IdentifyRequest
from .identify_candidate import IdentifyCandidate
| from .identify_result import IdentifyResult
from .verify_face_to_person_request import VerifyFaceToPersonRequest
from .verify_face_to_face_request import VerifyFaceToFaceRequest
from .verify_result import VerifyResult
from .persisted_face import PersistedFace
from .face_list import FaceList
from .person_group import Pe... |
rogerthat-platform/rogerthat-backend | src/rogerthat/models/properties/news.py | Python | apache-2.0 | 14,083 | 0.001562 | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# 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... | ibuted on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either expre | ss or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@
import logging
from collections import defaultdict
from contextlib import closing
from datetime import datetime
from google.appengine.ext import db
from mcfw.properties im... |
iohannez/gnuradio | gr-analog/python/analog/qa_random_uniform_source.py | Python | gpl-3.0 | 2,736 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2015 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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... | seful,
# but WITHOUT ANY WARRANTY; without even t | he implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin St... |
ANickerson/kilosort-py | src/algorithms.py | Python | gpl-2.0 | 10,332 | 0.012195 | """
Module containing all the individual algorithms.
It would be possible to use alternative implementations
"""
import numpy as np
import theano
from theano import tensor as T
from theano.tensor import nlinalg
class algorithms_numpy():
"""
The algorit | hms implemented in numpy.
This should be the base class for any extended implementations
global notes:
gather_ | try is a concept of executing planned matrix operations. Not implmented
global todos:
TODO: remove/alter ops.
TODO: better commenting of code
TODO: test output of functions with matlab code - find some input!
TODO: min function in matlab returns index as well as value. need to fix all calls as the... |
hugollm/foster | tests/frames/build/foobar/bar/bar.py | Python | mit | 29 | 0 | def b | ar():
print(' | bar!')
|
gensmusic/test | l/python/book/learning-python/c22/module3.py | Python | gpl-2.0 | 137 | 0.043796 | #!/usr/bin/python
#coding:utf-8
| print 'start to load...'
import sys
name = 42
def func(): pass
cla | ss kclass : pass
print 'done loading.' |
blitzmann/Pyfa | gui/fitCommands/guiRemoveBooster.py | Python | gpl-3.0 | 1,009 | 0.000991 | import wx
from service.fit import Fit
import gui.mainFrame
from gui import globalEvents as GE
from .calc.fitRemoveBooster import FitRe | move | BoosterCommand
class GuiRemoveBoosterCommand(wx.Command):
def __init__(self, fitID, position):
wx.Command.__init__(self, True, "")
self.mainFrame = gui.mainFrame.MainFrame.getInstance()
self.sFit = Fit.getInstance()
self.internal_history = wx.CommandProcessor()
self.fitID =... |
djfroofy/beatlounge | bl/midi.py | Python | mit | 11,595 | 0.000172 | import pypm
from bl.utils import getClock
from bl.debug import debug
__all__ = ['init', 'initialize', 'getInput', 'getOutput', 'printDeviceSummary',
'ClockSender', 'MidiDispatcher', 'FUNCTIONS', 'ChordHandler',
'MonitorHandler', 'NoteEventHandler']
class PypmWrapper:
"""
Simple wrapper... | OCK = globals()['TIMINGCLOCK']
class MidiDispatcher(object):
"""
Dispatcher for events received from a midi input channel.
Example usage:
in | it()
input = getInput(3)
def debug_event(event):
print event
disp = MidiDispatcher(input, [debug_event, NoteOnOffHandler(instr)])
disp.start()
"""
def __init__(self, midiInput, handlers, clock=None):
self.clock = getClock(clock)
self.midiInput = midiI... |
markramm/jujulib | juju/exceptions.py | Python | lgpl-3.0 | 219 | 0 |
class EnvironmentNotBootstrapped(Exception):
def __init__(s | elf, environment):
self.environment = environment
def __str__(self):
return "environment %s is not bo | otstrapped" % self.environment
|
tommy-u/enable | enable/text_field_style.py | Python | bsd-3-clause | 1,133 | 0.013239 | # Enthought library imports
from traits.api import HasTrait | s, Int, Bool
from kiva.trait_defs.api import KivaFont
from enable.colors import ColorTrait
class TextFieldStyle(HasTraits):
""" This class holds style settings for rendering an EnableTextField.
fixme: See docstring on EnableBoxStyle
"""
# The color of the text
text_color = ColorTrait((0,0,0,1... | ont("Courier 12")
# The color of highlighted text
highlight_color = ColorTrait((.65,0,0,1.0))
# The background color of highlighted items
highlight_bgcolor = ColorTrait("lightgray")
# The font for flagged text (must be monospaced!)
highlight_font = KivaFont("Courier 14 bold")
# The numbe... |
ergonomica/ergonomica | tests/stdlib/test_cd.py | Python | gpl-2.0 | 557 | 0.003591 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
[tests/stdlib/test_cd.py]
Test the cd | command.
"""
im | port unittest
import os
import tempfile
from ergonomica import ergo
class TestCd(unittest.TestCase):
"""Tests the cd command."""
def test_cd(self):
"""
Tests the cd command.
"""
olddir = os.getcwd()
newdir = tempfile.mkdtemp()
ergo("cd {}".format(newdir))
... |
ahmedaljazzar/edx-platform | lms/djangoapps/shoppingcart/admin.py | Python | agpl-3.0 | 5,178 | 0.000386 | """Django admin interface for the shopping cart models. """
from django.contrib import admin
from shoppingcart.models import (
Coupon,
CourseRegistrationCodeInvoiceItem,
DonationConfiguration,
Invoice,
InvoiceTransaction,
PaidCourseRegistrationAnnotation
)
class SoftDeleteCouponAdmin(admin.Mo... | s = (
'created',
'modified',
'created_by',
'last_modified_by'
)
class InvoiceAdmin(admin.ModelAdmin):
"""Admin for invoices.
This is intended for the internal finance team
to be able to view and update invoice information,
including payments and refunds.
"""
... | r_reference_number',
'company_name',
)
fieldsets = (
(
None, {
'fields': (
'internal_reference',
'customer_reference_number',
'created',
'modified',
)
}
... |
ChrisTruncer/Just-Metadata | modules/analytics/cert_search.py | Python | gpl-3.0 | 1,648 | 0.003034 | '''
This module searches the shodan data for IPs using a user-specified https certific | ate
'''
from common import helpers
class Analytics:
def __init__(self, cli_options):
self.cli_name = "CertSearch"
self.description = "Searches for user-pr | ovided HTTPS certificate"
self.https_cert = ''
self.found_ips = []
def analyze(self, all_ip_objects):
if self.https_cert == '':
print "Please provide the HTTPS certificate you want to search for."
self.https_cert = raw_input(' \n\n[>] HTTPS Cert (including start and... |
oknuutti/visnav-py | visnav/iotools/read-raw-img.py | Python | mit | 811 | 0.006165 | import sys
import numpy as np
import cv2
def main():
w, h = map(int, (sys.argv[1] if len(sys.argv) > 1 else '2048x1944').split('x'))
imgfile = sys.argv[2] if len(sys.argv) > 2 else r'D:\Downloads\example-navcam-imgs\navcamTests0619\rubbleML-def-14062019-25.raw | '
i | mgout = sys.argv[3] if len(sys.argv) > 3 else r'D:\Downloads\example-navcam-imgs\navcamTests0619\rubbleML-def-14062019-25.png'
with open(imgfile, 'rb') as fh:
raw_img = np.fromfile(fh, dtype=np.uint16, count=w * h)
raw_img = raw_img.reshape((h, w))
# flip rows pairwise
final_img = raw... |
faneshion/MatchZoo | matchzoo/tasks/__init__.py | Python | apache-2.0 | 72 | 0 | from | .classification | import Classification
from .ranking import Ranking
|
mcstrother/dicom-sr-qi | inquiries/high_cases.py | Python | bsd-2-clause | 7,573 | 0.010828 | from srqi.core import inquiry
import matplotlib.pyplot as plt
import numpy as np
def get_accumulation_fig(proc):
fig = plt.figure()
plt.title("Accumulation During Procedure for Patient " + str(proc.PatientID) + " on " + str(proc.StudyDate))
event_starts = [e.DateTime_Started for e in proc.get_events... | =='Spot'])
high_cases[proc]['fluoro frames'] = sum([e.Number_of_Pulses for e in proc.get_fluoro_e | vents()])
high_cases[proc]['total frames'] = sum([e.Number_of_Pulses for e in proc.get_events()])
self.high_cases = high_cases
def get_text(self):
if len(self.high_cases) == 0:
return "No cases exceeding the dose limit found in the specified date ... |
mancoast/pycdc | tests/22_test_expressions.ref.py | Python | gpl-3.0 | 119 | 0.016807 |
def _lsbStrToInt(str):
return ord(s | tr[0]) + (ord(str[1]) << 8) + (ord(str[2]) << 16) + (ord(str[3]) << 24)
| |
kerautret/ipolDevel | ipol_demo/lib/base_app.py | Python | gpl-3.0 | 27,462 | 0.003459 | """
base IPOL demo web app
includes interaction and rendering
"""
# TODO add steps (cf amazon cart)
import shutil
from mako.lookup import TemplateLookup
import traceback
import cherrypy
import os.path
import math
import copy
import threading
import time
from mako.exceptions import RichTraceback
from . import http
fr... | blic_archive', '1') == '0':
| cherrypy.response.cookie['public_archive'] = '1'
self2.cfg['meta']['public'] = True
else:
self2.cfg['meta']['public'] \
= (cherrypy.request.cookie['public_archive'] != '0')
# user setting
if kwargs.has_key('set_public_archive'):
if kwargs.pop(... |
okuchaiev/f-lm | language_model_test.py | Python | mit | 1,667 | 0.0006 | import random
import numpy as np
import tensorflow as tf
from language_model import LM
from hparams import HParams
def get_test_hparams():
return HParams(
batch_size=21,
num_steps=12,
num_shards=2,
num_layers=1,
learning_rate=0.2,
max_grad_norm=1.0,
vocab_s... | 14,
state_size=17,
projected_size=15,
num_sampled=500,
num_gpus=1,
average_params=True,
run_profiler=False,
)
def simple_data_generator(batch_size, num_s | teps):
x = np.zeros([batch_size, num_steps], np.int32)
y = np.zeros([batch_size, num_steps], np.int32)
for i in range(batch_size):
first = random.randrange(0, 20)
for j in range(num_steps):
x[i, j] = first + j
y[i, j] = first + j + 1
return x, y, np.ones([batch_si... |
Leon109/IDCMS-Web | web/app/auth/errors.py | Python | apache-2.0 | 349 | 0.011461 | from flask import render_template
from . import auth
@auth.app_errorhandler(403)
de | f page_not_found(e):
return render_template('403.html'), 403
@auth.app_errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@auth.app_errorhandler(500)
def internal_server_error(e):
re | turn render_template('500.html'), 500
|
dungeonsnd/test-code | dev_examples/twisted_test/other_echo/echoserv_udp.py | Python | gpl-3.0 | 510 | 0.009804 | #!/usr/bin/env python
# Copyright (c) Twis | ted Matrix Laboratories.
# See | LICENSE for details.
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
# Here's a UDP version of the simplest possible protocol
class EchoUDP(DatagramProtocol):
def datagramReceived(self, datagram, address):
self.transport.write(datagram, address)
def m... |
daniel-dinu/rational-python | test_rational/test_rational.py | Python | mit | 32,468 | 0.001016 | import unittest2
from unittest2 import TestCase
from rational.rational import gcd
from rational.rational import Rational
__author__ = 'Daniel Dinu'
class TestRational(TestCase):
def setUp(self):
self.known_values = [(1, 2, 1, 2),
(-1, 2, -1, 2),
... | (Rational(1, 2), Rational(-1, 2), (2, -2)),
(Rational(1, 2), Rational(-1, 4), (4, -2)),
(Rational(1, 4), Rational(-1, 2), (2, -4)),
(Rational(-1, 2), Rational(-1, 2), (-2, -2)),
(Ra... | (Rational(-1, 4), Rational(-1, 2), (-2, -4))]
for a, b, expected_result in test_transform_values:
with self.subTest(a=a, b=b, expected_result=expected_result):
computed_result = Rational.transform(a, b)
self.assertEqual(expected_result, computed_resul... |
bszcz/python | tutorial_notes.py | Python | mit | 4,575 | 0.007213 | # Copyright (c) 2020 Bartosz Szczesny <bszcz@bszcz.org>
# This program is free software under the MIT license.
print('\n# avoid new line at the beginning')
s = """\
test
"""
print(s)
print('\n# string are immutable')
s = 'string'
try:
s[1] = 'p'
except TypeError as e:
print(e)
print('\n# enumerate() functi... | t(ns.get_n())
print('\n# lists operations')
print("""\
a = list()
a.copy() => a[:] # return shallow copy
a.clear() => del a[:]
a.append(item) => a[len(a):] = [it | em]
a.extend(iterable) => a[len(a):] = iterable
""")
print('\n# set comprehension')
a = 'abracadabra'
s = {x for x in a}
print(a, '->', s)
print('\n# keys can be any immutable type')
d = dict()
d[('a', 1)] = 100
d[('b', 2)] = 200
print(d)
print('\n# dictionary comprehension')
d = {x: 'got ' + str(x) for x in rang... |
thumbor-community/librato | setup.py | Python | mit | 441 | 0 | # coding: utf-8
from setuptools import setup, find_packages
setup | (
name='tc_librato',
version="0.0.1",
description='Thumbor Librato extensions',
author='Peter Schröder, Sebastian Eichner',
author_email='peter.schroeder@jimdo.com, sebastian.eichner@jimdo.com',
zip_safe=False,
include_package_data=True,
packages=f | ind_packages(),
install_requires=[
'thumbor',
'librato-metrics',
]
)
|
pivstone/andromeda | registry/middleware.py | Python | mit | 797 | 0.00129 | # coding=utf-8
from django import http
from django.conf | import settings
from django.contrib.auth import authenticate
from django.utils.cache import patch_vary_headers
from registry.exceptions import RegistryException
__author__ = 'pivstone'
class CustomHeaderMiddleware(object):
"""
增加自定头
"""
def process_response(self, request, response):
for key,... | 统一错误返回
"""
def process_exception(self, request, exception):
if isinstance(exception, RegistryException):
response = http.JsonResponse(status=exception.status, data=exception.errors())
return response
|
munhyunsu/Hobby | Signal/signal_propagation_shell.py | Python | gpl-3.0 | 819 | 0.003663 | import os
import sys
import signal
import time
import subprocess
WHO = None
def handler(signum, frame):
global WHO
print('Signal | handler', signum, WHO, frame)
print('Disable handler', signum, WHO, frame)
signal.signal(signal.SIGINT, signal.SIG_DFL)
def main(argv):
global WHO
WHO = argv[1]
if WHO == 'parent':
signal.signal(signal.SIGINT, handler)
p = subprocess.Popen('python3 signal_propagation.py child',
... | )
if WHO == 'parent':
p.send_signal(signal.SIGINT)
p.communicate()
else:
while True:
time.sleep(1)
print('Sleep 1 infinity')
if __name__ == '__main__':
main(sys.argv)
|
cmjatai/cmj | sapl/comissoes/migrations/0019_auto_20181214_1023.py | Python | gpl-3.0 | 509 | 0.001972 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-12-14 12:23
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('comissoes', '0018_auto_20180924_1724'),
]
operations = [
migrations.AlterFi... | name='hora_fim',
field=models.TimeField(blank=True, null=True, verbose_name='Horário | de Término (hh:mm)'),
),
]
|
rembo10/headphones | lib/feedparser/exceptions.py | Python | gpl-3.0 | 1,957 | 0.000511 | # Exceptions used throughout feedparser
# Copyright 2010-2021 Kurt McKee <contactme@kurtmckee.org>
# Copyright 2002-2008 Mark Pilgrim
# All rights reserved.
#
# This file is a part of feedparser.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the follo... | NCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SU | BSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DA... |
mhugent/Quantum-GIS | python/plugins/processing/interface.py | Python | gpl-2.0 | 38 | 0 | # - | *- coding: utf-8 -*-
| iface = None
|
mpetyx/palmdrop | venv/lib/python2.7/site-packages/cms/plugins/flash/migrations/0001_initial.py | Python | apache-2.0 | 3,244 | 0.008323 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Flash'
db.create_table('cmsplugin_flash', (
('cmsplugin_ptr', self.gf('django.db... | lugin_flash')
models = {
'cms.cmsplugin': {
'Meta': {'object_name': 'CMSPlugin'},
'changed_date': ('django | .db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language': ('django.db.models... |
carboncointrust/CarboncoinCore | contrib/linearize/linearize.py | Python | mit | 3,360 | 0.034226 | #!/usr/bin/python
#
# linearize.py: Construct a linear, no-fork, best version | of the blockchain.
#
#
# Copyright (c) 2013 The Carboncoin developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
import json
import struct
import re
import base64
import httplib
import sys
ERR_SLEEP = 15
MAX_NONCE = 10... | inRPC:
OBJID = 1
def __init__(self, host, port, username, password):
authpair = "%s:%s" % (username, password)
self.authhdr = "Basic %s" % (base64.b64encode(authpair))
self.conn = httplib.HTTPConnection(host, port, False, 30)
def rpc(self, method, params=None):
self.OBJID += 1
obj = { 'version' : '1.1',
... |
assaabloy-ppi/salt-channel-python | saltchannel/saltlib/pure_pynacl/tweetnacl.py | Python | mit | 25,273 | 0.005342 | # -*- coding: utf-8 -*-
# import python libs
import os
from array import array
# import pure_pynacl libs
from saltchannel.saltlib.pure_pynacl import lt_py3, lt_py33
from saltchannel.saltlib.pure_pynacl import TypeEnum, integer, Int, IntArray
class u8(Int):
'''unsigned char'''
bits = array('B').itemsize*8
... | d = True
order = TypeEnum.i64
def __repr__(self):
return 'i64(%s)' % integer.__repr__(self)
class gf(IntArray):
def __init__(self, init=()):
IntArray.__init__(self, i64, init=init, size=16)
def randombytes(c, s):
'''
insert s random bytes into c
'''
if lt_py3:
c[... | _121665 = gf([0xDB41, 1])
D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203])
D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406])
X = gf([0xd51a, 0x8... |
Joel-U/sparkle | sparkle/stim/auto_parameter_model.py | Python | gpl-3.0 | 15,413 | 0.002336 | import numpy as np
class AutoParameterModel():
"""Model to hold all the necessary information to generate
auto-tests, where parameters of components are systematically
manipulated
"""
def __init__(self):
self._parameters = []
def nrows(self):
"""The number of auto-parameters
... | """Sets the arguments as field=val for parameter
indexed by *row*
:param row: the ith pa | rameter number
:type row: int
"""
param = self._parameters[row]
for key, val in kwargs.items():
param[key] = val
def paramValue(self, row, field):
"""Gets the value for *field* for parameter indexed by
*row*
:param row: the ith parameter ... |
Oriphiel/Python | AlarmaTecno/Alarma/migrations/0005_djkombumessage_djkombuqueue.py | Python | apache-2.0 | 1,116 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('Alarma', '0004_auto_20151025_0206'),
]
operations = [
migrations.CreateModel(
name='DjkombuMessage',
| fields=[
('id', models.IntegerField(serialize=False, primary_key=True)),
('visible', models.BooleanField()),
('sent_at', models.DateTimeField(null=True, blank=True)),
('payload', models.TextField()),
],
options={
... | igrations.CreateModel(
name='DjkombuQueue',
fields=[
('id', models.IntegerField(serialize=False, primary_key=True)),
('name', models.CharField(unique=True, max_length=200)),
],
options={
'db_table': 'djkombu_queue',
... |
Twilight0/service.subtitles.subtitles.gr | resources/lib/addon.py | Python | gpl-3.0 | 12,802 | 0.002812 | # -*- coding: utf-8 -*-
'''
Subtitles.gr Addon
Author Twilight0
SPDX-License-Identifier: GPL-3.0-only
See LICENSES/GPL-3.0-only for more information.
'''
import re, unicodedata
from shutil import copy
from os.path import splitext, exists, split as os_split
from resources.lib import subtitlesgr, xsubs... | ery), executor.submit(self.xsubstv, query),
executor.submit(self.vipsubs, query), executor.submit(self.podnapisi, query)
]
for future in concurrent_futures.as_c | ompleted(threads):
item = future.result()
if not item:
continue
self.list.extend(item)
if len(self.list) == 0:
control.directory(self.syshandle)
return
f = []
# noinspection PyUnre... |
FredHutch/swift-switch-account | sw2account/sw2account.py | Python | apache-2.0 | 11,887 | 0.025742 | #!/usr/bin/python
__version__='0.2.1'
impo | rt argparse
import logging
import os
import os.path
import sys
import requests
import getpass
import ConfigParser
def _persist( export, rcfile ):
f = open( rcfile, 'w' )
logging.debug( "writing to {}".format( rcfile ) ) |
f.write( "\n".join( export ) )
f.close()
os.chmod( rcfile, 0600 )
logging.info( "saved Swift credentials" )
def sh(creds, auth_version, savepw=False, persist=False ):
export = []
if auth_version == 'v1':
export.append(
"unset OS_USERNAME OS_PASSWORD OS_TENANT_NAME OS_AUTH_U... |
tarashor/vibrations | py/fem/result.py | Python | mit | 2,014 | 0.004965 | import numpy as np
from . import finiteelements as fe
from . import matrices
from math import cos
class Result:
def __init__(self):
pass
def __init__(self, freq, u1, u2, u3, mesh, geometry):
self.freq = freq
self.u1 = u1
self.u2 = u2
self.u3 = u3
self.mesh ... | ps):
return rps/(2*np.pi)
def get_displacement_and_deriv(self, x1, x2, x3, time):
element = self | .mesh.get_element(x1, x3)
if (element is None):
print ("x1 = {}, x2 = {}".format(x1, x3))
u_nodes = np.zeros((8))
u_nodes[0] = self.u1[element.top_left_index]
u_nodes[1] = self.u1[element.top_right_index]
u_nodes[2] = self.u1[element.bottom_right_index]
u_n... |
arseneyr/essentia | test/src/unittest/spectral/test_hpcp.py | Python | agpl-3.0 | 7,101 | 0.021405 | #!/usr/bin/env python
# Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia 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 ... | maxFrequency = sampleRate/2,
minFrequency = 0,
orderBy = 'magnitude')
hpcpAlg = HPCP( | minFrequency=50, maxFrequency=500, bandPreset=False, harmonics=3)
frame = fc(audio)
while len(frame) != 0:
spectrum = specAlg(windowingAlg(frame))
(freqs, mags) = sPeaksAlg(spectrum)
hpcp = hpcpAlg(freqs,mags)
self.assertTrue(not any(numpy.isnan(hpcp... |
ssanderson/turing.py | turing.py | Python | mit | 2,182 | 0.007333 | required_states = ['accept', 'reject', 'init']
class TuringMachine(object):
def __init__(self, sigma, gamma, delta):
self.sigma = sigma
self.gamma = gamma
self.delta = delta
self.state = None
self.tape = None
self.head_position = None
return
... | arr=transition[2])
)
self.state = transition[0]
self.tape[self.head_position] = transition[1]
if(transition[2] == 'left'):
self.head_position = max(0, self.head_position - 1)
else:
assert(transition[2]... | self.print_tape_contents()
return
def print_tape_contents(self):
formatted = ''.join(char if i != self.head_position else '[%s]' % char
for i, char in enumerate(self.tape))
print(formatted)
def run(self, input_string, verbose=False):
... |
dsp-jetpack/JetPack | src/pilot/control_overcloud.py | Python | apache-2.0 | 1,930 | 0 | #!/usr/bin/python3
# Copyright (c) 2016-2021 Dell Inc. or its subsidiaries.
#
# 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... | elp="Control power state of all overcloud nodes")
args = parser.parse_args()
os_auth_url, os_tenant_name, os_username, os_password, \
os_user_domain_name, os_project_domain_name = \
CredentialHelper.get_undercloud_creds()
kwargs = {'os_username': os_user | name,
'os_password': os_password,
'os_auth_url': os_auth_url,
'os_tenant_name': os_tenant_name,
'os_user_domain_name': os_user_domain_name,
'os_project_domain_name': os_project_domain_name}
ironic = client.get_client(1, **kwargs)
for node in... |
rhcarvalho/kombu | kombu/tests/async/http/test_curl.py | Python | bsd-3-clause | 5,102 | 0.000196 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from kombu.async.http.curl import READ, WRITE, CurlClient
from kombu.tests.case import (
HubCase, Mock, call, patch, case_requires, set_module_symbol,
)
@case_requires('pycurl')
class test_CurlClient(HubCase):
class Client(CurlClient):
... | hub.add_reader.assert_called_with(fd, x.on_readable, fd)
hub.add_writer.assert_called_with(fd, x.on_writable, fd)
self.assertEqual(x._fds[fd], READ | WRITE)
# UNKNOWN EVENT
hub = x.hub = Mock(name='hub')
x._handle_socket(0xff3f, fd, x._multi, None, _pycurl... | DS
hub = x.hub = Mock(name='hub')
x._fds.clear()
x._handle_socket(0xff3f, fd, x._multi, None, _pycurl)
self.assertFalse(hub.remove.called)
def test_set_timeout(self):
x = self.Client()
x._set_timeout(100)
def test_timeout_check(self):
wit... |
rsinger86/goose-extractor | goose/article.py | Python | apache-2.0 | 4,751 | 0.00021 | # -*- coding: utf-8 -*-
"""\
This is a python port of "Goose" orignialy licensed to Gravity.com
under one or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.
Python port was written by Xavier Grangier for Recrutae
Gravity.co... | the publish date of an article was
self.publish_date = None
# A property bucket for consumers of goose to store custom data extractions.
self.additional_data = {}
@property
def infos(self):
data = {
"meta": {
"description": self.meta_description,
... | },
"image": None,
"domain": self.domain,
"title": self.title,
"cleaned_text": self.cleaned_text,
"opengraph": self.opengraph,
"tags": self.tags,
"tweets": self.tweets,
"movies": [],
"links": self.links... |
erwindl0/python-rpc | org.eclipse.triquetrum.python.service/scripts/scisoftpy/plot.py | Python | epl-1.0 | 26,232 | 0.006023 | ###
# Copyright 2011 Diamond Light Source Ltd.
#
# 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 l... | YPES = ["PNG/JPEG File", "Postscript File", "SVG File"]
d | ef export(name=None, format=None, savepath=None):
'''Export plot to svg, png, jpg, ps
Argument:
name -- name of plot view to use (if None, use default name)
format -- format of the file to export to: can be 'svg', 'png', 'jpg' or 'ps' (if None, svg is used by default)
savepath -- full path an... |
burbanom/python-utils | file_utils.py | Python | gpl-3.0 | 1,260 | 0.00873 | from __future__ import print_function
import os
import sys
import fnmatch
import mmap
def clean_fil | es(path,pattern):
all_files = os.listdir(path)
filtered = fnmatch.filter(all_files,pattern+"*")
for element in filtered:
os.remove(os.path.join(path,element))
def find_files(path,target):
matches = []
for root, subFolders, files in os.walk(path):
if target in files:
mat... | tch.filter(filenames, pattern):
matches.append([root,filename])
return matches
def return_value(filename,pattern):
if type(pattern) is str:
pattern = pattern.encode()
with open(filename, "r") as fin:
# memory-map the file, size 0 means whole file
m = mmap.mmap(fin.fileno... |
DelusionalLogic/TAS-100 | python/test.py | Python | gpl-3.0 | 571 | 0.010508 | import serial
import time
ser = serial.Serial(
port = "/dev/ttyACM0",
baudrate = 9600,
bytesize = serial.EIGHTBITS
)
time.sleep(2)
ser.write("\x36\x20\x00")
print(hex(ord(ser.read(1))))
print(hex(ord(se | r.read(1))))
print(hex(ord(ser.read(1))))
print(hex(ord(ser.read(1))))
print(hex(ord(ser.read(1))))
print(hex(ord(ser.read(1))))
print(hex(ord(ser.read(1))))
print(hex(ord(ser.read(1))))
print(hex(ord(ser.read(1))))
print(hex(ord(ser.read(1 | ))))
print(hex(ord(ser.read(1))))
print(hex(ord(ser.read(1))))
print(hex(ord(ser.read(1))))
|
repotvsupertuga/repo | plugin.video.exodus/resources/lib/sources/newlinks_mv.py | Python | gpl-2.0 | 4,985 | 0.016048 | # -*- coding: utf-8 -*-
'''
Exodus Add-on
Copyright (C) 2016 Exodus
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 l... | n the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If... | import re,urllib,urlparse,json,base64
from resources.lib.modules import cleantitle
from resources.lib.modules import client
from resources.lib.modules import debrid
class source:
def __init__(self):
self.domains = ['newmyvideolink.xyz', 'beta.myvideolinks.xyz']
self.base_link = 'http://newmyvideo... |
Sohojoe/damon | damon1/replace_it.py | Python | apache-2.0 | 14,439 | 0.019046 | """replace.py
Tool for replacing variable names in Damon.
Copyright (c) 2009 - 2011, Mark H. Moulton for Pythias Consulting, LLC.
Purpose: This tool was developed to replace CamelCase argument
variables with all lower case equivalents across all Damon modules.
It is being retained because it is readily adaptable to ... | nts',
'OutputAs':'output_as',
'RespCats':'resp_cats',
'RLRow':'rl_row',
'RLCol | ':'rl_col',
'CLRow':'cl_row',
'CLCol':'cl_col',
'CoreRow':'core_row',
'CoreCol':'core_col',
'WholeRow':'whole_row',
'WholeCol':'whole_col',
'WholeArray':'whole',
'Fileh':'fileh',
'TextFile':'textfile',
'TextFil... |
EVEprosper/ProsperAPI | scripts/manager.py | Python | mit | 850 | 0.001176 | """manager.py: Flask-Script launcher for services
using https://github.com/yabb85/ueki as prototype
"""
from os import path
from flask_script import Manager, Server
from publicAPI import create_app
import prosper.common.prosper_logging as p_logging
import prosper.common.prosper_config as p_config
HERE = path.abspa... | E, 'app.cfg')
CONFIG = p_config.ProsperConfig(CONFIG_FILEPATH)
SETTINGS = {
'PORT':8001
}
APP = create_app(SETTINGS, CONFIG)
MANAGER = Manager(APP)
MANAGER.add_command(
'runserver',
Server(
host='0.0.0.0',
port=CONFIG.get('PROD', 'PORT')
)
)
MANAGER.add_command(
'debug',
Serve... | port=CONFIG.get('DEBUG', 'PORT')
)
)
if __name__ == '__main__':
MANAGER.run()
|
opnsense/core | src/opnsense/scripts/filter/list_tables.py | Python | bsd-2-clause | 1,992 | 0.000502 | #!/usr/local/bin/python3
"""
Copyright (c) 2015-2019 Ad Schellevis <ad@opnsense.org>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain th... | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
--------------------------------------------------------------------------------------
returns a list of pf tables (optional as a json container)
"""
import... |
suda/micropython | tests/micropython/heapalloc.py | Python | mit | 891 | 0.007856 | # check that we can do certain things without allocating heap memory
import gc
def f1(a):
print(a)
def f2(a, b=2):
print(a, b)
def f3(a, b, c, d):
x1 = x2 = a
x3 = x4 = b
x5 = x6 = c
x7 = x8 = d
print(x1, x3, x5, x7, x2 + x4 + x6 + x8)
global_var = 1
def test():
global global_var
... | # function call
f1(i * 2 + 1) # binary operation with small ints
f1(a=i) # keyword arguments
f2(i) # default arg (second one)
f2(i, i) # 2 args
f3(1, 2, 3, 4) # function with lots of local state
# call h with heap allocation disabled and all memory u... | r boundmeth
except MemoryError:
pass
test()
gc.enable()
|
HybridF5/jacket | jacket/tests/compute/unit/virt/libvirt/volume/test_volume.py | Python | apache-2.0 | 11,446 | 0 | # Copyright 2010 OpenStack Foundation
# Copyright 2012 University Of Minho
#
# 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.... | o)
tree = conf.format_dom()
self._assertDiskInfoEquals(tree, self.disk_info)
def test_libvirt_volume_disk_info_type(self):
self.disk_info['type'] = 'cdrom | '
self._test_libvirt_volume_driver_disk_info()
def test_libvirt_volume_disk_info_dev(self):
self.disk_info['dev'] = 'hdc'
self._test_libvirt_volume_driver_disk_info()
def test_libvirt_volume_disk_info_bus(self):
self.disk_info['bus'] = 'scsi'
self._test_libvirt_volume_d... |
jdufresne/staticsauce | staticsauce/commands/build.py | Python | gpl-3.0 | 3,466 | 0 | # This file is part of Static Sauce <http://github.com/jdufresne/staticsauce>.
#
# 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 ... | me, uri)
kwargs = {}
| if route.kwargs:
kwargs.update(route.kwargs)
kwargs.update(permutation)
try:
controller(static_file, **kwargs)
except AlreadyUpdatedError:
pass
else:
self.logger.info... |
potzenheimer/kotti_mb | setup.py | Python | mit | 1,275 | 0.000784 | import os
from setuptools import find_packages
from setuptools import setup
version = '1.0'
project = 'kotti_mb'
install_requires=[
'Kotti',
],
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read(... | sion=version,
description="AddOn for Kotti",
long_description=README + '\n\n' + CHANGES,
classifiers=[
"Programming Language :: Python",
"Framework :: Pyramid",
"License :: Repoze Public License",
],
keywo | rds='kotti addon',
author='Christoph Boehner',
author_email='cb@vorwaerts-werbung.de',
url='http://pypi.python.org/pypi/',
license='bsd',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=install_requires,
tests_require=[],
... |
mvidalgarcia/indico | indico/modules/networks/util.py | Python | mit | 506 | 0 | # This file is part of Indico.
# Copyright | (C) 2002 - 2019 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
def serialize_ip_network_group(group):
"""Serialize group to JSON-like object"""
return {
... | .id),
'_type': 'IPNetworkGroup'
}
|
dede67/sokoban | SokoGoodFloors.py | Python | gpl-3.0 | 5,693 | 0.026464 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import deque
import SokoMove
import Helper as hlp
class SokoGoodFloors():
# Interface:
# findGoodFloors() -> good-floor-List
def __init__(self, pgs, pgdp, zfl, pp):
self.pgs=pgs
self.pgdp=pgdp
self.zfl=zfl
self.pp=pp
self.bf=[]... | lls eine Liste von Floors machen
(dp, d)=hlp.munpack(i)
if dp not in rc:
rc.append(dp)
return(rc)
# ###########################################################
# Durchläuft rekursiv alle möglichen Box-Positionen, die
# durch Ziehen von einem GoalSquare erreicht werden können.
# Mit goo... | NICHT -wie sonst üblich- Player-Positionen) zusammen mit
# einer Pull-Richtung stehen. Somit können Floors mehrfach (bis
# zu viermal) besucht werden - mit je einer anderen Pull-Richtung.
#
# Verlängert ggf. good_floors und ändert pgdp.
def __findGoodFloorsForSingleBox(self, pgdp, pull, pp, good_floors):
... |
testmana2/test | DocumentationTools/TemplatesListsStyle.py | Python | gpl-3.0 | 7,017 | 0.00456 | # -*- coding: utf-8 -*-
# Copyright (c) 2004 - 2015 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Module implementing templates for the documentation generator (lists style).
"""
from __future__ import unicode_literals
#################################################
## Common templates for index and docu fil... |
<b>Deprecated.</b>
{{Lines}}
</p>'''
authorInfoTemplate = \
'''<p>
<i>Author(s)</i>:
{{Author | s}}
</p>'''
seeListTemplate = \
'''<dl>
<dt><b>See Also:</b></dt>
{{Links}}
</dl>'''
seeListEntryTemplate = \
'''<dd>
{{Link}}
</dd>'''
seeLinkTemplate = '''<a style="color:{LinkColor}" {{Link}}'''
sinceInfoTemplate = \
'''<p>
<b>since</b> {{Info}}
</p>'''
#################################
## Templates for index ... |
verilylifesciences/analysis-py-utils | verily/query_kit/__init__.py | Python | apache-2.0 | 637 | 0 | # Copyright 2019 Verily Life Sciences Inc. All Right | s 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 agreed to in writing, software
# distri... | 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.
"""Package marker file."""
|
surabujin/libpy | libpy/test/test_shadow.py | Python | mit | 1,664 | 0 | # -*- coding:utf-8 -*-
import mock
import pytest
import libpy
import libpy.shadow
class TestShadow(object):
def test(self):
proxy = libpy.shadow.Shadow(ShadowTarget())
assert isinstance(proxy, libpy.shadow.Shadow)
assert proxy.a == mock.sentinel.proxy_target_a
assert proxy.b == ... |
assert proxy.b == mock.sentinel.proxy_target_b
delattr(proxy, 'b')
with pytest.raises(AttributeError):
_ = proxy.b
def test_update(self):
target = S | hadowTarget()
proxy = libpy.shadow.Shadow(target)
assert proxy.a == mock.sentinel.proxy_target_a
target.a = 'new_value_for_a'
assert proxy.a == mock.sentinel.proxy_target_a
delattr(proxy, 'a')
assert proxy.a == 'new_value_for_a'
def test_override(self):
pro... |
zachcp/qiime | tests/test_distance_matrix_from_mapping.py | Python | gpl-2.0 | 8,329 | 0.002641 | #!/usr/bin/env python
# File created on 27 Sep 2011
from __future__ import division
__author__ = "Antonio Gonzalez Pena"
__copyright__ = "Copyright 2011, The QIIME Project"
__credits__ = [
"Antonio Gonzalez Pena",
"Andrew J. King",
"Michael S. Robeson",
]
__license__ = "GPL"
__version__ = "1.9.1-dev"
__mai... |
7718017.604,
6626434.332,
6626434.332,
9890271.864,
9779697.476,
111693.865,
0.0,
9890271.864,
9890271.864],
[7154900.607,
5877643.846,
7154900.607,
... | , 5877643.846, 7154900.607, 7154900.607, 0.0, 110574.389, 10001965.729, 9890271.864, 0.0, 0.0]])
res_out = calculate_dist_vincenty(self.latitu |
squarebracket/star | scheduler/tests/schedule_generator_tests.py | Python | gpl-2.0 | 3,829 | 0.000522 | from django.utils.unittest.case import TestCase
from scheduler.models import ScheduleGenerator
from uni_info.models import Semester, Course
class ScheduleGeneratorTest(TestCase):
"""
Test class for schedule generator, try different courses
"""
fixtures = ['/scheduler/fixtures/initial_data.json']
... | tor(course_list, self.fall_2013_semester)
result = generator.generate_schedules()
self.assertIsNotNone(result)
self | .assertEqual(4, len(result))
def test_should_not_generate_schedule_for_3_course_conflict(self):
"""
Test generator with three conflicting courses
"""
soen341 = [s for s in Course.objects.all() if
s.course_letters == 'SOEN' and
s.course_numbers =... |
gusaul/gigsblog | urls/main.py | Python | mit | 683 | 0.011713 | from django.conf.urls import patterns, include, url
fro | m django.contrib import admin
import urls
from apps.blog import views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'gigsblog.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
# url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.Index.as_view(), name='index'),
u... | s.Login.as_view(), name='login'),
url(r'^logout', 'django.contrib.auth.views.logout',{'next_page':'/'}, name='logout'),
url(r'^post/', include('urls.blog', namespace='post')),
url(r'^admin/', include('urls.admin')),
)
|
mmgen/mmgen | mmgen/wallet/brain.py | Python | gpl-3.0 | 1,905 | 0.026247 | #!/usr/bin/env python3
#
# mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
# Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
# Licensed under the GNU General Public License, Version 3:
# https://www.gnu.org/licenses
# Public project repositories:
# https://github.com/mmgen/mmgen
# http... | t_bw_params(self):
# already checked
a = opt.brain_params.split(',')
return int(a[0]),a[1]
def _deformat(self):
self.brainpasswd = ' '.join(self.fmt_data.split())
return True
def _decrypt(self):
d = self.ssdata
if opt.brain_params:
"""
Don't set opt.seed_len! When using multiple wallets, BW see... | t seed length of {yellow(str(Seed.dfl_len))} bits\n'
+ 'If this is not what you want, use the --seed-len option' )
self._get_hash_preset()
bw_seed_len = opt.seed_len or Seed.dfl_len
qmsg_r('Hashing brainwallet data. Please wait...')
# Use buflen arg of scrypt.hash() to get seed of desired length
seed ... |
wubr2000/googleads-python-lib | examples/dfa/v1_20/create_campaign.py | Python | apache-2.0 | 2,699 | 0.004817 | #!/usr/bin/python
#
# Copyright 2014 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 b... | landing_page_name
}
default_landing_page_id = campaig | n_service.saveLandingPage(
default_landing_page)['id']
# Construct and save the campaign.
campaign = {
'name': campaign_name,
'advertiserId': advertiser_id,
'defaultLandingPageId': default_landing_page_id,
'archived': 'false',
'startDate': start_date,
'endDate': end_date
... |
brodeau/barakuda | python/exec/orca_mesh_mask_to_bitmap.py | Python | gpl-2.0 | 842 | 0.011876 | #!/usr/bin/env python
# B a r a K u d a
#
# L. Brodeau, 2017]
import sys
import numpy as nmp
from PIL import Image
import string
import os
from netCDF4 import Dataset
narg = len(sys.argv)
if narg != 2:
print 'Usage: '+sys.argv[0]+' <mesh_mask>'; sys.exit(0)
cf_mm = sys.argv[1]
cf_bmp = string.repl... | ave(cf_bmp)
print ' *** Im | age '+cf_bmp+' saved!\n'
|
lunarca/fngrpt | models/BaseModels.py | Python | apache-2.0 | 1,637 | 0.001833 | # -*- coding: utf-8 -*-
'''
Created on Mar 12, 2012
@author: moloch
Copyright 2012
Licensed under the Apache License, Version 2.0 (the "Lice | nse");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
| http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing ... |
vim-IDE/MatchTagAlways | python/mta_core.py | Python | gpl-3.0 | 8,519 | 0.024416 | #!/usr/bin/env python
#
# Copyright (C) 2012 Strahinja Val Markovic <val@markovic.io>
#
# This file is part of MatchTagAlways.
#
# MatchTagAlways 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 versio... | .name == closing_tag.name:
return opening_tag, closing_tag
current_of | fset = opening_tag.start_offset
def AdaptCursorOffsetIfNeeded( sanitized_html, cursor_offset ):
"""The cursor offset needs to be adapted if it is inside a tag.
If the cursor is inside an opening tag, it will be moved to the index of the
character just past the '>'. If it's inside the closing tag, it will be mov... |
lang-uk/lang.org.ua | languk/corpus/mongodb.py | Python | mit | 4,932 | 0.002636 | from pymongo import MongoClient
from pymongo.collection import Collection
from pymongo.errors import AutoReconnect
from django.conf import settings
from types import FunctionType
import functools
import time
__all__ = ("connection", "connections", "db", "get_db")
"""
Goals:
* To provide a clean universal handler fo... | attr__(self, func):
old = getattr(self._collection, func)
if type(old) is FunctionType:
return with_reconnect(old)
return old
def __repr__(self):
return "<Coll | ectionWrapper %s>" % self._collection.__repr__()
def __str__(self):
return "<CollectionWrapper %s>" % self._collection.__str__()
class DatabaseWrapper(object):
def __init__(self, database):
self._database = database
def __getattr__(self, func):
old = getattr(self._database, func)... |
tommo/gii | support/waf/waflib/Tools/kde4.py | Python | mit | 2,732 | 0.031845 | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2006-2010 (ita)
"""
Support for the KDE4 libraries and msgfmt
"""
import os, sys, re
from waflib import Options, TaskGen, Task, Utils
from waflib.TaskGen import feature, after_method
@feature('msgfmt')
def apply_msgfmt(self):
"""
Process all languages to creat... | dencies.cmake' % prefix
try: os.stat(fname)
except OSError:
fname = '%s/share/kde4/apps/cmake/modules/KDELibsDependencies.cmake' % prefix
try: os.stat(fname)
except OSError: self.fatal('could not open %s' % fname)
try:
txt = Utils.readf(fname)
except (OSError, IOError):
self.fatal('could not read %s' % f... | dall(txt)
for (_, key, val) in found:
#print key, val
self.env[key] = val
# well well, i could just write an interpreter for cmake files
self.env['LIB_KDECORE']= ['kdecore']
self.env['LIB_KDEUI'] = ['kdeui']
self.env['LIB_KIO'] = ['kio']
self.env['LIB_KHTML'] = ['khtml']
self.env['LIB_KPARTS'] = ['kpa... |
andresailer/DIRAC | Core/Workflow/WorkflowReader.py | Python | gpl-3.0 | 4,858 | 0.01832 | """
This is a comment
"""
#try: # this part to import as part of the DIRAC framework
import xml.sax
from xml.sax.handler import ContentHandler
from DIRAC.Core.Workflow.Parameter import *
from DIRAC.Core.Workflow.Module import *
from DIRAC.Core.Workflow.Step import *
from DIRAC.Core.Workflow.Workflow import Workf... | t == None: #if root not defined by constractor
self.root = Workflow()
self.stack.append(self.root)
elif name == "StepDefinition":
obj = StepDefinition("TemporaryXMLObject_StepDefinition")
if self.root == None: # in case we are saving Step only
self.root = obj
self.stack.appe... | uleDefinition":
obj = ModuleDefinition("TemporaryXMLObject_ModuleDefinition")
if self.root == None: # in case we are saving Module only
self.root = obj
self.stack.append(obj)
elif name == "ModuleInstance":
obj = ModuleInstance("TemporaryXMLObject_ModuleInstance")
self.stack.ap... |
Fillll/reddit2telegram | reddit2telegram/channels/~inactive/r_getmotivated/app.py | Python | mit | 147 | 0.006803 | #encoding:utf-8
subreddi | t = 'getmotivated'
t_channel = '@r_getmotivated'
def send_post(submission, r2t):
| return r2t.send_simple(submission)
|
LegNeato/buck | scripts/rulekey_diff2_test.py | Python | apache-2.0 | 11,981 | 0.001335 | import unittest
from contextlib import contextmanager
from StringIO import StringIO
from | rulekey_diff2 import *
@contextmanager
def captured_output():
new_out, new_err = StringIO(), StringIO()
old_out, old_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = new_out, new_err
yield sys.stdout, sys.stderr
finally:
sys.stdout, sys | .stderr = old_out, old_err
class MockFile(object):
def __init__(self, lines):
self._index = -1
self._lines = lines
def readline(self):
self._index += 1
return self._lines[self._index]
def readlines(self):
return self._lines
def __iter__(self):
return ... |
sgraham/nope | tools/perf/page_sets/pathological_mobile_sites.py | Python | bsd-3-clause | 1,806 | 0.002769 | # Copyright 2015 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.
from telemetry.page import page as page_module
from telemetry.page import page_set as page_set_module
class PathologicalMobileSitesPage(page_module.Page):
... | l, page_set):
super(PathologicalMobileSitesPage, self).__init__(
url=url, page_set=page_set, credentials_path='data/credentials.json')
self.user_agent_type = 'mobile'
self.archive_data_file = 'data/pathological_mobile_sites.json'
def RunPageInteractions(self, action_runner):
interaction = act... | eInteraction(
'ScrollAction', is_smooth=True)
action_runner.ScrollPage()
interaction.End()
class PathologicalMobileSitesPageSet(page_set_module.PageSet):
"""Pathologically bad and janky sites on mobile."""
def __init__(self):
super(PathologicalMobileSitesPageSet, self).__init__(
user... |
thekot/cam_to_webm | modules/tar_to_webm_compressor.py | Python | mit | 2,578 | 0.003491 | import os
import shutil
import logging
import tarfile
import tempfile
import subprocess
from threading import Thread
class TarToWebmCompressor(object):
@staticmethod
def compress(filename):
thread = Thread(target=TarToWebmCompressor._compress, args=(filename,))
thread.start()
@staticmetho... | e.mkdtemp()
try:
| tar = tarfile.open(filename, "r|")
tar.extractall(tmp_dir)
tar.close()
except:
logging.exception("Failed extract %s file" % (filename,))
os.rmdir(tmp_dir)
return
# compress images into web movie
vopts = "-c:v libvpx -quality ... |
lunzhy/PyShanbay | tests/ui_test.py | Python | mit | 2,044 | 0.000978 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'Lunzhy'
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from pyshanbay.shanbay import VisitShanbay
from pyshanbay import page_parser as parser
from gui.ui_main import UIMainWidget
class MainForm(QWidget):
def __init__(self):
s... | ion)
self.table.verticalHeader().setResizeMode(QHeaderView.Fixed)
self.table.itemClicked.connect(self.show_selected)
return
def set_data(s | elf, members_data):
self.table.setColumnCount(2)
self.table.setRowCount(len(members_data))
for row_index, member in enumerate(members_data):
new_item = QTableWidgetItem(member['nickname'])
self.table.setItem(row_index, 0, new_item)
new_item = QTableWidgetItem... |
valohai/valohai-cli | valohai_cli/commands/yaml/pipeline.py | Python | mit | 2,212 | 0.000452 | from typing import List
import click
from valohai.internals.pipeline import get_pipeline_from_source
from valohai.yaml import config_to_yaml
from valohai_yaml.objs.config import Config
from valohai_cli.ctx import get_project
from valohai_cli.exceptions import ConfigurationError
from valohai_cli.messages import error,... | f"See the full traceback below."
)
raise
merged_config = old_config.merge_with(new_config)
if old_config.serialize() != merged_config.serialize():
with open(yaml_filename, "w") as out_file:
out_file.write(config_to_yaml(merged_config))
... | ect: Project) -> Config:
try:
return project.get_config()
except FileNotFoundError as fnfe:
valohai_yaml_name = project.get_config_filename()
raise ConfigurationError(
f"Did not find {valohai_yaml_name}. "
f"Can't create a pipeline without preconfigured steps."
... |
alquerci/pip | tests/unit/test_index.py | Python | mit | 1,950 | 0.001538 | import os
from pip.backwardcompat import u | rllib
from tests.lib.path import Path
from pip.index import package_to_requirement, HTMLPage
from pip.index import PackageFinder, Link, INSTALLED_VERSION
from tests.lib import path_to_url
from string import ascii_lowercase
from mock import patch
def test_package_name_should_be_converted_to_requirement():
"""
... | translates a name like Foo-1.2 to Foo==1.3
"""
assert package_to_requirement('Foo-1.2') == 'Foo==1.2'
assert package_to_requirement('Foo-dev') == 'Foo==dev'
assert package_to_requirement('Foo') == 'Foo'
def test_html_page_should_be_able_to_scrap_rel_links():
"""
Test scraping page looking for... |
noiselabs/box-linux-sync | src/noiselabs/box/output.py | Python | lgpl-3.0 | 6,736 | 0.011435 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This file is part of box-linux-sync.
#
# Copyright (C) 2013 Vítor Brandão <noisebleed@noiselabs.org>
#
# box-linux-sync 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... | names."""
codes = {}
"""Maps attribute name to ansi code."""
esc_seq = "\x1b["
codes["normal"] = esc_seq + "0m"
codes['reset'] = esc_seq + "39;49;00m"
codes["bold"] = esc_seq + "01m"
codes | ["faint"] = esc_seq + "02m"
codes["standout"] = esc_seq + "03m"
codes["underline"] = esc_seq + "04m"
codes["blink"] = esc_seq + "05m"
codes["overline"] = esc_seq + "06m"
codes["reverse"] = esc_seq + "07m"
codes["invisible"] = esc_seq + "08m"
codes["no-attr"] = esc_seq + "22... |
joopert/home-assistant | tests/helpers/test_config_validation.py | Python | apache-2.0 | 26,925 | 0.000409 | """Test config validators."""
from datetime import date, datetime, timedelta
import enum
import os
from socket import _GLOBAL_DEFAULT_TIMEOUT
from unittest.mock import Mock, patch
import uuid
import pytest
import voluptuous as vol
import homeassistant
import homeassistant.helpers.config_validation as cv
def test_bo... | ssert schema(["sensor.light", "SENSOR.demo"]) == ["sensor.light", "sensor.demo"]
def test_ensure_list_csv():
"""Test ensure_list_csv."""
schema = vol.Schema(cv.ens | ure_list_csv)
options = (None, 12, [], ["string"], "string1,string2")
for value in options:
schema(value)
assert schema("string1, string2 ") == ["string1", "string2"]
def test_event_schema():
"""Test event_schema validation."""
options = (
{},
None,
{"event_data":... |
seancug/python-example | fatiando-0.2/test/test_gravmag_euler.py | Python | gpl-2.0 | 2,686 | 0.004468 | from __future__ import division
import numpy as np
from fatiando.gravmag.euler import Classic, ExpandingWindow, MovingWindow
from fatiando.gravmag import sphere, fourier
from fatiando.mesher import Sphere
from fatiando import utils, gridder
model = None
xp, yp, zp = None, None, None
inc, dec = None, None
struct_ind = ... | base = 10
field = utils.nt2si(sphere.tf(x, y, z, [model], inc, dec)) + base
x | deriv = fourier.derivx(x, y, field, shape)
yderiv = fourier.derivy(x, y, field, shape)
zderiv = fourier.derivz(x, y, field, shape)
def test_euler_classic_sphere_mag():
"gravmag.euler.Classic for sphere model and magnetic data"
euler = Classic(x, y, z, field, xderiv, yderiv, zderiv, struct_ind).fit()
... |
zxtstarry/src | book/rsf/rsf/gui/gui.py | Python | gpl-2.0 | 1,270 | 0.028346 | #!/usr/bin/env python
import os, sys
try:
from Tkinter import *
except:
sys.stderr.write('Please install Tkinter!\n\n')
sys.exit(1)
root = Tk()
root.title('Wavelet Demo')
wtype = StringVar()
wtype.set('b')
type_frame = Frame(root,relief=SUNKEN,borderwidth=2)
type_frame.pack(side=TOP,fill=X)
Label(type_... | .pack(side=RIGHT)
Label(pclip_frame,text='Threshold\nPercentile').pack(side=RIGHT,anchor=SE)
frame = Frame(root)
frame.pack(side=TOP,fill=X)
quit = Button(frame,text='Quit',background='red',command=sys.exit)
quit.pack(side=RIGHT)
def scons():
'Get parameters from GUI and pass them to SCons'
os.system ('scons... | Run',background='yellow',command=scons)
cycle.pack()
root.mainloop()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.