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
failys/CAIRIS
cairis/test/test_AssetAPI.py
Python
apache-2.0
13,606
0.006688
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may...
url = '/api/assets/name/%s' % quote(self.new_asset.theName) upd_asset = self.new_asset upd_asset.theName = 'Test2' upd_asset_dict = self.new_asset_dict upd_asset_dict['object'] = upd_asset upd_asset_body = jsonpickle.encode(upd_asset_dict) self.logger.info('[%s]
JSON data: %s', method, upd_asset_body) rv = self.app.put(url, content_type='application/json', data=upd_asset_body) if (sys.version_info > (3,)): putResponse = rv.data.decode('utf-8') else: putResponse = rv.data self.logger.debug('[%s] Response data: %s', method, putResponse) json_res...
alefnula/perart
src/tea/qt/__init__.py
Python
gpl-3.0
139
0.014388
__author__ = 'Vikt
or Kerkez <alefnula@gmail.com>' __date__ = '18 February 2
010' __copyright__ = 'Copyright (c) 2010 Viktor Kerkez'
fedora-infra/github2fedmsg
tools/fake-github-post.py
Python
agpl-3.0
5,286
0.022891
# This file is a part of github2fedmsg, a pubsubhubbub to zeromq bridge. # Copyright (C) 2014, Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # Li...
lphbean/statatat/commit/ffedad58abec3cbf6546daedfb4249db5b994203" }, { "ad
ded": [], "author": { "email": "rbean@redhat.com", "name": "Ralph Bean", "username": "ralphbean" }, "committer": { "email": "rbean@redhat.com", "name": "Ralph Bean", "username": "ralphbean" }, "distinct": Tr...
Edraak/edraak-platform
common/djangoapps/course_modes/views.py
Python
agpl-3.0
15,273
0.002815
""" Views for the course_m
ode module """ import decimal import json import urllib import waffle from babel.dates import format_datetime from django.contrib.auth.decorators import login_required from django.urls import reverse from django.db import transaction from django.http import HttpResponse, HttpResponseBadRequest from django.shortcu
ts import redirect from django.utils.decorators import method_decorator from django.utils.translation import ugettext as _ from django.utils.translation import get_language, to_locale from django.views.generic.base import View from ipware.ip import get_ip from opaque_keys.edx.keys import CourseKey from six import text_...
sutartmelson/girder
tests/cases/access_test.py
Python
apache-2.0
12,062
0.000332
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright 2014 Kitware 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 cop...
() # Public access endpoints do not need to be a Resource subclass method, # they can be a regular function accesstest = server.root.api.v1.accesstest accesstest.route('GET', ('default_function_access', ), defaultFunctionHandler) a
ccesstest.route('GET', ('admin_function_access', ), adminFunctionHandler) accesstest.route('GET', ('user_function_access', ), userFunctionHandler) accesstest.route('GET', ('public_function_access', ), publicFunctionHandler) accesstest.route('GET', ('test_loadmodel_plain', ':id'), plainF...
furbrain/tested
tested/itypes/__init__.py
Python
gpl-3.0
361
0.00277
from .basics import InferredType, UnknownType, TypeSet, is_inferred_type from .compound import InferredIterator, is_inferred_sequence from .builtins import get_global_scope, get_type_by_name, get_
type_by_value, create_list, create_set, create_dict, create_tuple from .functions import FunctionType from .classes import ClassType from .mod
ules import ModuleType
erinspace/scrapi
scrapi/processing/postgres.py
Python
apache-2.0
6,903
0.002608
from __future__ import absolute_import import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.api.settings") import copy import logging import django from api.webview.models import HarvesterResponse, Document, Version from scrapi import events from scrapi.util import json_without_bytes from scrapi.linter i...
sponse.ok) @property
def content(self): if isinstance(self.response.content, memoryview): return self.response.content.tobytes() if isinstance(self.response.content, bytes): return self.response.content return str(self.response.content) @property def encoding(self): return...
hsoft/hscommon
sqlite.py
Python
bsd-3-clause
4,304
0.006738
# Created By: Virgil Dupras # Created On: 2007/05/19 # 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/gpl...
self._query(COMMIT) def execute(self, sql, values=()): if not self._run: return None # Connection closed res
ult = self._query((sql, values)) if isinstance(result, Exception): raise result return result def rollback(self): if not self._run: return None # Connection closed self._query(ROLLBACK) def run(self): # The whole chdir thing is because sq...
vicky2135/lucious
src/oscar/apps/dashboard/orders/views.py
Python
bsd-3-clause
33,150
0
import datetime from collections import OrderedDict from decimal import Decimal as D from decimal import InvalidOperation from django.conf import settings from django.contrib import messages from django.core.exceptions import ObjectDoesNotExist from django.core.urlresolvers import reverse from django.db.models import ...
view for order statistics. Supports the permission-based dashboard. """ template_name = 'dashboard/orders/statistics.html' form_class = Ord
erStatsForm def get(self, request, *args, **kwargs): return self.post(request, *args, **kwargs) def form_valid(self, form): ctx = self.get_context_data(form=form, filters=form.get_filters()) return self.render_to_response(ctx) def get_form_kwarg...
HowManyOliversAreThere/led_strip
main.py
Python
mit
343
0.002915
from ledstripcontroller import LedStripController
from encoder import Encoder def main(): enc = Encoder(pin_clk=13, pin_dt=12, pin_mode=Pin.PULL_UP, min_val=40, max_val=1020, clicks=1, accel=5) enc._value = 1020 controller = LedStripController(enc) controller
.run() if __name__ == '__main__': main()
yugangw-msft/azure-cli
src/azure-cli/azure/cli/command_modules/acs/tests/hybrid_2020_09_01/test_loadbalancer.py
Python
mit
3,509
0.00228
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
rProfileOutboundIPs( public_i_ps="public_i_ps" ) profile.outbound_ip_prefixes = ManagedClusterLoadBalancerProfileOutboundIPPrefixes( public_ip_prefixes="public_ip_prefixes" ) p = loadbalancer.configure_load_balancer_profile( managed_outbound_ip_count,...
profile, lb_models, ) self.assertEqual(p.managed_outbound_i_ps.count, 5) self.assertEqual(p.outbound_i_ps, None) self.assertEqual(p.outbound_ip_prefixes, None) self.assertEqual(p.allocated_outbound_ports, 80) self.assertEqual(p.idle_timeout_in_mi...
mvaled/sentry
src/sentry/api/bases/monitor.py
Python
bsd-3-clause
1,422
0.001406
from __future__ import absolute_import from sentry import features from sentry.api.base import Endpoint from sentry.api.exceptions import ResourceDoesNotExist from sentry.api.bases.project import ProjectPermission from sentry.models import Monitor, Project, ProjectStatus from sentry.utils.sdk import configure_scope ...
return self.respond(status=400)
if not features.has("organizations:monitors", project.organization, actor=request.user): raise ResourceDoesNotExist self.check_object_permissions(request, project) with configure_scope() as scope: scope.set_tag("organization", project.organization_id) scope.set_ta...
cgwalters/hawkey
tests/python/tests/test_goal.py
Python
lgpl-2.1
6,817
0.001174
# # Copyright (C) 2012-2013 Red Hat, Inc. # # Licensed under the GNU Lesser General Public License Version 2.1 # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of th...
obsoleted = goal.obsoleted_by_package(reinstall) self.
assertItemsEqual(list(map(str, obsoleted)), ("fool-1-3.noarch", )) def test_req(self): goal = hawkey.Goal(self.sack) self.assertEqual(goal.req_length(), 0) self.assertFalse(goal.req_has_erase()) sltr = hawkey.Selector(self.sack).set(name="jay") goal.erase(select=sltr) ...
leifos/boxes
treasure-houses/asg/game.py
Python
mit
4,228
0.007569
__author__ = 'leif' from asg.abstract_search_game import ABSGame from asg.asg_generator import RandomYieldGenerator, TestHighYieldGenerator, ConstantLinearYieldGenerator, TestYieldGenerator, CueGenerator, GainBasedCueGenerator from asg.asg_generator import TestLowYieldGenerator, RandGainBasedCueGenerator from models im...
store_game_incache(id, game) def end_game(user, game): update_user_profile(user, game) new_high = update_high_scores(user, game) update_game_experiment(game) return new_high def update_user_profile(user, game): up = user.get_profile() up.last_tim
e_played = datetime.datetime.now() up.no_games_played = up.no_games_played + 1 up.no_queries_issued = up.no_queries_issued + game.queries_issued up.no_docs_assessed = up.no_docs_assessed + game.docs_assessed up.total_points = up.total_points + game.points up.total_tokens = up.total_tokens + game.tok...
Hernanarce/pelisalacarta
python/main-classic/servers/vimpleru.py
Python
gpl-3.0
2,480
0.003227
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Conector para vimple.ru # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import re from core import config from core imp...
TALL).findall(data) for match in matches: titulo = "[vimpleru]" url = "http://player.vimple.ru/iframe/" + match if url not in encontrados:
logger.info(" url=" + url) devuelve.append([titulo, url, 'vimpleru']) encontrados.add(url) else: logger.info(" url duplicada=" + url) return devuelve
xiaoyongaa/ALL
python基础2周/购物车作业改进.py
Python
apache-2.0
38,553
0.013623
#默认选择是0.家电类下面的所有商品 #选择你要购买的物品,要结算请在物品编号最后加j,例如(1,2,3,j) 不结算的就不加j #购买多件商品按,(逗号)隔开,例如1,2,3,j(结算),不结算(1,2,3) import os shoop1=[ ("家电类"), ("衣服类"), ("手机类"), ("车类"), ] jiadianshoop=[ ("电冰箱",20000), ("彩电",2000), ("洗衣机",400), ("脸盆",30), ("牙刷",50) ] flag=True long=len(jiadianshoop) def f(): ...
if i<long: #print("你输入的商品号合法") jiage=jiadianshoop[i][1] if jiage<=cash: print("你的余额足够") cash=cash-jiage ...
n.write(wuping+"\n") n.close() cash=str(cash) #转换成str形势保存 q=open("cash"+user,"w") #账户的余额历史保存 ...
platzi/django-avanzado
userprofiles/forms.py
Python
gpl-2.0
148
0
from django import forms class LoginForm(forms.Form)
: username = forms.Cha
rField() password = forms.CharField(widget=forms.PasswordInput)
Tony-Wang/YaYaNLP
yaya/common/nature.py
Python
apache-2.0
4,416
0.000297
# coding=utf-8 from yaya.common.enum import Enum __author__ = 'tony' # 词性 NATURE = Enum( "bg", # u"区别语素", "mg", # u
"数语素", "nl", # u"名词性惯用语", "nx", # u"字母专名", "qg", # u"量词语素", "ud", # u"助词", "uj", # u"助词", "uz", # u"
着", "ug", # u"过", "ul", # u"连词", "uv", # u"连词", "yg", # u"语气语素", "zg", # u"状态词", "n", # u"名词", "nr", # u"人名", "nrj", # u"日语人名", "nrf", # u"音译人名", "nr1", # u"复姓", "nr2", # u"蒙古姓名", "ns", # u"地名", "nsf", # u"音译地名", "nt", # u"机构团体名", "ntc", # u"公司名...
Kefkius/electrum-frc
lib/network_proxy.py
Python
gpl-3.0
7,346
0.004764
#!/usr/bin/env python # # Electrum - lightweight Bitcoin client # Copyright (C) 2014 Thomas Voegtlin # # 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 y...
if msg_id is not None: with self.lock: method, params, callback = s
elf.unanswered_requests.pop(msg_id) else: method = response.get('method') params = response.get('params') with self.lock: for k,v in self.subscriptions.items(): if (method, params) in v: callback = k ...
alex-slynko/tile-generator
sample/src/app/app.py
Python
apache-2.0
3,178
0.021082
#!/usr/bin/env python # tile-generator # # Copyright (c) 2015-Present Pivotal Software, 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...
', "name": "first-plan", "description": "A first, free, service plan" },{ "id": name + '-plan-2-id', "name": "second-plan", "description": "A second, for-a-fee, service plan", "free": False }], "dashboard_client": { "id": name + '-client-id', "secret": "secret", "redirect_uri": route('/...
n 'hello' @app.route("/env") def environment(): return json.dumps(dict(os.environ), indent=4) @app.route("/proxy") def proxy(): url = request.args.get('url') if url is None: return json.dumps('expected url parameter'), 404 response = requests.get(url, verify=False) return response.content, response.status_code...
litex-hub/pythondata-cpu-blackparrot
pythondata_cpu_blackparrot/system_verilog/black-parrot/external/basejump_stl/testing/bsg_cache/regression_v2/test_atomic4.py
Python
bsd-3-clause
1,146
0.02007
import sys import random from test_base import * class TestAtomic1(TestBase): def generate(self): self.clear_tag() for iteration in range(10): for n in range(10000): tag = random.randint(0,9) index = random.randint(0,1) block_offset = random.randint(0,self.block_size_in_word...
elif op == 4: self.send_amoxor_w(taddr) elif op == 5: self.send_amoand_w(taddr) elif op == 6: self.send_amoor_w(taddr) e
lif op == 7: self.send_amomin_w(taddr) elif op == 8: self.send_amomax_w(taddr) elif op == 9: self.send_amominu_w(taddr) elif op == 10: self.send_amomaxu_w(taddr) # done self.tg.done() # main() if __name__ == "__main__": t = TestAtomic1() t.g...
bitforks/freetype-py
freetype/ft_enums/ft_load_targets.py
Python
bsd-3-clause
2,226
0.003594
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # # FreeType high-level python API - Copyright 2011-2015 Nicolas P. Rougier # Distributed under the terms of the new BSD license. # # ----------------------------------------------------------------------------- ""...
MONO' : _FT_LOAD_TARGET_(FT_RENDER_MODE_MONO), 'FT_LOAD_TARGET_LCD' : _FT_LOAD_TARGET_(FT_R
ENDER_MODE_LCD), 'FT_LOAD_TARGET_LCD_V' : _FT_LOAD_TARGET_(FT_RENDER_MODE_LCD_V) } globals().update(FT_LOAD_TARGETS) #def FT_LOAD_TARGET_MODE(x): # return (x >> 16) & 15
barbagroup/pygbe
pygbe/matrixfree.py
Python
bsd-3-clause
59,346
0.002915
""" Matrix free formulation of the matrix vector product in the GMRES. """ import numpy from numpy import pi from pygbe.tree.FMMutils import computeIndices, precomputeTerms from pygbe.tree.direct import coulomb_direct from pygbe.projection import project, project_Kt, get_phir, get_phir_gpu from pygbe.classes import P...
complexobj(surf.XinV): #if surf.XinK.dtype == complex or surf.XinV.dtype == complex: K_lyr_Re, V_lyr_Re = project(surf.XinK.real, surf.XinV.real, LorY, su
rf, surf, K_diag, V_diag, IorE, s, param, ind0, timing, kernel) K_lyr_Im, V_lyr_Im = project(surf.XinK.imag, surf.XinV.imag, LorY, surf, surf, K_diag, V_diag, IorE, s, param, ind0, timing, kernel) K_lyr = K_lyr_Re + 1j * K_lyr_Im V_lyr...
gviejo/ThalamusPhysio
python/main_pop_corr_fig.py
Python
gpl-3.0
9,516
0.032787
import numpy as np import pandas as pd # from matplotlib.pyplot import plot,show,draw import scipy.io from functions import * from pylab import * from sklearn.decomposition import PCA import _pickle as cPickle import time import os, sys import ipyparallel import matplotlib.cm as cm from scipy.optimize import curve_fi...
'nucleus']), data = 0), 'rem': pd.D
ataFrame(index = bins[0:-1], columns = np.unique(space['nucleus']), data = 0), 'rip': pd.DataFrame(index = bins[0:-1], columns = np.unique(space['nucleus']), data = 0) } } lambdaa = { 'session': { 'wak': pd.DataFrame(index = files, columns = ['a', 'b', 'c', 'mx', 'my'], data = 0), 'rem': pd.DataFrame(index =...
gdestuynder/MozDef
mozdef_util/mozdef_util/utilities/is_cef.py
Python
mpl-2.0
824
0.002427
def isCEF(aDict): # determine if this is a CEF event # could be an event posted to the /cef http endpoint if 'endpoint' in aDict and aDict['endpoint'] == 'cef': return True # maybe it snuck in some other way # check some key CEF indicators (t
he header fields) if 'fields' in aDict and isinstance(aDict['fields'], dict): lowerKeys = [s.lower() for s in aDict['fields'].keys()] if 'devicevendor' in lowerKeys and 'deviceproduct' in lowerKeys and 'deviceversion' in lowerKeys: return True if 'details'
in aDict and isinstance(aDict['details'], dict): lowerKeys = [s.lower() for s in aDict['details'].keys()] if 'devicevendor' in lowerKeys and 'deviceproduct' in lowerKeys and 'deviceversion' in lowerKeys: return True return False
queria/my-tempest
tempest/api/volume/test_volumes_snapshots.py
Python
apache-2.0
8,340
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
('details' if with_detail else '', key) self.assertEqual(params[key], snap[key], msg) @test.attr(type='gate') @test.services('compute') def test_snapshot_create_with_volume_in_use(self): # Create a snapshot when volume status is in
-use # Create a test instance server_name = data_utils.rand_name('instance-') resp, server = self.servers_client.create_server(server_name, self.image_ref, self.flavor_ref) s...
Arno-Nymous/pyload
module/plugins/hooks/ExternalScripts.py
Python
gpl-3.0
9,817
0.000611
# -*- coding: utf-8 -*- import os import subprocess from ..internal.Addon import Addon from ..internal.misc import Expose, encode class ExternalScripts(Addon): __name__ = "ExternalScripts" __type__ = "hook" __version__ = "0.73" __status__ = "testing" __config__ = [("activated", "bool", "Activat...
e_extracted': "archive_extracted", 'package_extract_failed': "package_extract_failed", 'package_extracted': "package_extracted", 'all_archives_extracted': "all_archives_extracted", 'all_archives_processed': "all_arch...
ask() # @NOTE: Initial scan so dont miss `pyload_start` scripts if any def activate(self): self.pyload_start() def make_folders(self): for folder in self.folders: dir = os.path.join("scripts", folder) if os.path.isdir(dir): continue try: ...
regisf/yablog
plugins/contact/__init__.py
Python
bsd-3-clause
3,704
0.00567
# -*- coding: utf-8 -*- # YaBlog # (c) Regis FLORET # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the fol...
init__(self, context): self.context = context self.js = None self.templ = None def install_javascript(self): """ Install javascript to handling contact form """ if self.js is None: self.js = open(os.path.join(CURRENT_PATH, 'contact.js'), 'r').read() ...
elf): """ Display the contact form """ if self.templ is None: self.templ = open(os.path.join(CURRENT_PATH,"contact.html"), "r").read() return Template(self.templ).render(self.context) def create(context): """ Create the plugin - Entry Point """ return Contact(context) d...
chicm/carvana
car-segment/net/imagenet/pyramidnet1.py
Python
apache-2.0
6,020
0.00814
import os import math import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable def make_conv_bn_relu(in_channels, out_channels, kernel_size=3, stride=1, padding=1, groups=1): return [ nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride,...
hNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() def make_layer(self, block, planes, blocks, stride=1): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( nn.Conv2d(self.inplanes,...
on, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes * block.expansion), ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion for i in range(1, blocks): layers.appen...
maxprais/psoriassist
novartis/receivers.py
Python
mit
1,422
0.000703
from django.dispatch import receiver from account.signals import password_changed from account.signals import user_sign_up_attempt, user_signed_up from account.signals import user_login_attempt, user_logged_in from psoriassist.views import Index from psoriassist import views from pinax.eventlog.models import log ...
*kwargs): log( user=kwargs.get("user"), action="USER_SIGNED_UP", extra={} )
not-na/fritzctl
fritzctl/dynapi.py
Python
gpl-2.0
2,360
0.014831
#!/usr/bin/env python # -*- coding: utf-8 -*- # # dynapi.py # # Copyright 2016-2020 fritzctl Contributors> # # 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 Lice...
methods for calling actions. This class will generate API methods based on the device definitions found in the session. You may pass arguments to the auto-generated methods via
keyword arguments only. If you need to pass an argument that is not a valid Python identifier, use this trick: ``api.MyAPIMethod(**{"Some-Strange-Name":"Value"})``\ . :param Session session: :py:class:`Session()` object used for requests :param str urn: Service Type URN to be wrapped by this inst...
nzlosh/st2
st2common/st2common/util/db.py
Python
apache-2.0
1,690
0.002959
# Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme Networks, 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 ...
age governing permissions and # limitations under the License. from __future__ import absolute_import import mongoengine import six from collections.abc import Mapping def mongodb_to_python_types(value): # Convert MongoDB BaseDict and BaseList types to python dict and list types. if isinstance(value, mongo...
alue, mongoengine.base.datastructures.BaseList): value = list(value) # Convert collections.Mapping types to python dict otherwise YAQL/Jinja related # functions used to convert JSON/YAML objects/strings will errored. This is caused # by the PR StackStorm/orquesta#191 which converts dict to collectio...
andycavatorta/oratio
Roles/avl-settings/mcp3008Adafruit_test.py
Python
mit
1,191
0.005038
# Simple example of reading the MCP3008 analog input channels and printing # them all out. # Author: Tony DiCola # License: Public Domain import time # Import SPI library (for hardware SPI) and MCP3008 library. import Adafruit_GPIO.SPI as SPI import Adafruit_MCP3008 # Software SPI configuration: CLK = 18 MISO = 23 ...
.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) print('Reading MCP3008 values, press Ctrl-C to quit...') # Print nice channel column headers. print('| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*range(8))) print('-' * 57) # Main program loop. for i in range(10) : # Read all the ...
c function will get the value of the specified channel (0-7). values[i] = mcp.read_adc(i) # Print the ADC values. print('| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*values)) # Pause for half a second. time.sleep(0.5)
CityGrid/twonicorn
twonicornweb/views/exception.py
Python
apache-2.0
471
0.002123
from pyramid.view import view_config from twonicornweb.views import (
site_layout, get_user, ) @view_config(context=Exception, renderer='twonicornweb:templates/exception.pt') def error(exc, request): request.response.status_int = 500 page_title = 'Internal Server Error'
user = get_user(request) return {'layout': site_layout(), 'page_title': page_title, 'user': user, 'error': exc.message }
SDM-OS/playlist
doc/sphinx/conf.py
Python
gpl-3.0
9,469
0.007709
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # CherryMusic documentation build configuration file, created by # sphinx-quickstart on Fri Mar 1 23:32:37 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # ...
plit into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML ...
will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'c...
globby/Jagl
jaglk.py
Python
gpl-2.0
3,653
0.033945
import re from jaglt import * from jaglf import * ''' Regexes ''' JRE_Num = [ re.compile(r"[0-8]+o"), #Octal re.compile(r"[\dA-F]+x"), #Hex re.compile(r"(?:-?\d+(?:\.(?:\d+)?)?|\.\d+|-?\d+)e-?\d+"), #Scientific re.compile(r"-?\d+(?:\.(?:\d+)?)?|-?\.\d+"), #Decimal ] JRE_Str = re.compile(r...
ner[s:e])) elif clss == JFunc: arr.append(JFunc(inner[s:e])) elif clss in [JArray, JBlock]: arr.append(makeArray(inner[s:e])) elif clss == str: arr.ap
pend(JArray(map(lambda x: JNum(ord(x)), inner[s+1:e-1]))) elif clss == EStr: arr.append(JArray(map(lambda x: JNum(ord(x)), inner[s+1:e-1].decode("string_escape")))) if string[0] == "(": return JArray(arr) return JBlock(arr) ''' Tokenizer ''' def tokenize(string): string = preprocess(string) il = classifyLev...
lesserwhirls/scipy-cwt
scipy/special/tests/test_orthogonal_eval.py
Python
bsd-3-clause
4,547
0.004179
import numpy as np from numpy.testing import assert_ import scipy.special.orthogonal as orth from scipy.special._testutils import FuncData def test_eval_chebyt(): n = np.arange(0, 10000, 7) x = 2*np.random.rand() - 1 v1 = np.cos(n*np.arccos(x)) v2 = orth.eval_chebyt(n, x) assert_(np.allclose(v1, ...
polyfunc(*p): p = (p[0].astype(int),) + p[1:] return func(*p) olderr = np.seterr(all='raise') try: ds = FuncData(polyfunc, dataset, range(len(param_ranges)+2), -1, rtol=rtol) ds.check() finally: np.seterr(**ol...
param_ranges=[(-0.99, 10), (-0.99, 10)], x_range=[-1, 1], rtol=1e-5) def test_sh_jacobi(self): self.check_poly(orth.eval_sh_jacobi, orth.sh_jacobi, param_ranges=[(1, 10), (0, 1)], x_range=[0, 1], rtol=1e-5) def test_gegenbauer(self...
xfornesa/BDDByExample-python
src/MyTaste/in_memory_repository.py
Python
mit
41
0
cla
ss InMemoryRepository(list): pas
s
ryanvarley/adsbibtex
adsbibtex/adsbibtex_cache.py
Python
mit
505
0.00198
""" simple cache based on shelve """ import shelve import
time def load_cache(cache_file): cache = shelve.open(cache_file) return cache def read_key(cache, key, ttl): """ Reads value from cache, if doesnt exist or is
older than ttl, raises KeyError """ bibtex, timestamp = cache[key] if (timestamp + ttl) < time.time(): raise KeyError("Cached entry is too old") else: return bibtex def save_key(cache, key, value): cache[key] = (value, time.time())
eoprede/ansible_fortios_api
fortios/fortios_api_firewall_ippool.py
Python
gpl-3.0
2,902
0.001723
#!/usr/bin/python # # Ansible module for managing Fortigate devices via API # (c) 2017, Will Wagner <willwagner602@gmail.com> and Eugene Opredelennov <eoprede@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print...
_api_args = { 'endpoint': 'cmdb/firewall/ippool', 'list_identifier': 'ippool', 'object_identifier': 'name', 'default_i
gnore_params': [] } def main(): forti_api = API(system_global_api_args) forti_api.apply_configuration_to_endpoint() if __name__ == "__main__": main()
ypkang/Dato-Core
src/unity/python/graphlab/extensions.py
Python
agpl-3.0
27,795
0.003778
""" This module hosts all the extension functions and classes created via SDK. The function :py:func:`ext_import` is used to import a toolkit module (shared library) into the workspace. The shared library can be directly imported from a remote source, e.g. http, s3, or hdfs. The imported module will be under namespace...
re passed kwargs : dictionary The keyword arguments that were passed """ # scan for all the arguments in args num_args_got = len(args) + len(kwargs
) num_args_required = len(arguments) if num_args_got != num_args_required: raise TypeError("Expecting " + str(num_args_required) + " arguments, got " + str(num_args_got)) ## fill the dict first with the regular args argument_dict = {} for i in range(len(args)): argument_dict[argumen...
ResearchSoftwareInstitute/MyHPOM
ref_ts/models.py
Python
bsd-3-clause
6,208
0.002255
from django.db import models from django.contrib.contenttypes.fields import GenericRelation from mezzanine.pages.page_processors import processor_for from hs_core.models import BaseResource, ResourceManager, resource_processor,\ CoreMetaData, AbstractMetaDataElement from lxml import etree ...
esResource.objects.filter(object_id=self.id).first() @classmethod def g
et_supported_element_names(cls): # get the names of all core metadata elements elements = super(RefTSMetadata, cls).get_supported_element_names() # add the name of any additional element to the list elements.append('Method') elements.append('QualityControlLevel') elements...
rob-nn/python
first_book/playing_cards.py
Python
gpl-2.0
1,659
0.027125
# Playing Cards # Demonstrates combining objects class Card(object): """A playing card.""" RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"] SUITS = ["c", "d", "h", "s"] def __init__(self, rank, suit): self.rank = rank self.suit = suit def __str__(self): rep = self.rank + self.sui...
d4 = Card(rank = "4", suit="c") card5 = Card(rank = "5", suit="c") print("\nPrinting the rest of the objects individuall
y:") print(card2) print(card3) print(card4) print(card5) my_hand = Hand() print("\nPrintting my hand before I add any cards:") print(my_hand) my_hand.add(card1) my_hand.add(card2) my_hand.add(card3) my_hand.add(card4) my_hand.add(card5) print("\nPrinting my hand after adding 5 cards:") print(my_hand) your_hand = H...
nagyistoce/devide
modules/vtk_basic/vtkHierarchicalDataSetGeometryFilter.py
Python
bsd-3-clause
536
0.001866
# class generated by DeVIDE::createDeVID
EModuleFromVTKObject from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase import vtk class vtkHiera
rchicalDataSetGeometryFilter(SimpleVTKClassModuleBase): def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkHierarchicalDataSetGeometryFilter(), 'Processing.', ('vtkMultiGroupDataSet',), ('vtkPolyData',), replace...
webmasterraj/FogOrNot
flask/lib/python2.7/site-packages/pandas/tseries/tests/test_plotting.py
Python
gpl-2.0
41,563
0.001227
from datetime import datetime, timedelta, date, time import nose from pandas.compat import lrange, zip import numpy as np from numpy.testing.decorators import slow from numpy.testing import assert_array_equal from pandas import Index, Series, DataFrame from pandas.tseries.index import date_range, bdate_range from p...
), 2) @slow def test_frame_inferred(self): # inferred freq import matplotlib.pyplot as plt idx = date_range('1/1/1987', freq='MS', periods=100) idx = DatetimeIndex(idx.values, freq=None) df
= DataFrame(np.random.randn(len(idx), 3), index=idx) _check_plot_works(df.plot) # axes freq idx = idx[0:40].union(idx[45:99]) df2 = DataFrame(np.random.randn(len(idx), 3), index=idx) _check_plot_works(df2.plot) # N > 1 idx = date_range('2008-1-1 00:15:00', freq...
benjyw/pants
src/python/pants/backend/python/typecheck/mypy/rules.py
Python
apache-2.0
13,525
0.002884
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import itertools import logging from collections import defaultdict from dataclasses import dataclass from typing import Iterable, Optional, Tuple from pants.backend.python.target_types i...
r_constraints import InterpreterConstraints from pants.backend.python.util_rules.pex import ( Pex, PexRequest, PexRequirements, VenvPex, VenvPexProcess, ) from pants.backend.python.util_rules.pex_from_targets import PexFromTargetsRequest from pants.backend.python.util_rules.python_sources import ( ...
m pants.core.goals.typecheck import TypecheckRequest, TypecheckResult, TypecheckResults from pants.core.util_rules.config_files import ConfigFiles, ConfigFilesRequest from pants.core.util_rules.source_files import SourceFiles, SourceFilesRequest from pants.engine.addresses import Addresses, UnparsedAddressInputs from p...
azaroma/ipc-classifier
classifier/models.py
Python
mit
303
0.0033
"""Provide data models""" class PatentDocument(object):
"""A model for a IPC patent""" def __init__(self, number, title, ipcs, l
ist_ipc, abstract): self.number = number self.title = title self.ipcs = ipcs self.list_ipc = list_ipc self.abstract = abstract
tjcsl/cslbot
cslbot/commands/translate.py
Python
gpl-2.0
1,669
0.001797
# Copyright (C) 2013-2018 Samuel Damashek, Peter Foley, James Forcier, Srijay Kasturi, Reed Koser, Christopher Reffett, and Tris Wilson # # 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 v...
Y; 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 not, write to the Free Software # Foundation, Inc., 51 Franklin Stree...
om ..helpers import arguments from ..helpers.command import Command from ..helpers.textutils import gen_translate @Command(['translate', 'trans'], ['config']) def cmd(send, msg, args): """Translate something. Syntax: {command} [--from <language code>] [--to <language code>] <text> See https://cloud.googl...
Edraak/edx-platform
lms/envs/edraak_devstack.py
Python
agpl-3.0
179
0
from .devstack import * from .edraak_common import * # WARNING: D
on't just add/delete settings from here. Make sur
e the settings are # reflected in `cms/envs/edraak_devstack.py`
BayanGroup/sentry
tests/sentry/api/endpoints/test_project_member_index.py
Python
bsd-3-clause
1,222
0
from __future__ import absolute_import from django.core.urlresolvers import reverse from sentry.testutils import APITestCase class ProjectMemberIndexTest(APITestCase): def test_simple(self): user_1 = self.create_user('foo@localhost', username='foo') user_2 = self.create_user('bar@localhost', use...
org = self.create_organization(owner=user_1) team = self.create_team(organization=org, slug='baz') project_1 = self.create_project(team=team, slug='foo') self.create_project(team=team, slug='bar') org.member_set.create(user=user_2, has_global_access=True) org.member_set....
url = reverse('sentry-api-0-project-member-index', kwargs={ 'organization_slug': project_1.organization.slug, 'project_slug': project_1.slug, }) response = self.client.get(url) assert response.status_code == 200 assert len(response.data) == 2 assert resp...
plotly/plotly.py
packages/python/plotly/plotly/validators/sunburst/marker/_cmax.py
Python
mit
468
0.002137
import _plotly_utils.basevalidators class CmaxValidator(_plotly_utils.basevalidators.NumberValidator): def __init__(self, plotly_name="cmax", pa
rent_name="sunburst.marker", **kwargs): super(CmaxValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type",
"plot"), implied_edits=kwargs.pop("implied_edits", {"cauto": False}), **kwargs )
maxkoryukov/route4me-python-sdk
route4me/sdk/_internals/net.py
Python
isc
7,427
0.031641
# -*- coding: utf-8 -*- """ Internal module, provides HTTP access to API """ import re import requests import platform import logging from ..errors import Route4MeNetworkError from ..errors import Route4MeApiError from ..version import VERSION_STRING from ..version import RELEASE_STRING from ..version import BUILD ...
else '' # remove leading slashes from path path = re.sub(r'^/
+', '', path) url = 'https://{subdomain}{base_host}/{path}'.format( subdomain=subdomain, base_host=self.base_host, path=path, ) return url def __read_response(self, req): res = self.__handle_net_exceptions(req) if res.status_code >= 300: # TODO: need to parse text! msg = res.text # TODO...
subhrm/google-code-jam-solutions
solutions/2010/Q/A/A.py
Python
mit
344
0.005814
def solve(n, k): if k == 0: return 0 if (k >= n) and ((k+1) %(2**n) == 0): return 1 return 0 if __name__ == "__main__": t = int(input()) f
or ti in range(1, t + 1): n, k = map(int, input().split(" ")) sol = "ON" if solve(n, k) == 1 else "OFF" print("Case #{0}: {1}
".format(ti, sol))
Urinx/Machine_Learning
Logistic-Regression/LogisticRegression.py
Python
gpl-2.0
2,429
0.074516
#! /usr/bin/env python # coding:utf-8 from numpy import * from matplotlib.pyplot import * from scipy.optimize import fmin_bfgs class ML(): def __init__(self,x=[],y=[]): self.X=x self.Y=y self.Theta=[] self.Alpha=0.01 self.Iterations=1500 def load(self,fname,d=','): data=loadtxt(fname,delimiter=d) sel...
x=[],y=[]): self.Lambda=1 self.data_Norm=0 self.mu=0 self.sigma=0 def sigmoid(self,z)
: return 1/(1+exp(-z)) ######################################################### # CostFunc: # sigmoid() has a problem for that when z is too huge the # return result is equal to 1. which cause log(h) to nan # Solution: # normalize the feature first ######################################################### d...
lily4630/test_4
envs.py
Python
gpl-3.0
14,078
0.006038
import cv2 from gym.spaces.box import Box import numpy as np import numpy import gym from gym import spaces import logging import universe from universe import vectorized from universe.wrappers import BlockingReset, GymCoreAction, EpisodeID, Unvectorize, Vectorize, Vision, Logger from universe import spaces as vnc_spac...
self.env_id = env_id import envs_li self.env_li = envs_li
.env_li(env_id=env_id, task=task, subject=subject, summary_writer=summary_writer) '''observation_space''' from config import observation_space self.observation_space = observation_spac...
plotly/python-api
packages/python/plotly/plotly/validators/volume/colorbar/_y.py
Python
mit
509
0.001965
import _plotly_utils.basevalidators class YValidator(_plotly_utils.basevalidators.NumberValidator): def __init__(self, plotly_name="y", parent_name="volume.colorbar", **kwargs): super(YValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_typ...
)
antoinecarme/pyaf
tests/model_control/detailed/transf_Logit/model_control_one_enabled_Logit_LinearTrend_NoCycle_NoAR.py
Python
bsd-3-clause
149
0.04698
import tests.model_control.test_ozone_custom_models_enabled as testmod testmod.build_model( ['Logit'] , ['LinearTrend'] , ['NoCycle']
, ['NoAR'] )
;
viggates/nova
nova/virt/hardware.py
Python
apache-2.0
27,991
0.000286
# Copyright 2014 Red Hat, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
us cpuset_ids -= cpuset_reject_ids return cpuset_ids def format_cpu_spec(cpuset, allow_ranges=True): """Format a libvirt CPU range specification. :param cpuset: set
(or list) of CPU indexes Format a set/list of CPU indexes as a libvirt CPU range specification. It allow_ranges is true, it will try to detect continuous ranges of CPUs, otherwise it will just list each CPU index explicitly. :returns: a formatted CPU range string """ # We attempt to dete...
usc-isi-i2/etk
etk/timeseries/annotation/utility.py
Python
mit
566
0.003534
row_key = "Rows" column_key = "Cols" special_keywords = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec', 'january'
, 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december', 'q1', 'q2', 'q3', 'q4'] # cell classes text_cell = "text" nu
mber_cell = "number" empty_cell = "empty" date_cell = "date" blank_cell = "blank" row_orientation = "row" column_orientation = "col" def data_to_string(data): return str(data)
nuclear-wizard/moose
python/mms/test/mms_spatial.py
Python
lgpl-2.1
973
0.012333
#!/usr/bin/env python3 #* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICEN
SE for details #* https://www.gnu.org/licenses/lgpl-2.1.html import mms df1 = mms.run_spatial('mms_spatial.i', 4, console=False, executable='../../../test') df2 = mms.run_spatial('mms_spatial.i', 4, 'Mesh/second_order=true', 'Variables/u/order=SECOND', console=False, executable='../../../test') ...
er', marker='o', markersize=8) fig.plot(df2, label='2nd Order', marker='o', markersize=8) fig.save('mms_spatial.png') #TESTING (leave this comment, it is used in doco to remove the following from a demo) df1.to_csv('mms_spatial_first.csv') df2.to_csv('mms_spatial_second.csv')
agry/NGECore2
scripts/mobiles/dathomir/purbole.py
Python
lgpl-3.0
1,377
0.027596
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate() mobil...
.setHideAmount(8) mobileTemplate.setBoneType("Animal Bones") mobileTemplate.setBoneAmount(8) mobileTemplate.setSocialGroup("purbole") mobileTemplate.se
tAssistRange(12) mobileTemplate.setStalker(True) mobileTemplate.setOptionsBitmask(Options.AGGRESSIVE | Options.ATTACKABLE) templates = Vector() templates.add('object/mobile/shared_purbole.iff') mobileTemplate.setTemplates(templates) attacks = Vector() attacks.add('bm_bite_4') attacks.add('bm_defensive_4') ...
seanmavley/DjangoHoldit
Placeholder/wsgi.py
Python
mit
397
0.002519
""" WSGI
config for Placeholder project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Placeholder.settings") from django.core.w...
lication()
Talifero/Main
sortfiles.py
Python
gpl-2.0
6,925
0.01325
#!/usr/bin/python # -*- coding: utf-8 -*- """ Created on Thu Apr 4 2013 @author: talifero Module for imeges template convertation. Tamplates: HD 1920x1080 720p 1280x720 PAL 720x380 300 300x120 """ import os, locale from PIL import Image import pyexiv2 locale.setlocale(lo...
ьному имени файла добавляется имя шаблона. Расширение записывается в нижнем регистре независимо от регистра оригинала. Например файл с именем DSC096
40.JPG после команды pic_res.py hd получит имя DSC09640HD.jpg. Версия от 6 января 2014 года. talifero@gmail.com ''' #_____________________________________________
thomazs/geraldo
site/newsite/django_1_0/django/core/cache/backends/base.py
Python
lgpl-3.0
2,316
0.001295
"Base Cache class." from django.core.exceptions import ImproperlyConfigured class InvalidCacheBackendError(ImproperlyConfigured): pass class BaseCache(object): def __init__(self, params): timeout = params.get('timeout', 300) try: timeout = int(timeout) except (ValueError, ...
Fetch a given key from the cache. If the key does not exist, return default, which itself defaults to None. """ raise NotImplementedError def set(self, key, value, timeout=None): """ Set a value in the cache. If timeout is given, that timeout will be used fo...
mplementedError def delete(self, key): """ Delete a key from the cache, failing silently. """ raise NotImplementedError def get_many(self, keys): """ Fetch a bunch of keys from the cache. For certain backends (memcached, pgsql) this can be *much* faster ...
khaleeque-ansari/Online-Coding-
ProjectEulerCode/prob81.py
Python
apache-2.0
723
0.030429
#Reading input file matrix = [] with open("prob81_input.txt", 'rt') as f: for line in f: matrix.append(map(int, line.strip().split(','))) #print matrix[0][0] #print matrix[1][0] m_len = len(matrix) #print m_len for k i
n range(m_len-2,-1,-1): matrix[m_len-1][k] += matrix[m_len-1][k+1] for l in range(m_len-2,-1,-1): matrix[l][m_len-1] += matrix[l+1][m_len-1] #print matrix for i in range(m_len-2,-1,-1): for j in range(m_len-2,-1,-1): if matrix[i+1][j] < matrix[i][j+1]: ...
[j+1] print matrix[0][0]
johnctitus/troposphere
troposphere/efs.py
Python
bsd-2-clause
1,223
0
from . import AWSObject, Tags from .validators import boolean Bursting = 'bursting' Provisioned = 'provisioned' def throughput_mode_validator(mode): valid_modes = [Bursting, Provisioned] if mode not in valid_modes:
raise ValueError( 'ThroughputMode must be one of: "%s"' % (', '.join(valid_modes)) ) return mode def provisioned_throughput_validator(throughput): if throughput < 0.0: raise ValueError( 'ProvisionedThroughputInMibps must be greater than or equal to 0.0' ) ...
olean, False), 'FileSystemTags': (Tags, False), 'KmsKeyId': (basestring, False), 'PerformanceMode': (basestring, False), 'ProvisionedThroughputInMibps': (float, False), 'ThroughputMode': (throughput_mode_validator, False), } class MountTarget(AWSObject): resource_type =...
trysrv/GitHub.Uploader.CuiCmd.201706231541
IssueCreate.py
Python
cc0-1.0
4,273
0.007362
#!/usr/bin/python3 #!python3 #encoding:utf-8 import sys import os.path import subprocess import configparser import argparse import web.service.github.api.v3.AuthenticationsCreator import web.service.github.api.v3.Client import database.src.Database import cui.uploader.Main import web.log.Log import database.src.contri...
'URL: {0}'.format(self.__args.homepage)) def __create_issue(self): auth_creator = web.service.github.api.v3.AuthenticationsCreator.AuthenticationsCreator(self.__db, self.__args.username) authentications = auth_creator.Create() client = web.service.github.api.v3.Client.Cl
ient(self.__db, authentications, self.__args) title = self.__args.issues[0] body = None # 1行目タイトル, 2行目空行, 3行目以降本文。 if 1 < len(self.__args.issues): body = '\n'.join(self.__args.issues[1:]) return client.Issues.create(title, body=body) # main = cui.uploader.Main.Main(self._...
svschannak/openslides-templates-pmv
openslides/__init__.py
Python
gpl-2.0
1,492
0.002681
import socket import os import sys from os.path import realpath, join, dirname try: from mercurial import ui as hgui from mercurial.localrepo import localrepository from mercurial.node import short as shorthex from mercurial.error import RepoError nomercurial = False except: nomercurial = True ...
nts) ctx = repository['.'] if ctx.tags() and ctx.tags() != ['tip']: revision = ' '.join(ctx.tags()) else: revision = '%(num)s:%(id)s' % { 'num': ctx.rev(), 'id': shorthex(ctx.node()) } except TypeError: revision = 'unknown' exce...
do never timeout and as such we have blocking workers. # Socket timeouts are set globally within the whole application. # The value *must* be a floating point value. socket.setdefaulttimeout(10.0) return revision if not nomercurial: OPENSLIDES_REVISION = _bootstrap() del _bootstrap
EvgeniyBlinov/estimate
estimate/__init__.py
Python
mit
133
0
from __futu
re__ import (absolute_import, division, print_function) __metaclass__ = type from .es
timate_parser import EstimateParser
Warvito/pydeeplearn
code/lib/deepbelief.py
Python
bsd-3-clause
38,804
0.010205
import numpy as np import restrictedBoltzmannMachine as rbm from batchtrainer import * from ac
tivationfunctions import * from common import * from debug import * from trainingoptions import * import theano from theano import tensor as T from theano.tensor.shared_randomstreams import RandomStreams theanoFloat = theano.config.floatX DEBUG = False class Mi
niBatchTrainer(BatchTrainer): def __init__(self, input, inputLabels, nrLayers, initialWeights, initialBiases, activationFunction, classificationActivationFunction, visibleDropout, hiddenDropout, adversarial_training, adversarial_epsilon, adversarial_coefficient): self...
boneyao/sentry
src/sentry/web/frontend/accounts.py
Python
bsd-3-clause
10,117
0.001581
""" sentry.web.frontend.accounts ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import import itertools from django.contrib import messages from django.contrib.auth import login as lo...
Ugly way of doing this, but Django requires the backend be set user = authenticate( username=user.username, password=form.cleaned_data['password'], )
login_user(request, user) password_hash.delete() return login_redirect(request) else: form = ChangePasswordRecoverForm() context = { 'form': form, } return render_to_response(tpl, context, request) @csrf_protect @never_cache @logi...
zblz/naima
src/naima/version.py
Python
bsd-3-clause
241
0
from pkg_resources import D
istributionNotFound, get_distribution def get_version(): try: return get_distribution("naima").version except DistributionNotFound: # package is not installed return "U
NINSTALLED"
lovasb/django-smart-forms
smartforms/models.py
Python
mit
1,341
0.002983
from django.db import transaction from .base import BaseForm from .composite import CompositeForm from .formset import FormSet class BaseModelForm(BaseForm): def save(self, commit=True): retval = [] with transaction.atomic(): for form in self._subforms: if form.empty_p...
j in self._subforms): raise ValueError('all form instance must have save method (model form)') class ModelFormSet(FormSet, BaseModelForm): def __init__(self, data=None, files=None, form_class=None, repeat=1, instances=None, **kwar
gs): if not hasattr(form_class, 'save'): raise ValueError('form_class must be ModelForm') self._instances = instances super(ModelFormSet, self).__init__(data, files, form_class, repeat, **kwargs) def _update_kwargs(self, kwargs, i): try: kwargs['instance'] = ...
point97/hapifis
server/apps/survey/migrations/0077_auto__chg_field_response_ts__chg_field_respondant_review_status__chg_f.py
Python
gpl-3.0
17,288
0.007693
# -*- 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): # Changing field 'Response.ts' db.alter_column(u'survey_response', 'ts', self.gf('django.db.models.fields.D...
estion']", 'null': 'True', 'blank': 'True'}) }, u'survey.gridanswer': { 'Meta': {'object_name': 'GridAnswer'}, 'answer_numb
er': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}), 'answer_text': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'col_label': ('django.db.models.fields.TextField', [], {'null': 'True', 'b...
otsaloma/gaupol
gaupol/actions/__init__.py
Python
gpl-3.0
1,223
0.0139
# -*- coding: utf-8 -*- # Copyright (C) 2007 Osmo Salomaa # # This program is free software: you can redistribute it and/or modify # it under the terms of the GN
U General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTI...
ense # along with this program. If not, see <http://www.gnu.org/licenses/>. """User-activatable actions for :class:`gaupol.Application`.""" from gaupol.actions.audio import * # noqa from gaupol.actions.edit import * # noqa from gaupol.actions.file import * # noqa from gaupol.actions.help import * # noq...
todaychi/hue
desktop/core/ext-py/django-axes-1.5.0/axes/signals.py
Python
apache-2.0
919
0
from django.dispatch import receiver from django.dispatch import Signal from django.utils.timezone import now from django.contrib.auth.signals import user_logged_out from django.core.exceptions import ObjectDoesNotExist from axes.models import AccessLog user_locked_out = Signal(providing_args=['request', 'username',...
username = user.get_username() except AttributeError: # Django < 1.5 username = user.username access_logs = AccessLog.objects.filter( username=username, logout_time__isnull=True, ).order_by('-attempt_time') if access_logs: access_log = access_logs[0] ...
access_log.logout_time = now() access_log.save()
nil0x42/phpsploit
src/core/tunnel/compat_handler.py
Python
gpl-3.0
837
0
"""Bac
kwards compatible tunnel handler for phpsploit v1 backdoors, aka: <?php eval(base64_decode($_POST[%%PASSKEY%%])); ?> """ __all__ = ["Request_V1_x"] from . import handler from .
exceptions import BuildError class Request_V1_x(handler.Request): def __init__(self): """Force default method to POST, because only this one was supported on phpsploit v1 versions. """ super().__init__() self.default_method = "POST" def build_forwarder(self, method, d...
akintolga/superdesk-core
apps/publish/enqueue/__init__.py
Python
agpl-3.0
5,186
0.003664
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014, 2015, 2016 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license ...
shed_items() if len(items) > 0: enqueue_items(items) finally: unlock(lock_name, '') def enqueue_item(published_item):
""" Creates the corresponding entries in the publish queue for the given item """ published_item_id = ObjectId(published_item[config.ID_FIELD]) published_service = get_resource_service(PUBLISHED) archive_service = get_resource_service(ARCHIVE) published_update = {QUEUE_STATE: PUBLISH_STATE.IN_P...
jorik041/CrackMapExec
cme/modules/mimipenguin.py
Python
bsd-2-clause
1,518
0.003294
from cme.helpers.bash import get_script from sys import exit class CMEModule: ''' Runs the Mimipenguin script to dump credentials from memory Module by @byt3bl33d3r ''' name = 'mimipenguin' description = 'Dumps cleartext credentials in memory' supported_protocols = ['ssh'] opse...
) self.script = scripts[self.script_choice] def on_admin_login(self, context, connection): if self.script_choice == 'BASH': stdin, stdout, stderr = connection.conn.exec_command("bash -") elif self.script_choice == 'PYTHON': stdin, stdout, stderr = connection.conn.ex...
on2 -") stdin.write("{}\n".format(self.script)) stdin.channel.shutdown_write() context.log.success('Executed command') for line in stdout: context.log.highlight(line.strip())
ella/ella-newman
test_newman/settings/config.py
Python
bsd-3-clause
1,071
0.00747
from tempfile import gettempdir from os.path import join ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DEBUG = False TEMPLATE_DEBUG = DEBUG DISABLE_CACHE_TEMPLATE = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': join(gettempdir(), 'ella...
REDIS = {'db': 15} TIME_ZONE = 'Europe/Prague' LANGUAGE_CODE = 'en-us' SITE_ID = 1 # Make this unique, and don't share it with anybody. SECRET_KEY = '88b-01f^x4lh$-s5-hdccnicekg07)niir2g6)93!0#k(=mfv$' # TODO: Fix logging # init logger #LOGGING_CONFIG_FILE = join(dirname(testbed.__file__), 'settings', 'logger.ini'...
ance(LOGGING_CONFIG_FILE, basestring) and isfile(LOGGING_CONFIG_FILE): # logging.config.fileConfig(LOGGING_CONFIG_FILE) # we want to reset whole cache in test # until we do that, don't use cache CACHE_BACKEND = 'dummy://' NEWMAN_MEDIA_PREFIX = '/static/newman_media/' USE_PRIORITIES = True TAG_LISTINGS_PAGINATE_B...
tinloaf/home-assistant
homeassistant/components/fan/mqtt.py
Python
apache-2.0
14,941
0
""" Support for MQTT fans. For more details about this platform, please refer to the documentation https://home-assistant.io/components/fan.mqtt/ """ import logging import voluptuous as vol from homeassistant.core import callback from homeassistant.components import fan, mqtt from homeassistant.const import ( CO...
_entry(hass, config_entry, async_add_entities): """Set up MQTT fan dynamically through MQTT discovery.""" async def async_discover(discovery_payload): """Discover and add a MQTT fan.""" config = PLATFORM_SCHEMA(discovery_payload) await _async_setup_entity(hass, config, async_add_entities...
async_dispatcher_connect( hass, MQTT_DISCOVERY_NEW.format(fan.DOMAIN, 'mqtt'), async_discover) async def _async_setup_entity(hass, config, async_add_entities, discovery_hash=None): """Set up the MQTT fan.""" async_add_entities([MqttFan( config, ...
hammerlab/pepdata
test/test_amino_acids.py
Python
apache-2.0
918
0.004357
from nose.tools import eq_ from pepdata.amino_acid_alphabet import ( canonical_amino_acids, canonical_amino_acid_letters, extended_amino_acids, extended_amino_acid_letters, ) def test_canonical_amino_acids(): assert len(canonical_amino_acids) == 20 de
f test_canonical_amino_acids_letters():
assert len(canonical_amino_acid_letters) == 20 assert "X" not in canonical_amino_acid_letters expected_letters = [aa.letter for aa in canonical_amino_acids] eq_(expected_letters, canonical_amino_acid_letters) def test_extended_amino_acids(): assert len(extended_amino_acids) > 20 def test_extended_...
vmrob/sbsmanip
sbsmanip/cubeblocks.py
Python
mit
1,449
0.00207
import xml.etree.ElementTree as ET class Definition(object): def __init__(self, definition_root): self._definition_root = definition_root def type_name(self): type_id = self._definition_root.find('Id').find('TypeId') subtype_id = self._definition_root.find('Id').find('SubtypeId') ...
setter def build_time(self, value): time = self._definition_root.find('BuildTimeSeconds') if time is None: time = ET.SubElement(self._definition_root, 'BuildTimeSeconds') time.text = str(value) @property def disassembly_ratio(self): ratio = self._definit
ion_root.find('DisassembleRatio') if ratio is not None: return float(ratio.text) return 1 @disassembly_ratio.setter def disassembly_ratio(self, value): ratio = self._definition_root.find('DisassembleRatio') if ratio is None: ratio = ET.SubElement(self._de...
ibm-security-intelligence/api-samples
reference_data/04_Tables.py
Python
apache-2.0
12,660
0.000079
#!/usr/bin/env python3 # In this example we will see how data in reference tables can be manipulated # using the REST API. # Our company has a multilevel security authorization architecture. Users # are assigned an authorization server that they must use to log in to the # network. Once inside the general network, som...
{ 'outer_key': 'calvin', 'inner_key': 'Authorization_Server_IP_General', 'value': '7.12.15.12' }, { 'outer_key': 'calvin', 'inner_key': 'Last_Secure_Login', 'value': str(current_time) ...
'value': '7.12.14.85' }, { 'outer_key': 'mill', 'inner_key': 'Authorization_Server_IP_Secure', 'value': '6.3.9.12' }, { 'outer_key': 'mill', 'inner_key': 'Authorization_Server_PORT...
rickdberg/mgmodel
ratedownanalytic.py
Python
mit
19,209
0.004685
# -*- coding: utf-8 -*- """ Created on Wed Sep 23 16:31:33 2015 @author: Rick Berg, University of Washington, School of Oceanography !!!!!!!!!!Need to add in way to deal with upper boundary condition, saving output, input process. Is this following the sediment package rather than depth? Script for modeling reaction...
nplen-4] befconc1 = concpad[1:conplen-3] aftconc1 = concpad[3:conplen-1] aftconc2 = concpad[4:conplen] concsmooth = np.column_stack((conc[:,0], (befconc2*0.06+befconc1*0.24+conc[:,1
]*0.4+aftconc1*0.24+aftconc2*0.06))) conc = concsmooth ''' # Add in the modern seawater concentration at surface and make interpolation function concfull = np.concatenate((np.array(([0],ct0)).T, conc), axis=0) concinterp = interp1d(concfull[:, 0], concfull[:, 1], kind='linear') #######################################...
phenoxim/nova
nova/objects/bandwidth_usage.py
Python
apache-2.0
3,995
0.001001
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
uid=uuid, start_period=start_period, mac=mac) @base.serialize_args @base.remotable_classmethod def get_by_instance_uuid_and_mac(cls, context, instance_uuid, mac, start_period=None, use_slave=False): db_
bw_usage = cls._db_bw_usage_get(context, uuid=instance_uuid, start_period=start_period, mac=mac, use_slave=use_slave) if db_bw_usage: return cls._from_db_object(context, cls(), db_bw_usage) @base.serialize_args @bas...
google/differentiable-atomistic-potentials
dap/tests/test_tf_chebyshev.py
Python
apache-2.0
1,352
0.004438
# Copyright 2018 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
byshev import (chebvander_py, chebvander) import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' class TestTFChebyshev(tf.test.TestCase): def test_chebvander_py(self): """Test the python implementation.""" x = np.linspace(0, 1, 11)
for deg in range(1, 49): ref = np.polynomial.chebyshev.chebvander(x, deg) Tn = chebvander_py(x, deg) self.assertTrue(np.allclose(ref, Tn)) def test_chebvander_tf(self): """Test the Tensorflow implementation.""" x = np.linspace(0, 1, 11) with self.test_session(): for deg in r...
xiaoyongaa/ALL
面向对象模块学习/模拟人生.py
Python
apache-2.0
3,617
0.025278
class main: guoji="中国" 人种="黄种人" def __init__(self,name,sex,age,work,cash,car,fang): self.name=name self.sex=sex self.age=age self.work=work self.cash=cash self.fang=fang self.car=car for key in self.cash: if key=="poor": ...
hn.cash,car=john.car,fang=john.fang) john.talk(msg) Liz.talk("Liz:john,多年不见。你现在好有钱。好土豪。我打算和你复合。。") john.talk("john:开玩笑,当初你背叛了我。选择了Peter,现在后悔了?") Liz.talk("Liz:求你再给我吃机会,我是真心要复合的。。") john.talk("你太天真了,我已经有女朋友了。。想跟我,,没门!") Liz.talk("Liz:你现在的女朋友是谁?") john.talk("john:看,就是这个,我网上订购的,终身保修,,说完。john拿手机给Liz看,是某宝的充气娃娃限量款。") Liz.tal...
"+++++++++++++end++++++++++++++++++") msg="\033[31mLiz:你现在{n}的女朋友是谁?\033[0m".format(n=john.guoji) print(msg) ''' 格式:\033[显示方式;前景色;背景色m 说明: 前景色 背景色 颜色 --------------------------------------- 30 40 黑色 31 41 红色 32 42 ...
urinieto/hier_eval
segment_tree.py
Python
gpl-3.0
51,887
0.000173
# CREATED:2013-08-13 12:02:42 by Brian McFee <brm2132@columbia.edu> ''' Evaluation criteria for structural segmentation fall into two categories: boundary annotation and structural annotation. Boundary annotation is the task of predicting the times at which structural changes occur, such as when a verse transitions to...
mpy as np import scipy.stats import scipy.sparse import scipy.misc import scipy.special import collections import warnings from mir_eval import util # For hierarchical eval import tree def validate_boundary(reference_intervals, estimated_intervals, trim): '''Checks that the input annotations to a segment boundar...
d segment times, and throws helpful errors if not. :parameters: - reference_intervals : np.ndarray, shape=(n, 2) reference segment intervals, in the format returned by :func:`mir_eval.io.load_intervals` or :func:`mir_eval.io.load_labeled_intervals`. - estima...
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/ubuntu-sso-client/ubuntu_sso/xdg_base_directory/windows.py
Python
gpl-3.0
91
0.021978
..
/../../../../../share/pyshared/ubun
tu-sso-client/ubuntu_sso/xdg_base_directory/windows.py
maxiee/MyCodes
PyQt4Learning/001_hello.py
Python
gpl-3.0
494
0.030364
import sys from PyQt4 import QtGui, QtCore class demowind(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__
(self,parent) self.setWindowTitle('Demo Window') self.setGeometry(300,300,200,200) quit=QtGui.QPushButton('Close',self) quit.setGeometry(10,10,70,40) self.connect(quit,QtCore.SIGNAL('clicked()'),QtGui.qApp,QtCore.SLOT
('quit()')) app = QtGui.QApplication(sys.argv) dw = demowind() dw.show() sys.exit(app.exec_())
SuperDARNCanada/realtimedisplay
websockets/websockify/websockify/websocketproxy.py
Python
mit
21,312
0.00488
#!/usr/bin/env python ''' A WebSocket to TCP socket proxy with support for "wss://" encryption. Copyright 2011 Joel Martin Licensed under LGPL version 3 (see docs/LICENSE.LGPL-3) You can make a cert/key with openssl using: openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem as taken from http://doc...
nection(self): if self.server.token_plugin:
(self.server.target_host, self.server.target_port) = self.get_target(self.server.token_plugin, self.path) if self.server.auth_plugin: try: self.server.auth_plugin.authenticate( headers=self.headers, target_host=self.server.target_host, ...
HelloLily/hellolily
lily/search/lily_search.py
Python
agpl-3.0
11,226
0.000891
import logging from django.conf import settings from elasticsearch_old.exceptions import RequestError from elasticutils import S from lily.accounts.models import Account from lily.contacts.models import Contact from lily.messaging.email.utils import get_shared_email_accounts from lily.search.connections_utils import ...
'last_used': hit.get('last_used') }) return hits, facets, execute.count, execute.took return hits, None, execute.count, execute.took except RequestError as e: # This can happen when the query is malformed. For example: ...
al characters. This should normally be taken # care of where the request is built (usually in Javascript), # by escaping or omitting special characters. # This may be hard to get fool proof, therefore we also # catch the exception here to prevent server errors. ...
2947721120/django-material
tests/visual/test_widget_fileinput.py
Python
bsd-3-clause
2,211
0.004975
from selenium.webdriver.common.keys import Keys from django.test.utils import override_settings from .. import test_widget_fileinput as test from . import VisualTest @override_settings(ROOT_URLCONF='tests.test_widget_fileinput') class Test(VisualTest): def test_test_default_usecase(self): self.driver.get...
l, test.Test.test_default_usecase.url)) self.assertScreenshot('form', 'fileinput_default_usecase')
def test_invalid_value(self): self.driver.get('%s%s' % (self.live_server_url, test.Test.test_invalid_value.url)) self.driver.find_element_by_css_selector("button").send_keys(Keys.RETURN) self.assertScreenshot('form', 'fileinput_missing_value_error') def test_part_group_class(self): ...
lucas2109/estruturaDados
pilha.py
Python
mit
1,546
0.003881
import unittest c
lass PilhaVaziaErro(Exception): pass class Pilha(): def __init__(self): self.lista=[] def empilhar(self,valor): self.lista.append(valor) def vazia(self): return not bool(self.lista) def topo(self): try: return self.lista[
-1] except IndexError: raise PilhaVaziaErro def desempilhar(self): if (self.lista): return self.lista.pop(-1) else: raise PilhaVaziaErro class PilhaTestes(unittest.TestCase): def test_topo_lista_vazia(self): pilha = Pilha() self.asser...
int-0/potp
src/potp/transport.py
Python
lgpl-3.0
11,848
0.00346
#!/usr/bin/env python # # Python Object Transfer: transport # import struct import select import socket import logging import threading import SocketServer logger = logging.getLogger(__name__) _DEB = logger.debug _INF = logger.info # # Factory # def get_transport(qos={}): return TCPTransport() # # URI encoding...
urns if transport is secure or not. """ return False @property def sap(self): """ Service access point. This property is used to compose endpoint string reference. """ return TransportSAP() @property def ready(self): """ On line. This property re...
turn if transport has a callback or not. Args: none. Returns: True if callback is defined. Raises: none. """ raise NotImplementedError() def bind(self, callback): """ Set server callback. Args: callback...
kayhayen/Nuitka
tests/optimizations/Attributes.py
Python
apache-2.0
1,056
0
# Copyright 2021
, Kay Hayen, mailto:kay.hayen@gmail.com # # Python test originally created or extracted from other peoples work. The # parts from me are licensed as below. It is at least Free Software where # it's copied from other people. In these cases, that will normally be # indicated. # # Licensed under the Ap...
icense 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 th...
jwlawson/tensorflow
tensorflow/python/keras/_impl/keras/layers/__init__.py
Python
apache-2.0
2,093
0.001433
# 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...
rflow.python.keras._impl.keras.layers.noise import * from tensorflow.python.keras._impl.keras.layers.normalization import * from tensorflow.python.keras._impl.keras.layers.pooling import * from tensorflow.python.keras._impl.keras.layers.recurrent import * from tensorflow.python.keras._impl.keras.layers.serialization im...
from tensorflow.python.keras._impl.keras.layers.serialization import serialize from tensorflow.python.keras._impl.keras.layers.wrappers import *
akathorn/pyrus
sceneManager/sceneManager.py
Python
gpl-2.0
4,331
0.025398
''' Created on 24/05/2009 @author: akathorn ''' import os os.environ['SDL_VIDEO_CENTERED'] = '1' import pygame from pygame.locals import * pygame.init() from fonts import * from scene import * from basicScenes import * import time import data class SceneManager(object): def __init__(self, screen_size=(800,60...
return True def nextScene(self): self.scene=self.sceneList.pop(0)(self) def updateScene(self, scene=None): if not scene: scene=self.scene self.clock.tick(self.fps) gameTime=self.clock.get_time() sceneSurface=s...
.clock.get_fps(), self.debug_text) self.renderText(debugstring, (20,1), bg=(255,255,255)) def renderText(self, text, pos=(50,50), color=(0,0,0), font=comicsans, bg=None): try: textSprite=font.render(text, 1, color) except pygame.error: return False posx=...
nens/openradar
openradar/scripts/elevation_image.py
Python
gpl-3.0
2,413
0
# -*- coding: utf-8 -*- # (c) Nelen & Schuurmans. GPL licensed, see LICENSE.rst. """ TODO Docstring. """ import argparse import logging import sys import h5py import numpy as np from PIL import Image from matplotlib import colors from matplotlib import cm from openradar import calc from openradar import config lo...
# calculate theta = calc.calculate_theta( rang=rang, elev=np.radians(elev), anth=anth, ) alt = calc.calculate_height( theta=theta, elev=np.radians(elev), anth=anth, ) which = np.ma.where( alt == alt.min(0), np.indices(alt.shape)[0],
-1, ).max(0) what = alt.min(0) # colors hue = cm.hsv(colors.Normalize(vmax=len(radars))(which), bytes=True) sat = 1 - colors.Normalize(vmax=5, clip=True)(what)[..., np.newaxis] hue[..., :3] *= sat hue[sat.mask[..., 0]] = 255 Image.fromarray(hue).save('elevation_image.png') retur...