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
aabilio/PyDownTV
Servers/tve.py
Python
gpl-3.0
6,285
0.006712
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of PyDownTV. # # PyDownTV 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) a...
("</file>"): # Contiene la URL urlVideo = sourceXML.split("<file>")[1].split("</file>")[0] elif sourceXML.find("assetDataId::") != -1: # Dar el rodeo idAsset = sourceXML.split("assetDataId::")[1].split("\"/>")[0]
urlXMLasset = "www.rtve.es/scd/CONTENTS/ASSET_DATA_VIDEO/" + idAsset[-1] \ + "/" + idAsset[-2] + "/" + idAsset[-3] \ + "/" + idAsset[-4] + "/ASSET_DATA_VIDEO-" + idAsset + ".xml" sourceAssetXML = self.__descXML(urlXMLasset) urlInSourceAss...
dhluong90/PokemonGo-Bot
pokemongo_bot/cell_workers/move_to_fort.py
Python
mit
5,477
0.003104
# -*- coding: utf-8 -*- from __future__ import unicode_literals from pokemongo_bot import inventory from pokemongo_bot.constants import Constants from pokemongo_bot.walkers.walker_factory import walker_factory from pokemongo_bot.worker_result import WorkerResult from pokemongo_bot.base_task import BaseTask from utils ...
nventory.Items.has_space_for_loot() if not has_space_for_loot and not self.ignore_item_count: self.emit_event( 'inventory_full', formatted="Inventory is full. You might want to
change your config to recycle more items if this message appears consistently." ) return has_space_for_loot or self.ignore_item_count or self.bot.softban def is_attracted(self): return (self.lure_distance > 0) def work(self): if not self.should_run(): return Wo...
f3b/blender_f3b_exporter
src/f3b_export.py
Python
gpl-3.0
48,666
0.01426
# This file is part of blender_io_f3b. blender_io_f3b 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 the hope that it will be useful, but WITHOUT # ANY WARRANTY;...
ort_all_collisionplane(scene, data, cfg) export_all_tobjects(scene, data, cfg) if hasattr
(f3b.datas_pb2.Data,"cr_emitters") : export_all_emitters(scene,data,cfg) export_all_speakers(scene, data, cfg) export_all_geometries(scene, data, cfg) export_all_materials(scene, data, cfg) export_all_lights(scene, data, cfg) export_all_skeletons(scene, data, cfg) export_all_actions(scene, data...
endlessm/chromium-browser
third_party/llvm/lldb/test/API/functionalities/breakpoint/breakpoint_command/bktptcmd.py
Python
bsd-3-clause
812
0.006158
from __future__ import print_function import side_effect def useless_function(first, second): print("I have the wrong number of arguments.") def function(frame, bp_loc, dict): side_effect.bktptcmd = "function was here" def another_function(frame, bp_loc, extra_args, d
ict): se_value = extra_args.GetValueForKey("side_effect") se_string = se_value.GetStringValue(100) side_effect.fancy = se_string def a
_third_function(frame, bp_loc, extra_args, dict): se_value = extra_args.GetValueForKey("side_effect") se_string = se_value.GetStringValue(100) side_effect.fancier = se_string def empty_extra_args(frame, bp_loc, extra_args, dict): if extra_args.IsValid(): side_effect.not_so_fancy = "Extra args s...
sramana/pysis
apps/passwords/tests/test_reset_password.py
Python
unlicense
1,236
0.004045
from djangosanetesting.cases import HttpTestCase from django.conf import settings from django.core.urlresolvers import reverse from
django.core import mail from accounts.tests import testdata class TestResetPassword(HttpTestCase): def __init__(self, *args, **kwargs): super(self.__class__, self).__init__(*args, **kwargs) self.host = 'localhost' self.port = 8000 def setUp(self): testdata.run() def test_...
}, follow=True) assert reverse('password_reset_done') in res.request['PATH_INFO'] assert len(mail.outbox) == 1 reset_url = [word for word in mail.outbox[0].body.split() if word.startswith('http')][0] res = self.client.get(reset_url, follow=True) ...
Arelle/Arelle
arelle/TableStructure.py
Python
apache-2.0
28,566
0.005776
''' Created on Feb 02, 2014 @author: Mark V Systems Limited (c) Copyright 2014 Mark V Systems Limited, All rights reserved. ''' try: import regex as re except ImportError: import re from collections import defaultdict import os, io, json from datetime import datetime, timedelta from arelle import XbrlConst fro...
one), ("LAP", RE(STMT, notDET, isPAR, r".*(?!.*changes)(?=.*assets).*liquidati"), None) ] HMRCtableCodes = [ # ELRs are parsed for these patterns in sort order until there is one match per code # sheet(s) may be plural ("DEI", RE(r".*entity\W+.*information.*"), None), ("BS", RE(r".*balance\W+she...
SE", RE(r".*(shareholder|equity).*"), None), ] def evaluateRoleTypesTableCodes(modelXbrl): disclosureSystem = modelXbrl.modelManager.disclosureSystem if disclosureSystem.validationType in ("EFM", "HMRC"): detectMultipleOfCode = False if disclosureSystem.validationType == "EFM": ...
maartenbreddels/vaex
packages/vaex-ui/vaex/ui/main.py
Python
mit
89,877
0.002348
from __future__ import print_function __author__ = 'breddels' # import astropy.vo.samp as sampy import platform import vaex.utils import sys import threading import vaex.export import vaex.utils import vaex.promise import vaex.settings import vaex.remote import psutil from vaex.parallelize import parallelize from vae...
rint "do", stat_name, "on", column_name return 1 # f = stats[stat_name] # return column_name, stat_name, f(self.data.columns[column_name]) # stats = {"minimum": lambda x: str(np.nanmin(x)), "maximum": lambda x: str(np.nanmax(x)), "mean": lambda x: str(np.mean(x)), "std": lambda x: str(np.std(x...
bda x: str(np.nanmax(x)), "mean": lambda x: str(np.mean(x)), "std": lambda x: str(np.std(x))} def statsrun(args): columns, stat_name, column_name = args f = stats[stat_name] # print args return 1 class StatWorker(QtCore.QThread): def __init__(self, parent, data): QtCore.QThread.__init__(...
Neoklosch/Motey
motey/models/service.py
Python
apache-2.0
2,107
0.000949
import uuid from motey.models.image import Image from motey.models.service_state import ServiceState class Service(object): """ Model object. Represent a service. A service can have multiple states, action types and service types. """ def __init__(self, service_name, images, id=uuid.uuid4().hex,...
n: the translated service model, None if something went wrong """ if 'service_name' not in data or 'images' not in data: return None return Service( id=data['id'] if 'id' in data else uuid.uuid4().hex, service_name=data['service_name'], images=[Ima...
orm(image) for image in data['images']], state=data['state'] if 'state' in data else ServiceState.INITIAL, state_message=data['state_message'] if 'state_message' in data else '' )
eduardosan/csindex
csindex/tests/test_cassandra.py
Python
gpl-2.0
2,692
0.000373
#!/usr/env python # -*- coding: utf-8 -*- __author__ = 'eduardo' import unittest import uuid from . import config from ..model import cs from cassandra.cluster import Session class TestCassandra(unittest.TestCase): """ Test interação com o banco de dados Cassandra """ def setUp(self): """ ...
id2 = uuid.uuid4() doc2 = cs.CS( content={'teste': 1234}, document_id=id2
) doc2.add() result = doc2.get() self.assertIsNotNone(result) # Testa documento que não existe id3 = uuid.uuid4() doc3 = cs.CS( content={'teste': 12345}, document_id=id3 ) result = doc3.get() self.assertIsNone(result) ...
leighpauls/k2cro4
third_party/WebKit/Tools/Scripts/webkitpy/common/net/credentials_unittest.py
Python
bsd-3-clause
9,141
0.002297
# Copyright (C) 2009 Google Inc. All rights reserved. # # 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 f...
_os_x(), False) self.assertEqual(credentials._credentials_from_keychain("foo"), ["foo", None]) def test_security_output_parse(self): credentials = MockedCredentials("bugs.webkit.org") self.assertEqual(credentials._parse_security_tool_output(self.example_security_output), ["test@we
bkit.org", "SECRETSAUCE"]) def test_security_output_parse_entry_not_found(self): # FIXME: This test won't work if the user has a credential for foo.example.com! credentials = Credentials("foo.example.com") if not credentials._is_mac_os_x(): return # This test does not run on a n...
apiad/sublime-subtitle-sync
subtitle_sync.py
Python
mit
1,030
0.009709
import sublime_plugin import sublime SUB_RE = '\d\d:\d\d:\d\d,\d\d\d' def find_subtitles(view): subs = [] sel = view.sel() for match in view.find_all(SUB_RE): if sel.contains(match): subs.append(match) # sel.clear() # sel.add_all(subs) return subs def convert_to_time(s...
ll(2) + ':' + ("%.3f" % s).zfill(6).replace('.', ',') class SubtitleSyncCommand(sublime_plugin.TextCommand): def run(self, edit, delta): subs = find_subtitles(self.view) for sub in subs: # self.view.sel(): time = convert_to_time(self.view.substr(sub)) time += delta ...
time = convert_to_string(time) self.view.replace(edit, sub, time)
nanditav/15712-TensorFlow
tensorflow/python/kernel_tests/resource_variable_ops_test.py
Python
apache-2.0
3,885
0.008752
# Copyright 2016 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...
===================== """Tests for tensorflow.ops.resource_variable_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework im...
ps import array_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.platform import test class ResourceVariableOpsTest(test_util.TensorFlowTestCase): def testHandleDtypeShapeMatch(self): with self.test_session(): handle = resource_variable_ops.var_handle_op(dtype=dtypes.int...
quom/google-cloud-python
runtimeconfig/unit_tests/test_variable.py
Python
apache-2.0
7,382
0.000135
# Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
self.assertEqual(self.VARIABLE_NAME, variable.name) self.assertEqual(len(conn._requested), 1) req = conn._requested[0] self.assertEqual(req['method'], 'GET') self.assertEqual(req['path'], '/%s' % (self.PATH,)) self._verifyResourc
eProperties(variable, RESOURCE) def test_reload_w_alternate_client(self): from google.cloud.runtimeconfig.config import Config RESOURCE = { 'name': self.PATH, 'value': 'bXktdmFyaWFibGUtdmFsdWU=', # base64 my-variable-value 'updateTime': '2016-04-14T21:21:54.500...
MayukhSobo/OpenStreetMap
test/test.py
Python
mit
799
0
#!/usr/bin/env python def get_db(db_name): from pymongo import MongoClient
client = MongoClient('localhost:27017') db = client[db_name] return db def make_pipeline(): # complete the aggregation pipeline match = {"$match": {"created": {"$exists": 1}}} group = {"$group": {"_id": "$created.user", "total": {"$sum": 1}}} sort = {"$sort": {"total": -1}} limit = {"$...
t": 5} pipeline = [match, group, sort, limit] return pipeline def aggregate(db, pipeline): return [doc for doc in db.openStreetDataMap.aggregate(pipeline)] if __name__ == '__main__': db = get_db('udacity') pipeline = make_pipeline() result = aggregate(db, pipeline) # print(type(result)) ...
imk1/IMKTFBindingCode
filterHomerMotifs.py
Python
mit
2,184
0.028388
import sys import argparse def parseArgument(): # Parse the input parser=argparse.ArgumentParser(description=\ "Filter Homer motifs to remove those with a low % of hits in target sites and a low value of target/background") parser.add_argument("--HomerMotifsFileName", required=True,\ help='Name of file with H...
the motif passes the cutoffs foregroundBackground = line.strip().split("\t")[5] foregroundBackgroundElements = foregroundBackground.split(",") foregroundElements = foregroundBackgroundElements[0].split("(") backgroundElements = foregroundBackgroundElements[1].split("(") if (float(foregroundElements
[1][0:-2]) < options.minTargetPercentage) or \ (float(foregroundElements[1][0:-2]) < options.minFoldChange * float(backgroundElements[1][0:-2])): # The current motif does not meet the thresholds, so skip it recordCurrentMotif = False else: # Record the current motif recordCurrentMotif = True if...
mjmeli/facebook-chat-word-cloud
facebook_wordcloud/word_counter.py
Python
mit
2,049
0.00244
""" word_counter Provides helper f
unction
s for word counts. """ import os import re from collections import Counter STOPWORDS_FILE = os.path.join(os.path.dirname(__file__), "STOPWORDS") # Get the frequencies of each word as a dictionary. # strings = a list of strings, can be strings of any length/number of words def get_frequencies(strings): # Ensure us...
r4wd3r/VAGO
src/controller/FileProcessing.py
Python
gpl-2.0
2,276
0.004394
# encoding=utf-8 import codecs import sys from src.view.FileProcessingOutput import FileProcessingOutput class FileProcessing(): def __init__(self): self.fileProcessingOutput = FileProcessingOutput() def read_input_file(self, file_path, file_type): ''' Lectura de archivo y procesamie...
te al formato d
e proceso, y al tipo de archivo ingresado :param line: Linea a procesar :param file_type: Tipo de archivo :param line_counter: Contador de linea, para notificar en caso de error. :return: Retorna si la linea cumple o no con el formato establecido. ''' if file_type == 0: ...
ctuning/ck-env
soft/lib.opencv/customize.py
Python
bsd-3-clause
8,458
0.033932
# # Collective Knowledge (individual environment - setup) # # See CK LICENSE.txt for licensing details # See CK COPYRIGHT.txt for copyright details # # Developer: Grigori Fursin, Grigori.Fursin@cTuning.org, http://fursin.net # import os ############################################################################## # ...
x=os.path.join(pi,'3rdparty',pabi) cus['path_static_lib']=cus['path_lib'] cus['static_lib']='libopencv_core.a' cus['extra_static_libs']={'opencv_imgproc':'libopencv_imgproc.a', 'opencv_ocl':'libopencv_ocl.a',
'opencv_highgui':'libopencv_highgui.a'} env[ep+'_JNI']=os.path.join(pi,'jni') env[ep+'_THIRDPARTY']=os.path.join(pi,'3rdparty') env[ep+'_STATIC_LIB_PATH']=cus['path_static_lib'] if winh=='yes': s+='\nset '+ellp+'=%'+ep+'_LIB%;'+plx+';%'+ellp+'%\n' ...
astrofrog/psrecord
setup.py
Python
bsd-2-clause
2,302
0.001303
#!/usr/bin/env python # # Copyright (c) 2013, Thomas P. Robitaille # 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 the above copyright notice, thi...
"Programming Language :: Python", "License :: OSI Approved :: BS
D License", ], )
telegraphic/fits2hdf
aadnc_benchmarks/quinoa_idea/quinoa.py
Python
mit
4,834
0.005176
# -*- coding: utf-8 -*- """ quinoa.py ========= Create QUINOA compressed dataset. QUINOA (QUasi Integer Noise Offset Adjustment) compression is a lossy compression algorithm for floating point data, and is similar to the RICE-based compression technique that FPACK uses on floating point data. The FITS compression pa...
seed: change seed value """ if subtractive_dither: data = apply_dither(data, seed) zero_point = np.nanmin(data) max_point = np.nanmax(data) dyn_range = max_point - zero_point data_zeroed = data - zero_point # Compute scale factor noise_rms = estimate_noise(data)...
{ 'zero': zero_point, 'noise_rms': noise_rms, 'scale_factor': scale_factor, 'dithered': subtractive_dither, 'seed': seed, 'data': data_int, 'q': q, 'dtype': str(data_int.dtype) } return scale_dict def quinoa_unscale(scale_dict): """ Unapply Q...
gam-phon/taiga-back
taiga/auth/tokens.py
Python
agpl-3.0
2,045
0
# Copyright (C) 2014-2016 Andrey Antukh <niwi@niwi.nz> # Copyright (C) 2014-2016 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014-2016 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014-2016 Alejandro Alonso <alejandro.alonso@kaleidos.net> # This program is free software: you can redistribute it and/or mo...
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 PARTICULAR PURPOSE
. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from taiga.base import exceptions as exc from django.apps import apps from django.core import signing fr...
rwl/pyreto
pyreto/continuous/task.py
Python
gpl-3.0
6,830
0.00366
# Copyright (C) 2007-2010 Richard Lincoln # # PYPOWER is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, # or (at your option) any later version. # # PYPOWER is distributed in the...
c License for more details. # # You should have received a copy of the GNU General Public Licens
e # along with PYPOWER. If not, see <http://www.gnu.org/licenses/>. """ Defines a profit maximisation task. """ import logging from pybrain.rl.environments import Task from pyreto.discrete.task import ProfitTask as DiscreteProfitTask from pylon import PQ, PV logger = logging.getLogger(__name__) class ProfitTask...
sicekit/sicekit
robots/tool-list_networks.py
Python
mit
2,437
0.0119
#!/usr/bin/python # -*- coding: utf-8 -*- """ This bot regenerates the page VEIDs The following parameters are supported: -debug If given, doesn't do any real changes, but only shows what would have been changed. """ __version__ = '$Id: basic.py 4946 2008-01-29 14:58:25Z wikipedian $'...
tpl: if line.startswith("|PRIVATE=1"): private = True if not private: print page.title() def run(self): print "# generated by netlist.py" for page in self.nets_generator: self.reg
isterIpNet(page) def main(): # The generator gives the pages that should be worked upon. gen = None # If debug is True, doesn't do any real changes, but only show # what would have been changed. debug = False wantHelp = False # Parse command line arguments for arg in wikipedia.handl...
gbour/Strawberry
strawberry/tag.py
Python
agpl-3.0
3,892
0.031346
# -*- coding: utf8 -*- __version__ = "$Revision$ $Date$" __author__ = "Guillaume Bour <guillaume@bour.cc>" __license__ = """ Copyright (C) 2010-2011, Guillaume Bour <guillaume@bour.cc> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License a...
n error page: HTTP code == 404, routed to strawberry.404 return routing.HTTP_404 #(content=Template('404.html', title='404')) tag = ret.msg print dir(tag), tag.__fields__ #TODO: tentacles workaround links = list(tag.Link__tags) tid = tag.id related = list(filter(lambda t: not t.Link__tags.isdisjoint(l...
mplate return Template('tag.html', title="Tag &#9732; %s" % tag.name, query=tag.name, tagname=tag.name, links=tag.Link__tags, searchtags=[], related=related, ) """
tkosciol/micronota
micronota/cli.py
Python
bsd-3-clause
3,634
0
# ---------------------------------------------------------------------------- # Copyright (c) 2015--, micronota development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # ---------------------------------------------...
(join(dirname(__file__), 'commands')) for filename in listdir(cmd_folde
r): if filename.endswith('.py') and filename != '__init__.py': rv.append(splitext(filename)[0]) rv.sort() return rv def _get_command(self, ctx, cmd_name): try: mod = __import__('micronota.commands.' + cmd_name, None, None,...
mgard/epater
i18n.py
Python
gpl-3.0
2,337
0.001712
import gettext class I18n: """ This class is used for internationalization without a specific language. Objects can be stored as msgid from gettext or as str. """ def __init__(self, msg, isSTR=False): if isSTR: self.content = [msg] else: self.content = [self...
f self.formatKwargs: for key, value in self.formatKwargs.items(): if
type(value) == I18n or type(value) == self.__class__: self.formatKwargs[key] = value.getText(t) if self.formatArg: resultArg = [] for arg in self.formatArg: if type(arg) == I18n or type(arg) == self.__class__: ...
indico/indico
indico/modules/categories/blueprint.py
Python
mit
8,380
0.006683
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from flask import redirect, request from indico.modules.categories.compat import compat_category from ind...
nage_upcoming', RHManageUpcomingEvents, methods=('GET', 'POST')) @_bp.before_request def _redirect_to_bootstrap(): # No users in Indico yet? Redirect from index page to bootstrap form if (request.endpoint == 'categories.d
isplay' and not request.view_args['category_id'] and not User.query.filter_by(is_system=False).has_rows()): return redirect(url_for('bootstrap.index')) _compat_bp = IndicoBlueprint('compat_categories', __name__) _compat_bp.add_url_rule('/category/<legacy_category_id>/<path:path>', 'legacy_id', com...
samuelmasuy/Concordia-Schedule-to-Gcal
app/scheduletogcal/calendar_controller.py
Python
gpl-2.0
5,318
0
# -*- coding: utf-8 -*- # =========================================================================== # # Copyright (C) 2014 Samuel Masuy. All rights reserved. # samuel.masuy@gmail.com # # =========================================================================== """ Calendar controller. ~~~~~~~~~~~~~~~~~~...
nth, first_day.day, tzinfo=TIMEZONE) dt_max = datetime(last_day.year, last_day.month, last_day.day, tzinfo=TIMEZONE) # Create a list of all the events we need to delete. old_events_list = service.events().list( calendarId=cal_id, timeMin=dt_min.is...
vents = [] for old_event_id in old_events_list: old_recur_events.append( service.events().instances(calendarId=cal_id, eventId=old_event_id, timeMin=dt_min.isoformat(), timeMax=dt...
dubirajara/django_my_ideas_wall
myideas/api/urls.py
Python
agpl-3.0
931
0
"""tweetme URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-ba...
nt:pk>/', views.IdeasIdApiView.as_view(), name="id_api"), path('<username>/', views.UserListApiView.as_view(), name="use
r_api"), ]
mjem/themelog
tests/test_stdout.py
Python
apache-2.0
395
0
#
!/usr/bin/env python """Messages are written to stdout instead of the normal stderr. """ import logging from themelog import init_log logger = logging.getLogger() init_log(stdout=True) logger.debug('This is a debug message') logger.info('This is a info message') logger.w
arning('This is a warning message') logger.error('This is a error message') logger.critical('This is a critical message')
dvliman/jaikuengine
.google_appengine/google/appengine/tools/devappserver2/module_test.py
Python
apache-2.0
90,007
0.002822
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
gle.appengine.tools.devappserver2 import module from google.appengine.tools.devappserver2 import s
tart_response_utils from google.appengine.tools.devappserver2 import wsgi_server class ModuleConfigurationStub(object): def __init__(self, application_root='/root', application='app', module_name='default', automatic_scaling=appinfo.AutomaticScaling(), ...
jingxiang-li/kaggle-yelp
model/level3_model.py
Python
mit
5,368
0
from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import numpy as np import xgboost as xgb import argparse from os import path import os from hyperopt import fmin, tpe, hp, STATUS_OK, Trials from utils import * import pi...
eds = np.zeros((y.shape[0])) params['silent'] = 1 params['objective'] = 'binary:logistic' params['scale_pos_weight'] = float(np.sum(y == 0)) / np.sum(y == 1) for train_ix, test_ix in makeKFold(5, y, reps): X_train, X_test = X[train_ix, :], X[test_ix, :] y_train = y[train_ix] dtra...
num_boost_round=params['num_boost_round'], evals=[(dtrain, 'train')], feval=evalF1, maximize=True, verbose_eval=None) preds[test_ix] = bst.predict(dtest) return preds def get_model(params, X, y): dtr...
whitepages/nova
nova/tests/functional/api_sample_tests/test_shelve.py
Python
apache-2.0
2,280
0
# Copyright 2012 Nebula, Inc. # Copyright 2013 IBM Corp. # # Lice
nsed under the Apache License, Version 2.0 (the "License"); you may # not use this f
ile 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 COND...
javier-ruiz-b/docker-rasppi-images
raspberry-google-home/env/lib/python3.7/site-packages/google/api/config_change_pb2.py
Python
apache-2.0
8,266
0.000484
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
", serialized_pb=b'\n\x1egoogle/api/config_change.proto\x12\ngoogle.api"\x97\x01\n\x0c\x43onfigChange\x12\x0f\n\x07\x65lement\x18\x01 \x01(\t\x12\x11\n\told_value\x18\x02 \x01(\t\x12\x11\n\tnew_value\x18\x03 \x01(\t\x12+\n\x0b\x63hange_type\x18\x04 \x01(\x0e\x32\x16.google.api.ChangeType\x12#\n\x0
7\x61\x64vices\x18\x05 \x03(\x0b\x32\x12.google.api.Advice"\x1d\n\x06\x41\x64vice\x12\x13\n\x0b\x64\x65scription\x18\x02 \x01(\t*O\n\nChangeType\x12\x1b\n\x17\x43HANGE_TYPE_UNSPECIFIED\x10\x00\x12\t\n\x05\x41\x44\x44\x45\x44\x10\x01\x12\x0b\n\x07REMOVED\x10\x02\x12\x0c\n\x08MODIFIED\x10\x03\x42q\n\x0e\x63om.google.apiB...
yeti-platform/yeti
core/web/api/investigation.py
Python
apache-2.0
5,579
0.001255
from __future__ import unicode_literals import logging import re from datetime import datetime from bson import ObjectId from bson.json_util import loads from flask import request from flask_classy import route from flask_login import current_user from core import investigation from core.entities import Entity from ...
json["name"], updated=datetime.utcnow()) return render("ok") @route("/nodesearch/<path:que
ry>", methods=["GET"]) @requires_permissions("read") def nodesearch(self, query): result = [] query = re.compile("^{}".format(query), re.IGNORECASE) observables = Observable.objects(value=query).limit(5) entities = Entity.objects(name=query).limit(5) for results in [ob...
elbeardmorez/quodlibet
quodlibet/tests/test_qltk_cbes.py
Python
gpl-2.0
4,802
0.000208
# -*- coding: utf-8 -*- # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. from tests import TestCase, mkstemp import os ...
(row1[2], row2[2]) def test_text_changed_signal(self): called = [0] def cb(*args): called[0] += 1 def get_count(): c = called[0] called[0] = 0
return c self.cbes.connect("text-changed", cb) entry = self.cbes.get_child() entry.set_text("foo") self.failUnlessEqual(get_count(), 1) self.cbes.prepend_text("bar") # in case the model got changed but the entry is still the same # the text-changed signal should ...
loftytopping/UManSysProp_public
umansysprop/partition_models.py
Python
gpl-3.0
17,483
0.004519
# vim: set et sw=4 sts=4 fileencoding=utf-8: # # Copyright (c) 2016 David Topping. # All Rights Reserved. # This file is part of umansysprop. # # umansysprop 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, eit...
e along with # umansysprop. If no
t, see <http://www.gnu.org/licenses/>. from __future__ import ( unicode_literals, absolute_import, print_function, division, ) str = type('') import warnings from math import sqrt, exp, log, log10, isinf from . import data from . import groups from . import activity_coefficient_models as aiomfa...
Jidgdoi/MythologyQuest
src/JsonParser.py
Python
gpl-3.0
1,734
0.03291
# -*- coding:utf-8 -*- #
Cyril Fournier # 10/08/2016 # ==============================
========= # Update the trackList.json of a JBrowse, # by adding category, description, color # ======================================= import os,sys import json from Hero import Hero from Monster import Monster from Item import Item # ============================ #  === FUNCTIONS === # =========================...
yelongyu/leetcode
136.single_number.py
Python
apache-2.0
801
0
# -*- coding: utf-8 -*- ""
" Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? """ __author__ = 'yelongyu1024@gmail.com' class Solution(object): def __init__(self, nums): sel...
for num in self.nums: num_count.setdefault(num, 0) num_count[num] = num_count.get(num) + 1 print num_count for key, value in num_count.items(): if value == 1: return key def main(): solution = Solution([2, 3, 5, 7, 9, 3, 5, 7, 9]) print...
TheClimateCorporation/properscoring
properscoring/_brier.py
Python
apache-2.0
7,326
0.000956
import numpy as np from ._utils import move_axis_to_end, suppress_warnings def brier_score(observations, forecasts): """ Calculate the Brier score (BS) The Brier score (BS) scores binary forecasts $k \in \{0, 1\}$, ..math: BS(p, k) = (p_1 - k)^2, where $p_1$ is the forecast probability...
are already sorted along `axis`. axis : int, optional Axis in forecasts which corresponds to different ensemble members, along which to calculate the threshold decomposition. Returns ------- out : np.ndarray
Brier scores at each thresold for each ensemble forecast against the observations. If ``threshold`` is a scalar, the result will have the same shape as observations. Otherwise, it will have an additional final dimension corresponding to the threshold levels. References ----------...
hrayr-artunyan/shuup
shuup/front/basket/objects.py
Python
agpl-3.0
14,937
0.001674
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals import random from collections impo...
f.discount_amount = price_info.discount_amount assert self.price == price_info.price self.net_weight = product.net_weight self.gross_weight = product.gross_weight self.shipping_mode = product.shipping_mode self.sku = product.sku self.text = product.safe_translation_getter...
self.__dict__.get("type") or OrderLineType.OTHER) @type.setter def type(self, type): if self.__in_init: self.__dict__["type"] = type return if self.product and type != OrderLineType.PRODUCT: raise ValueError("Can not set a line type for a basket line when it...
airbnb/knowledge-repo
knowledge_repo/postprocessors/extract_images_to_s3.py
Python
apache-2.0
2,903
0.001033
import os import posixpath import random import string import logging import tempfile import time from .extract_images import ExtractImages logger = logging.getLogger(__name__) class ExtractImagesToS3(ExtractImages): ''' This KnowledgePostProcessor subclass extracts images from posts to S3. It is desig...
ring.ascii_lowercase) for i in range(6)) fname_img = '{repo_name}_{time}_{random_string}{ext}'.format( repo_name=repo_name, time=int(round(time.time() * 100)), random_string=random_string, ext=img_ext).strip().replace(' ', '-') # C...
need to be prefixed with a login agent; # for example, to handle multi-factor authentication. cmd = "aws s3 cp '{0}' {1}".format(tmp_path, fname_s3) logger.info("Uploading images to S3: {cmd}".format(cmd=cmd)) retval = os.system(cmd) if retval != 0: ...
AndrewRook/game_designer
card_game/migrations/0002_auto__del_unique_cards__del_cards__del_versions__del_unique_versions__.py
Python
mit
7,131
0.006731
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting model 'unique_cards' db.delete_table(u'card_game_unique_cards'...
db.delete_table(u'card_game_unique_versions') # Adding model 'Unique_Card' db.create_table(u'card_game_unique_card', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('card_id', self.gf('django.db.models.fields.related.ForeignKey')(
to=orm['card_game.Card'])), )) db.send_create_signal(u'card_game', ['Unique_Card']) # Adding model 'Card' db.create_table(u'card_game_card', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('name', self.gf('django.db.models.fields.CharF...
Naereen/mazhe
phystricksRechercheTangente.py
Python
gpl-3.0
3,050
0.041981
# -*- coding: utf8 -*- from __future__ import unicode_literals from phystricks import * def VGZooJnvvZc(): n_ssfig=6 pspictQuestion,figQuestion = SinglePicture("TangenteQuestionOM",script_filename="RechercheTangente") pspictDetail,figDetail = SinglePicture("TangenteDetailOM",scr
ipt_filename="RechercheTangente") pspictsSubFig,figSubFig = MultiplePictures("LesSubFiguresOM",n_ssfig) pspicts=[pspictQuestion,pspictDetail] pspicts.extend(pspictsSubFig) mx=0.7 Mx=5 x=var('x') f=phyFunction(-3/x+5).graph(mx,Mx) P=f.get_point(1.7) Q=f.get_point(4) P.put_mark(...
x=Point(Q.x,0) Qy=Point(0,Q.y) Py.put_mark(0.1,180,"$f(a)$",automatic_place=(pspicts,"E")) Qy.put_mark(0.1,180,"$f(x)$",automatic_place=(pspicts,"E")) Px.put_mark(0.2,-90,"$a$",automatic_place=(pspicts,"N")) Qx.put_mark(0.2,-90,"$x$",automatic_place=(pspicts,"N")) v1=Segment(Q,Qx) v2=S...
steinitzu/spotify-api
spotify/__init__.py
Python
mit
75
0.013333
from
.client import Client from .auth import OAuth _
_version__ = '0.0.8'
piotrmaslanka/bellum
mother/ajax/__init__.py
Python
agpl-3.0
39
0
'''Contains AJAX apps of mot
her app'''
googleapis/python-aiplatform
samples/generated_samples/aiplatform_generated_aiplatform_v1_vizier_service_complete_trial_sync.py
Python
apache-2.0
1,480
0.000676
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
execute the following: # python3 -m pip install google-cloud-aiplatform # [START aiplatform_generated_aiplatform_v1_VizierService_CompleteTrial_sync] from google.cloud import aiplatform_v1 def sample_complete_trial(): # Create a client client = aiplatform_v1.VizierServiceClient() # Initialize reques...
t) # Handle the response print(response) # [END aiplatform_generated_aiplatform_v1_VizierService_CompleteTrial_sync]
nwjs/chromium.src
third_party/blink/web_tests/http/tests/websocket/echo-with-no-extension_wsh.py
Python
bsd-3-clause
2,057
0
# Copyright 2012, Google Inc. # All rights reserved. # # 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 f...
RE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import six _GOODBYE_MESSAGE = u'Goodbye' def web_socket_do_extra_handshake(request): request.ws_extension_processors = [] def web_socket_transfer_data(request): while True: line = request.ws_stream.receive_message() if line is None: ...
_type): request.ws_stream.send_message(line, binary=False) if line == _GOODBYE_MESSAGE: return else: request.ws_stream.send_message(line, binary=True)
lariodiniz/GrimorioTRPG
grimorio/core/models.py
Python
gpl-2.0
3,520
0.011691
# coding: utf-8 #--------------//////////---------------------- #Projeto Criado por: Lário Diniz #Contatos: developer.lario@gmail.com #Data: 06/08/2015 #--------------//////////---------------------- from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugett...
ering = ['name'] verbose_name = _(u'Tipo') verbose_name_plural = _(u'Tipos') class Book(models.Model): name=models.CharField(_('Nome'), max_length=100, unique=True) def __unicode__(self): return self.name class Meta: ordering = ['name'] verbose_name = _(u'Livro') ...
ells(models.Model): name=models.CharField(_('Nome'), max_length=250, unique=True) execution=models.CharField(_(u'Execução'), max_length=100) nivel=models.IntegerField(_('Nivel da Magia')) reach=models.ForeignKey('Reach', verbose_name=_('Alcance'), blank=True) target=models.CharField(_('Alvo'), max_l...
mangadul/WhatsAppy
yowsup/common/constants.py
Python
gpl-3.0
837
0.003584
class YowConstants: DOMAIN = "s.whatsapp.net" ENDPOINTS = ( ("e1.whatsapp.net", 443), ("e2.whatsapp.net", 443), ("e3.whatsapp.net", 443), ("e4.whatsapp.net", 443), ("e5.whatsapp.net", 443), ("e6.whatsapp.net", 443), ("e7.whatsapp.net", 443), ...
("e8.whatsapp.net", 443), ("e9.whatsapp.net", 443), ("e10.whatsapp.net", 443), ("e11.whatsapp.net", 443), ("e12.whatsapp.net", 443), ("e13.whatsapp.net", 443), ("e14.whatsapp.net", 443), ("e15.whatsapp.net", 443), ("e16.whatsapp.net", 443), ) ...
SERVER = "s.whatsapp.net" WHATSAPP_GROUP_SERVER = "g.us" PATH_STORAGE = "~/.yowsup" PREVIEW_WIDTH = 64 PREVIEW_HEIGHT = 64
rwl/muntjac
muntjac/demo/sampler/features/commons/JSApiExample.py
Python
apache-2.0
4,137
0.000242
import time import threading from time import gmtime, strftime from muntjac.api import Button, VerticalLayout, Label, TextArea from muntjac.terminal.theme_resource import ThemeResource from muntjac.ui.button import IClickListener class JSApiExample(VerticalLayout): def __init__(self): super(JSApiExamp...
nt(Button('Run script', RunListener(self, script))) # syn
c = Label("<h3>Force Server Syncronization</h3>", # Label.CONTENT_XHTML) # self.addComponent(sync) # # self.addComponent(Label('For advanced client side programmers ' # 'Muntjac offers a simple method which can be used to force ' # 'the client to synchronize wi...
WebClub-NITK/Hacktoberfest-2k17
Sorting/Bubble_Sort/nishanthebbar2011.py
Python
mit
318
0.034591
arr=[] n=int(input("Please enter the number of elements and then the actual elements themselves!")) for i in range(n): x=int(input()) arr.a
ppend(x) for i in range(n-1)
: for j in range(0,n-i-1): if arr[j]>arr[j+1]: arr[j],arr[j+1]=arr[j+1],arr[j] print("The sorted arr is",arr)
bruny/romcollectionbrowser
resources/tests/test_matcher.py
Python
gpl-2.0
2,187
0.037401
# -*- coding: utf-8 -*- import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', 'resources', 'lib')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'resources', 'lib', 'pyscraper')) from matcher import Matcher import util as util import unittest class TestM...
= u'スーパー競輪', "Expected matching unicode strings to match") def test_getBestResultsNonMatchingWithUnicode(self): results = [{'SearchKey': [u'スーパー競輪']}] gamename = 'Super Test Game' m = Matcher() x = m.getBestResults(results, gamename) self.assertIsNone(x, "Expected non-matching strings to not match, inclu...
[{'SearchKey': ['FIFA 98']}, {'SearchKey': ['FIFA 97']}, {'SearchKey': ['FIFA 2001']}] gamename = 'FIFA \'98 (1998) [Electronic Arts]' m = Matcher() x = m.getBestResults(results, gamename) self.assertEquals(x.get('SearchKey')[0], 'FIFA 98') if __name__ == "__main__": unittest.main()
F5Networks/f5-ansible-modules
ansible_collections/f5networks/f5_modules/plugins/modules/bigiq_regkey_license_assignment.py
Python
mit
19,962
0.001904
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: (c) 2017, F5 Networks Inc. # 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_function __metaclass__ = type DOCUMENTATION = r''' --- module: bigiq_regkey_license_as...
client.provider['server'], self.client.provider['server_port'], filter) resp = self.client.api.get(uri) try: response = resp.json() except ValueError as ex: raise F5ModuleError(str(ex)) if resp.status == 200 and response[...
se['code'] == 400: if 'message' in response: raise F5ModuleError(response['message']) else: raise F5ModuleError(resp._content) id = response['items'][0]['uuid'] result = dict( link='https://localhost/mgmt/shared/resolver/device-groups/c...
foursquare/pants
contrib/go/src/python/pants/contrib/go/tasks/go_thrift_gen.py
Python
apache-2.0
7,092
0.010011
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import os import re from pants.backend.codegen.thrift.lib.thrift import Thrift from pant...
'support multiple files.') @classmethod def subsystem_dependencies(cls): return super(GoThriftGen, cls).subsystem_dependencies() + (Thrift.scoped(cls),) @property def _thrift_binary(self): return self._thrift.select(context=self.context) @property def _thrift_version(self): return self....
y def _deps(self): thrift_import_target = self.get_options().thrift_import_target if thrift_import_target is None: raise TaskError('Option thrift_import_target in scope {} must be set.'.format( self.options_scope)) thrift_imports = self.context.resolve(thrift_import_target) return thrift...
rbian/tp-libvirt
v2v/tests/linux_vm_check.py
Python
gpl-2.0
3,241
0.000309
import re import logging from autotest.client.shared import error from virttest import utils_v2v def run(test, params, env): """ Check VM after conversion """ target = params.get('target') check_obj = utils_v2v.LinuxVMCheck(test, params, env) logging.info("Check guest os info") os_info =...
Check parted info after conversion") parted_info = check_obj.get_vm_parted() if os_version != '3': if re.findall('/dev/vd\S+', parted_info): logging.info("SUCCESS") else: raise error.TestFail("FAIL") logging.info("Check virtio_net module in modprobe co
nf") modprobe_conf = check_obj.get_vm_modprobe_conf() if not re.search('No such file', modprobe_conf): virtio_mod = re.findall(r'(?m)^alias.*virtio', modprobe_conf) net_blk_mod = re.findall(r'(?m)^alias\s+scsi|(?m)^alias\s+eth', modprobe_conf) if len(virt...
cobbler/cobbler
tests/xmlrpcapi/repo_test.py
Python
gpl-2.0
3,559
0.000843
import pytest @pytest.fixture def create_repo(remote, token): """ Creates a Repository "testrepo0" with a mirror "http://www.sample.com/path/to/some/repo" and the attribute "mirror_locally=0". :param remote: The xmlrpc object to connect to. :param token: The token to authenticate against the remo...
, token) remote.modify_repo(repo, "mirror_locally", False, token) remote.save_repo(repo, token) @pytest.fixture def remove_repo(remote, token): """ Removes the Repository "testrepo0" which can be created with create_repo. :param remote: The xmlrpc object to connect to. :param token: The token...
rpc_base") class TestRepo: @pytest.mark.usefixtures("remove_repo") def test_create_repo(self, remote, token): """ Test: create/edit a repo object """ # Arrange --> Nothing to arrange # Act & Assert repo = remote.new_repo(token) assert remote.modify_repo(...
jedie/DragonPy
dragonpy/tests/test_BASIC_simple09.py
Python
gpl-3.0
25,042
0.000958
#!/usr/bin/env python """ 6809 unittests ~~~~~~~~~~~~~~ Test CPU with BASIC Interpreter from simple6809 ROM. :created: 2014 by Jens Diemer - www.jensdiemer.de :copyleft: 2014-2015 by the DragonPy team, see AUTHORS for more details. :license: GNU GPL v3 or above, see LICENSE for more details. ...
phery.add_to_input_queue('?3/2\r\n') op_call_count, cycles, output = self._run_until_OK(max_ops=4500) # print(op_call_count, cycles, output) self.assertEqual(output, ['?3/2\r\n', ' 1.5 \r\n', 'OK\r\n'] ) def test_division3(self): sel...
ops=5100) # print(op_call_count, cycles, output) self.assertEqual(output, ['?5/3\r\n', ' 1.66666667 \r\n', 'OK\r\n'] ) def test_multiply1(self): self.periphery.add_to_input_queue('?3*2\r\n') op_call_count, cycles, output = self._run_...
abhikeshav/ydk-py
cisco-ios-xr/ydk/models/cisco_ios_xr/_meta/_Cisco_IOS_XR_infra_syslog_oper.py
Python
apache-2.0
26,188
0.017413
import re import collections from enum import Enum from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLI...
ber('history', REFERENCE_CLASS, 'History' , 'ydk.models.cisco_ios_xr.Cisco_IOS_XR_infra_syslog_oper', 'Logging.History',
[], [], ''' Syslog Info ''', 'history', 'Cisco-IOS-XR-infra-syslog-oper', False), ], 'Cisco-IOS-XR-infra-syslog-oper', 'logging', _yang_ns._namespaces['Cisco-IOS-XR-infra-syslog-oper'], ...
GuessWhoSamFoo/pandas
pandas/tests/io/json/test_ujson.py
Python
bsd-3-clause
38,511
0
# -*- coding: utf-8 -*- try: import json except ImportError: import simplejson as json import calendar import datetime import decimal from functools import partial import locale import math import re import time import dateutil import numpy as np import pytest import pytz import pandas._libs.json as ujson fr...
) for double_precision in (3, 9):
output = ujson.encode(double_input, double_precision=double_precision) rounded_input = round(double_input, double_precision) assert rounded_input == json.loads(output) assert rounded_input == ujson.decode(output) @pytest.mark.parametrize(...
Pierre-Sassoulas/django-survey
survey/exporter/tex/question2tex_chart.py
Python
agpl-3.0
4,424
0.000226
import logging from django.conf import settings from django.utils.translation import gettext_lazy as _ from survey.exporter.tex.question2tex import Question2Tex LOGGER = logging.getLogger(__name__) class Question2TexChart(Question2Tex): """ This class permit to generate latex code directly from the Questi...
if answer: final_answers.append(answer) return
" {}".format(",\n ".join(final_answers)) def get_pie_options(self): # noqa: C901 r"""Return the options of the pie for: \pie[options]{data}""" options = "" if self.pos: options += "pos={%s}," % self.pos if self.explode: options += "exp...
dsarkozi/care4care-sdp-grp4
Care4Care/C4CApplication/views/RemoveFavoriteRedirectView.py
Python
agpl-3.0
926
0.007559
from django.views.decorators.cache import neve
r_cache from django.views.generic.base import RedirectView from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse_lazy from
C4CApplication.views.utils import create_user class RemoveFavoriteRedirectView(RedirectView): url = reverse_lazy("favorites") user= None def dispatch(self, request, *args, **kwargs): if 'email' not in self.request.session: raise PermissionDenied # HTTP 403 ...
FedoraScientific/salome-paravis
test/VisuPrs/GaussPoints/C1.py
Python
lgpl-2.1
2,013
0.002981
# Copyright (C) 2010-2014 CEA/DEN, EDF R&D # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library ...
er General Public # License along with this library; if not,
write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # # This case corresponds to: /visu/GaussPoints/C1 case # Create Gauss Points on the field of the MED file import os import sys fr...
sburnett/seattle
deploymentscripts/attic/deploy_server_final.py
Python
mit
13,882
0.01592
""" <Program Name> deploy_server_final.py <Started> July 2009 <Author> n2k8000@u.washington.edu Konstantin Pik <Purpose> This is a fully automated webserver that handles only certain web requests. The server assumes files exist in the locations that they're supposed to exist, and the files are placed th...
><tr>' # returns some HTML that are the navigation links at the bottom of the page previous_index = self.get_previous_index(current_index) if previous_index != -1: # not empty, so make a link html += '<td align="center">' previous_link = self.make_link
_to(previous_index, 'Previous') html += previous_link+'</td>' next_index = self.get_next_index(current_index) if next_index != -1: html += '<td align="center">' next_link = self.make_link_to(next_index, 'Next') html += next_link+'</td>' html += '</table>' return html...
marios-zindilis/musicbrainz-django-models
musicbrainz_django_models/tests/test_l_artist_release.py
Python
gpl-2.0
451
0
from django.test import
TestCase from ..models import l_artist_release class test_l_artist_release(TestCase): def setUp(self): """ Set up the test subject. """ self.subject = l_artist_release
() def test__l_artist_release__instance(self): self.assertIsInstance(self.subject, l_artist_release) def test__l_artist_release__str(self): self.assertEqual(str(self.subject), 'L Artist Release')
obi-two/Rebelion
data/scripts/templates/object/weapon/melee/sword/crafted_saber/shared_sword_lightsaber_one_handed_s12_gen1.py
Python
mit
497
0.044266
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTAT
ION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Weapon() result.template = "object/weapon/melee/sword/crafted_saber/shared_sword_lightsaber_one_handed_s12_gen1.iff" r
esult.attribute_template_id = 10 result.stfName("weapon_name","sword_lightsaber_type12") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
Foxi352/netlib
network.py
Python
gpl-3.0
39,974
0.003402
#!/usr/bin/env python3 # vim: set encoding=utf-8 tabstop=4 softtabstop=4 shiftwidth=4 expandtab ######################################################################### # Parts Copyright 2016 C. Strassburg (lib.utils) c.strassburg@gmx.de # Copyright 2017- Serge Wagener serge@wagener.family ##...
ng :rtype: string """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(('8.8.8.8', 1)) IP = s.getsockname
()[0] except: IP = '127.0.0.1' finally: s.close() return IP @staticmethod def get_local_ipv6_address(): """ Get's local ipv6 address of the interface with the default gateway. Return '::1' if no suitable interface is found :return...
VaclavDedik/infinispan-py
tests/func/server.py
Python
mit
2,231
0
# -*- coding: utf-8 -*- import os import signal import time import subprocess import pytest class Mode(object): STANDALONE = "standalone.sh" DOMAIN = "domain.sh" class InfinispanServer(object): DOWNLOAD_URL = "http://downloads.jboss.org/infinispan/%s.Final/" ZIP_NAME = "infinispan-server-%s.Final-b...
raise RuntimeError("Server already running") launch_script = os.path.join(self.dir_path, "bin", self.mode) self.process = subprocess.Popen( [launch_script], shell=True, preexec_fn=os.setsid) time.sleep(self._get_wait_time()) def stop
(self): if not self.process: raise RuntimeError("Server is already stopped") os.killpg(os.getpgid(self.process.pid), signal.SIGTERM) time.sleep(self._get_wait_time(start=False)) self.process = None def kill(self): if not self.process: raise RuntimeErr...
amfoss/fosswebsite
workshop/urls.py
Python
mit
2,168
0.007841
# created by Chirath R, chirath.02@gmail.com from django.conf.urls import url from django.contrib.auth.decorators import login_required from django.views.generic import TemplateView from workshop.views import WorkshopRegistrationListView, WorkshopDetailView, WorkshopRegistrationUpdateView, \ WorkshopRegisterFormVi...
iew, WorkshopDeleteView urlpatterns = [ url(r'^$', WorkshopListView.as_view(), name='workshop_list'), url(r'^create/$', login_required(WorkshopCreateView.as_view()), name='workshop_
create'), url(r'^(?P<workshop_id>[0-9]+)/$', WorkshopDetailView.as_view(), name='workshop_detail'), # TODO(2) Fix update and uncomment # url(r'^(?P<pk>[0-9]+)/update/$', login_required(WorkshopUpdateView.as_view()), name='workshopdetail_update'), url(r'^(?P<pk>[0-9]+)/delete/$', login_required(Worksho...
missionpinball/mpf
mpf/platforms/lisy/__init__.py
Python
mit
33
0
"""LISY System
1/80
platform."""
stephane-martin/salt-debian-packaging
salt-2016.3.3/tests/unit/states/selinux_test.py
Python
apache-2.0
5,176
0.000193
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Jayesh Kariya <jayeshk@saltstack.com>` ''' # Import Python libs from __future__ import absolute_import # Import Salt Testing Libs from salttesting import skipIf, TestCase from salttesting.mock import ( NO_MOCK, NO_MOCK_REASON, MagicMock, patch ) fro...
mock_bools = MagicMock(return_value={name: {'State': 'off', 'Default': 'on'}}) mock = MagicMock(side_effect=[True, False]
) with patch.dict(selinux.__salt__, {'selinux.list_sebool': mock_bools, 'selinux.setsebool': mock}): with patch.dict(selinux.__opts__, {'test': True}): comt = ('Boolean samba_create_home_dirs' ' is set to be cha...
jhunkeler/acstools
acstools/acszpt.py
Python
bsd-3-clause
14,427
0.000416
""" This module contains a class, :class:`Query`, that was implemented to provide users with means to programmatically query the `ACS Zeropoints Calculator <https://acszeropoints.stsci.edu>`_. The API works by submitting requests to the ACS Zeropoints Calculator referenced above and hence, it is only valid for ACS spec...
) >>> zpt_table = q.fetch() >>> print(zpt_table
) FILTER PHOTPLAM PHOTFLAM STmag VEGAmag ABmag Angstrom erg / (Angstrom cm2 s) mag(ST) mag mag(AB) ------ -------- ---------------------- ------- ------- ------- F435W 4329.2 3.148e-19 25.155 25.763 25.665 Retrieve the zeropoint information for the F435W filter for WFC a...
indictranstech/focal-erpnext
projects/doctype/project/project.py
Python
agpl-3.0
2,450
0.023673
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import flt, getdate from frappe import _ from erpnext.utilities.transaction_base import delete_events from frappe.m...
missions=True) def on_trash(self): delete_events(self.doctype, self.name) @frappe.whitelist() def get_cost_center_name(project_name): return frappe.db.get_value("Proj
ect", project_name, "cost_center")
retr0h/molecule
molecule/util.py
Python
mit
5,717
0.00035
# Copyright (c) 2015-2017 Cisco Systems, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge...
der on files managed by Molecule and returns None. :param filename: A string containing the target filename. :return: None """ molecule_header = '# Molecule managed\n\n' with open(fi
lename, 'r+') as f: content = f.read() f.seek(0, 0) f.write(molecule_header + content) def safe_dump(data): """ Dump the provided data to a YAML document and returns a string. :param data: A string containing an absolute path to the file to parse. :return: str """ # TO...
dannywxh/mypy
MyPys/common.py
Python
apache-2.0
3,687
0.034014
#!/usr/bin/env python # -*- coding: utf-8 -*- import os, re, time, sys import hashlib, bencode import requests from bs4 import BeautifulSoup reload(sys) #print sys.getdefaultencoding() #sys.setdefaultencoding('utf-8') print sys.getdefaultencoding() def parse_tor(file): bt_path = {} bt_...
listdir(path) if all([os.path.splitext(x)[1]=='.txt', not os.path.isdir(path+"\\"+x)])] # txtfile=[f for f in files if os.path.splitext(f)[1]=='.txt'] store=[] for txtfile in files: for line in open(path+"/"+txtfile): p,f=os.path.split(line) store.append((f.replac...
,txtfile)) return store #����list�ԱȺ��Ĺ��ܣ������ܵ��� def comparelist(src,des): #src: ["file"] #des:[("file","path")] from collections import defaultdict dic=defaultdict(list) for x in src: for a,b in des: #print x,a,b ...
filippog/pysnmp
pysnmp/entity/rfc3413/ntfrcv.py
Python
bsd-3-clause
4,010
0.001746
# # This file is part of pysnmp software. # # Copyright (c) 2005-2016, Ilya Etingof <ilya@glas.net> # License: http://pysnmp.sf.net/license.html # import sys from pyasn1.compat.octets import null from pysnmp.proto import rfc3411, error from pysnmp.proto.api import v1, v2c # backend is always SMIv2 compliant from pysnm...
snmpEngine.msgAndPduDsp.returnResponsePdu( snmpEngine, messageProcessingModel, securityModel, securityName, securityLevel, contextEngineId, contextName, pduVersion, rspPDU, maxSizeResponseScopedPDU, stateReference, statusInformation) ...
tion %s' % (stateReference, sys.exc_info()[1])) snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpSilentDrops') snmpSilentDrops.syntax += 1 elif PDU.tagSet in rfc3411.unconfirmedClassPDUs: pass else:...
nmalkin/multimail
multimail.py
Python
gpl-3.0
4,444
0.006076
#!/usr/bin/env python import csv import getopt import os import sys from ConfigParser import ConfigParser from tempfile import NamedTemporaryFile # Defaults VERBOSE = True CONFIG_SECTION = 'common' DEFAULT_CONFIG_FILE = 'batch.cfg' DEFAULT_RECIPIENTS_FILE = 'recipients.csv' DEFAULT_MESSAGE_FILE = 'message.txt' # Com...
alized_message, subject, address, cc, bcc, attachment_matched) def main(): config_file = DEFAULT_CONFIG_FILE recipients_file = DEFAULT_RECIPIENTS_FILE message_file = DEFAULT_MESSA
GE_FILE # Read command-line options try: opts, args = getopt.getopt(sys.argv[1:], 'c:r:m:s', ['config=', 'recipients=', 'message=', 'silent']) except getopt.GetoptError, err: print(str(err)) for opt, val in opts: if opt in ('-c', '--config'): config_file = val ...
midfies/django-imager
imagersite/imager_images/admin.py
Python
mit
728
0
from django.contrib import admin from imager_images.models import Photo, Album # class PhotoAdmin(admin.ModelAdmin): # list_display = ("title", "description") # fields = ('title', # 'description', # 'published', # 'owner') # class AlbumAdmin(admin.ModelAdmin): # ...
'owner') admin.site.register(Photo) class AlbumInline(admin.TabularInline): model = Album.photos.through @admin.register(Album) class AlbumAdmin(admin.ModelAdmin): inlines = (AlbumInline,
) exclude = ('photos',)
IT-PM-OpenAdaptronik/Webapp
apps/calc/apps.py
Python
mit
88
0
fr
om django.apps import AppConfig class CalcConfig(AppConfig): name = 'apps.c
alc'
Mellthas/quodlibet
quodlibet/qltk/renamefiles.py
Python
gpl-2.0
18,543
0
# Copyright 2004-2005 Joe Wreschnig, Michael Ur
man, Iñigo Serna # 2020 Nick Boultbee # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. import os import...
rt util from quodlibet import config from quodlibet import _ from quodlibet.plugins import PluginManager from quodlibet.pattern import FileFromPattern from quodlibet.pattern import ArbitraryExtensionFileFromPattern from quodlibet.qltk._editutils import FilterPluginBox, FilterCheckButton from quodlibet.qltk._editutils ...
stonebig/bokeh
bokeh/core/property/numeric.py
Python
bsd-3-clause
8,603
0.003487
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #-------------------------------------------------------------------...
self, value, detail=True): super(Interval, self).validate(value, detail) if not (value is None or self.interval_type.is_valid(value) and value >= self.start and value <= self.end): msg = "" if not detail else "expected a value of type %s in range [%s, %s], got %r" % (self.interval_type, sel...
lues (0-255). Example: .. code-block:: python >>> class ByteModel(HasProps): ... prop = Byte(default=0) ... >>> m = ByteModel() >>> m.prop = 255 >>> m.prop = 256 # ValueError !! >>> m.prop = 10.3 # ValueError !! ...
DataMonster/Python
exer/zipunzip/zip.py
Python
unlicense
1,230
0.034959
def zip(*arg): Result = [] Check = 1 #check if every item in arg has the same length for i in arg: if len(i) != len(arg[0]): print 'please make sure enter all items with the same length' Check = 0 break while (Check): for j in range(0,len(arg[0])):...
len(LIST)): LIST[j].append(item[j]) for k in LIST: result = result + (k,) return result def Test(): p
rint '#1 test: ' print ' zip([1,1,1],[2,2,2],[3,3,3],[4,4,4]) -->', zip([1,1,1],[2,2,2],[3,3,3],[4,4,4]) print '\n' print ' unzip([(1,2,3,4,5),(2,3,4,5,6),(3,4,5,6,7)]) -->', unzip([(1,2,3,4,5),(2,3,4,5,6),(3,4,5,6,7)]) print '\n' print '#2 test: unzip(zip([100,200,300],[200,300,400],[0,0,0]))' ...
skybon/obozrenie
obozrenie/launch_gtk.py
Python
gpl-3.0
1,061
0
#!/usr/bin/env python3 # This source file is part of Obozrenie # Copyright 2015 Artem Vorotnikov # For more information, see https://github.com/obozrenie/obozrenie # Obozrenie is free s
oftware: you can redist
ribute it and/or modify # it under the terms of the GNU General Public License version 3, as # published by the Free Software Foundation. # Obozrenie 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 PARTICULAR PURPOSE...
robocomp/learnbot
learnbot_dsl/Clients/Devices/JointMotor.py
Python
gpl-3.0
379
0
cla
ss JointMotor(): def __init__(self, _callDevice, _readDevice): self._callDevice = _callDevice self._readDevice = _readDevice self._angle = 0 def sendAngle(self, _angle): self._callDevice(_angle) self._angle = _angle def getAngle(self): return self._angle ...
self._readDevice()
houssemFat/bloodOn
bloodon/accounts/social/providers/oauth2/client.py
Python
mit
2,095
0.000955
try: from urllib.parse import parse_qsl, urlencode except ImportError: from urllib import urlencode from urlparse import parse_qsl import requests class OAuth2Error(Exception): pass class OAuth2Client(object): def __init__(self, request, consumer_key, consumer_secret, access_tok...
, callback_url, scope): self.request = request self.access_token_url = access_token_url self.callback_url = callback_url self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.scope = ' '.j
oin(scope) self.state = None def get_redirect_url(self, authorization_url, extra_params): params = { 'client_id': self.consumer_key, 'redirect_uri': self.callback_url, 'scope': self.scope, 'response_type': 'code' } if self.state: ...
interlegis/saap
saap/core/migrations/0019_auto_20180921_1540.py
Python
gpl-3.0
943
0.002123
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-09-21 18:40 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.
deletion import smart_selects.db_fields class Mi
gration(migrations.Migration): dependencies = [ ('core', '0018_auto_20180921_1539'), ] operations = [ migrations.AddField( model_name='distrito', name='estado', field=models.ForeignKey(default=21, on_delete=django.db.models.deletion.CASCADE, to='core.Est...
albertoferna/compmech
compmech/conecyl/clpt/setup_clpt_bc1.py
Python
bsd-3-clause
472
0.021186
from distutils.core import setup from distutils.extension import Extension from Cython.Distut
ils import build_ext args_linear = ['/openmp', '/O2', '/favor:INTEL64'] args_nonlinear = ['/openmp', '/O2', '/favor:INTEL64', '/fp:fast'] ext_modules = [ Extension('clpt_commons_bc1', ['clpt_co
mmons_bc1.pyx'], extra_compile_args=args_linear, )] setup( name = 'clpt_bc1', cmdclass = {'build_ext': build_ext}, ext_modules = ext_modules )
kafana/ubik
lib/ubik/rug/cli.py
Python
gpl-3.0
2,912
0.002747
#!/usr/bin/python # # Copyright 2012 Lee Verberne <lee@blarg.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # #...
hat.run() except ubik.hats.HatException as e: print >>sys.stderr, "ERROR:", str(e) if op
tions.debug: raise e return 1 else: print >>sys.stderr, "ERROR: No such command" return 2 if __name__ == '__main__': sys.exit(main())
code-disaster/fips
mod/tools/cmake.py
Python
mit
4,302
0.009298
"""wrapper for cmake tool""" import subprocess from subprocess import PIPE import platform from mod import log,util from mod.tools import ninja name = 'cmake' platforms = ['linux', 'osx', 'win'] optional = False not_found = 'please install cmake 2.8 or newer' #--------------------------------------------------------...
if cmake is in the path and has the required version :returns: True if cmake found and is the required version """ try: out = subprocess.che
ck_output(['cmake', '--version']).decode("utf-8") ver = out.split()[2].split('.') if int(ver[0]) > major or (int(ver[0]) == major and int(ver[1]) >= minor): return True else : log.info('{}NOTE{}: cmake must be at least version {}.{} (found: {}.{}.{})'.format( ...
googleapis/protoc-java-resource-names-plugin
plugin/templates/resource_name.py
Python
bsd-3-clause
13,100
0
# Copyright 2016 Google LLC # All rights reserved. # # 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...
er_list] self.format_string = collection_config.name_pattern def template_name(self): return "resource_name.mustache" class ParentResourceName(ResourceNameBase): def __init__(self, oneof, java_package, pattern_strings): super(ParentResourceName, self).__init__(
casing_utils.get_parent_resource_name_class_name( oneof.oneof_name), java_package) symbol_table = SymbolTable() pattern_to_id_segments = OrderedDict([ (p, get_id_segments(p)) for p in pattern_strings if not is_fixed_pattern(p)]) sel...
ric2b/Vivaldi-browser
update_notifier/thirdparty/wxWidgets/misc/scripts/png2c.py
Python
bsd-3-clause
3,184
0.005653
#!/usr/bin/python # This script is a slightly modified version of the original found at # # https://wiki.wxwidgets.org/Embedding_PNG_Images-Bin2c_In_Python # # without any copyright attribution so it is assumed it can be used under # wxWindows licence as the rest of the wiki material. import sys import os impor...
e in the image names in generated code.""" if len(sys.argv) < 2: print(USAGE) sys.exit(1) r = re.compile("^([a-zA-Z._][a-zA-Z._0-9]*)[.][pP][nN][gG]$") with_size = 0 size_suffix = '' for path in sys.argv[1:]: if path == '-s': with_size = 1 continue filename = ...
print("Skipped file (unsuitable filename): " + filename) continue # Read PNG file as character array bytes = array.array('B', open(path, "rb").read()) count = len(bytes) # Check that it's actually a PNG to avoid problems when loading it # later....
wiki-ai/revscoring
tests/languages/test_hungarian.py
Python
mit
3,830
0
import pickle from revscoring.datasources import revision_oriented from revscoring.dependencies import solve from revscoring.languages import hungarian from .util import compare_extraction BAD = [ "anyad", "anyád", "anyádat", "anyátok", "anyátokat", "apád", "asd", "balfasz", "basz...
ionary))) def test_stopwords(): cache = { revision_oriented.revision.text: 'játszótérnek még helyett park jól' } assert (solve(hungarian.stopwords.revision.datasources.stopwords, cache=cache) == ['még', 'jól']) assert (solve(hungarian.stopwords.revision.datasources.non_...
an.stopwords == pickle.loads( pickle.dumps(hungarian.stopwords))
indera/crossref-client
crossref-client.py
Python
mit
1,731
0
#!/usr/bin/env python """ crossref-client.py - Implement a tool for interaction with the api.crossref.org Usage: crossref-client.py -h | --help crossref-client.py [-c] Options: -h --help
Show the help message -c --count-publishers Display the number of publishers available [default:False] """ __author__ = "University of Florida CTS-IT Team" import json import requests from docopt import docopt from publisher import Publisher API_URL_MEMBERS...
s' def main(): args = docopt(__doc__, help=True) pub_count = count_publishers(API_URL_MEMBERS) if args['--count-publishers']: print("Total publishers @ {}: {}".format(API_URL_MEMBERS, pub_count)) else: print("List of {} publishers: ".format(pub_count)) groups = pub_count/1000...
RealOrangeOne/attack-on-blocks
target.py
Python
mit
3,542
0.009881
import pygame, logging from random import randint from game import generate_random_level class Target(pygame.sprite.Sprite): def __init__(self, x, y, textures, color=(30,0,150), width=23, height=23): super().__init__() self.width = width self.height = height self.textures = texture...
rect()
sprite_list[index].set_position(x,y, center=False) #Already Centered! changed = True for sprite in sprite_list: #Because sprite groups dont support indexing! group.add(sprite) return group
the-zebulan/CodeWars
katas/kyu_8/remove_exclamation_marks.py
Python
mit
63
0
def remove_
exclamation_marks(s): return s.replace
('!', '')
tinloaf/home-assistant
homeassistant/components/input_boolean.py
Python
apache-2.0
3,609
0
""" Component to keep track of user controlled booleans for within automation. For more details about this component, please refer to the documentation at https://home-assistant.io/components/input_boolean/ """ import logging import voluptuous as vol from homeassistant.const import ( ATTR_ENTITY_ID, CONF_ICON, C...
self): """Return name of the boolean input.""" return self._name @property
def icon(self): """Return the icon to be used for this entity.""" return self._icon @property def is_on(self): """Return true if entity is on.""" return self._state async def async_added_to_hass(self): """Call when entity about to be added to hass.""" # If ...
wmalinowski/test-example
testexample/test/test_example_app.py
Python
unlicense
442
0.002262
import tornado.testing from testexample import ExampleApp class TestExampleApp(tornado.testing.AsyncHT
TPTestCase, tornado.testing.LogTrapTestCase): def get_app(self): return ExampleApp() def test_home(self): response = self.fetch('/') self.assertEqual(response.code, 200) def test_ticker(self):
response = self.fetch('/ticker') self.assertEqual(response.code, 200)
cangencer/hazelcast-python-client
hazelcast/protocol/codec/map_execute_on_all_keys_codec.py
Python
apache-2.0
1,451
0.002068
from hazelcast.ser
ialization.bits import * from hazelcast.protocol.client_message import ClientMessage from haze
lcast.protocol.custom_codec import * from hazelcast.util import ImmutableLazyDataList from hazelcast.protocol.codec.map_message_type import * REQUEST_TYPE = MAP_EXECUTEONALLKEYS RESPONSE_TYPE = 117 RETRYABLE = False def calculate_size(name, entry_processor): """ Calculates the request payload size""" data_si...
justanr/flask-allows
src/flask_allows/additional.py
Python
mit
5,469
0.000549
from contextlib import contextmanager from functools import wraps from werkzeug.local import LocalProxy, LocalStack _additional_ctx_stack = LocalStack() __all__ = ("current_additions", "Additional", "AdditionalManager") @LocalProxy def current_additions(): """ Proxy to the currently added requirements ...
quirements = set(requirements) def add(self, requirement, *requirements): self._requirements.update((requiremen
t,) + requirements) def remove(self, requirement, *requirements): self._requirements.difference_update((requirement,) + requirements) @_isinstance def __add__(self, other): requirements = self._requirements | other._requirements return Additional(*requirements) @_isinstance ...
openstack/networking-arista
networking_arista/tests/unit/ml2/security_groups/sg_test_base.py
Python
apache-2.0
3,145
0
# Copyright (c) 2018 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
{'direction': direction, 'ethertype': ethertype, 'protocol': proto, 'remote_ip_prefix': cidr, 'port_range_min': range_min, 'port_range_max': range_max, 'security_group_id': sg_id, 'remote...
ant_id': 't1'}} rule = self.plugin.create_security_group_rule(self.context, rule) return sg_id, rule