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
garimamalhotra/davitpy
pydarn/proc/music/__init__.py
Python
gpl-3.0
678
0.00885
# Waver module __init__.
py """ ******************************* WAVER ******************************* This subpackage contains various utilities for WAVER, the SuperDARN Wave Analysis Software Package. DEV: functions/modules/classes with a * have not been developed yet ******************************* """ #import sigio from music ...
t * # # # ************************************************************* # Define a few general-use constants # Mean Earth radius [km] Re = 6371.0 # Polar Earth radius [km] RePol = 6378.1370 # Equatorial Earth radius [km] ReEqu = 6,356.7523
PritishC/nereid
trytond_nereid/party.py
Python
gpl-3.0
12,239
0.000163
# This file is part of Tryton. The COPYRIGHT file at the top level of # this repository contains the full copyright notices and license terms. import warnings from flask_wtf import Form from wtforms import TextField, IntegerField, SelectField, validators from werkzeug import redirect, abort from jinja2 import Template...
orm = RegistrationForm @classmethod def __register__(cls, module_name): pool = Pool() Party = pool.get('party.party') Con
tactMechanism = pool.get('party.contact_mechanism') TableHandler = backend.get('TableHandler') cursor = Transaction().cursor table = TableHandler(cursor, cls, module_name) party = Party.__table__() address = cls.__table__() mechanism = ContactMechanism.__table__() ...
CenterForOpenScience/waterbutler
tests/providers/osfstorage/test_exceptions.py
Python
apache-2.0
803
0.007472
import pytest from waterbutler.providers.osfstorage.exceptions import OsfStorageQuotaExceededError class TestExceptionSerialization: @pytest.mark.parametrize( 'exception_class', [(OsfStorageQuotaExceededError),] ) def test_tolerate_dumb_signature(self, exception_class): """In orde...
n as exc: pytest.fail(str(exc)) assert isinstance(i_live_bu
t_why, exception_class)
bolkedebruin/airflow
airflow/providers/google/cloud/hooks/kubernetes_engine.py
Python
apache-2.0
10,778
0.002227
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
key: The key label :param val: :return: The cluster proto updated with new label """ val = val.replace('.', '-').replace('+', '-') cluster_proto.resource_labels.update({key: val}) return cluster_proto @GoogleBaseHook.fallbac
k_to_default_project_id def delete_cluster( self, name: str, project_id: str = PROVIDE_PROJECT_ID, retry: Retry = DEFAULT, timeout: float = DEFAULT, ) -> Optional[str]: """ Deletes the cluster, including the Kubernetes endpoint and all worker nodes...
habibutsu/rc-car
rc_car/vechicle.py
Python
mit
3,174
0
import asyncio import logging import os import signal from collections import defaultdict import aiohttp.web from aiohttp_index import IndexMiddleware logger = logging.getLogger('rc-car.vechicle') class Vechicle: DEFAULT_CFG = {} de
f __init__(self, cfg=None, loop=None): self.loop = loop or asyncio.get_event_loop() self.cfg = cfg if self.cfg.model.use_mock: logger.info('Use mock-factory...')
os.environ['GPIOZERO_PIN_FACTORY'] = 'mock' from gpiozero.pins.mock import MockPWMPin from gpiozero import Device Device.pin_factory.pin_class = MockPWMPin self.commands = defaultdict(list) self.sensors = defaultdict(list) self.parameters = default...
LouisPlisso/analysis_tools
latex_directory_1_2.py
Python
gpl-3.0
5,070
0.002959
#!/usr/bin/env python "Module to aggregate all pdf figures of a directory \ into a single latex file, and compile it." from __future__ import division, print_function import os import sys import re from optparse import OptionParser _VERSION = '1.0' def latex_dir(outfile_name, directory, column=2, eps=False): "Pr...
OGNAME').capitalize(), 'include_pdf_package_option': '' if eps else '[pdftex]'}) files = os.listdir(os.getcwd() + '/' + directory) # exclude_filename = outfile.name.split('/'
)[-1].replace('.tex', '.pdf') exclude_filename = 'latex_dir_' pattern = re.compile(r'(?!%s)\S+\.%s' % (exclude_filename, ('eps' if eps else 'pdf'))) count = 0 if column == 1: line_size = .99 elif column == 2: ...
pubnative/redash
tests/handlers/test_authentication.py
Python
bsd-2-clause
2,213
0.003163
from tests import BaseTestCase import mock import time from redash.models import User from redash.authentication.account
import invite_token from tests.handlers import get_request, post_request class TestInvite(BaseTestCase): def test_expired_invite_token(self): with mock.patch('time.time') as patched_time: patched_time.return_value = time.time() - (7 * 24 * 3600) - 10 token = invite_token(self.fac...
elf.assertEqual(response.status_code, 400) def test_invalid_invite_token(self): response = get_request('/invite/badtoken', org=self.factory.org) self.assertEqual(response.status_code, 400) def test_valid_token(self): token = invite_token(self.factory.user) response = get_reques...
hmrc/service-manager
test/it/test_actions.py
Python
apache-2.0
11,909
0.002015
from servicemanager.actions import actions from servicemanager.smcontext import SmApplication, SmContext, ServiceManagerException from servicemanager.smprocess import SmProcess from servicemanager.service.smplayservice import SmPlayService from servicemanager.serviceresolver import ServiceResolver import pytest from ...
ion, None, False, False) service_resolver = ServiceResolver(sm_application) context.kill_everything(True) self.startFakeNexus() servicetostart = ["PLAY_NEXUS_END_TO_END_TEST"] appendArgs = {"PLAY_NEXUS_END_TO_END_TEST": ["-DFoo=Bar"]} fatJar = True r
elease = False proxy = None port = None seconds_to_wait = None actions.start_and_wait( service_resolver, context, servicetostart, False, fatJar, release, proxy, port, seconds_to_wait, appendArgs, ) service = SmPlayService(context, "PLAY_NEXUS_END_TO_END_TEST"...
fnzv/Boafi
BoafiPenTest.py
Python
mit
12,450
0.020484
#!/usr/bin/python # -*- coding: utf-8 -*- ########## boafi Pentest script ########## - Perform various pentests automatically and save reports for further study ########## - Features/TODOs: Ipv6,DHCP,DNS,NTP,exploits,mitm.. ########## - Router bruteforce for easy guessable passwords ########## - Scan networks hosts and...
rgument('-mitmAll', action='store', dest='mitmall', default="none", help='Perform MITM Attack on all hosts') parser.add_argument('-stop-mitm', action='store_true', dest='stopmitm', default=
False, help='Stop any Running MITM Attack') parser.add_argument('-denyTcp', action='store', dest='denytcp', default="none", help='Deny tcp connections of given host') parser.add_argument('--dg', action='store', dest='dg', default="none", help='Perform MITM A...
mbudiu-vmw/hiero
data/metadata/differential-privacy/data/ontime_private/gen_metadata.py
Python
apache-2.0
3,456
0.005498
#!/usr/bin/env python3 # Copyright (c) 2020 VMware Inc. All Rights Reserved. # SPDX-License-Identifier: Apache-2.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.ap...
0) elif cn == "DepDelay" or cn == "ArrDelay": (g, gMin, gMax) = (1, -100, 10
00) elif cn == "Cancelled": (g, gMin, gMax) = (1, 0, 1) elif cn == "ActualElapsedTime": (g, gMin, gMax) = (1, 15, 800) elif cn == "Distance": (g, gMin, gMax) = (10, 0, 5100) elif cn == "FlightDate": # cluster values: (86400000, 852076800000, 1561852800000) # 2017 ...
thehub/hubplus
scripts/patch_ref_creator_field.py
Python
gpl-3.0
267
0.011236
from apps.plus_permissions.default_
agents import get_admin_user from apps.plus_permissions.models import GenericReference def
patch(): for ref in GenericReference.objects.filter(creator=None): ref.creator = get_admin_user() ref.save() patch()
aronsky/home-assistant
homeassistant/components/hassio/websocket_api.py
Python
apache-2.0
3,538
0
"""Websocekt API handlers for the hassio integration.""" import logging import voluptuous as vol from homeassistant.components import websocket_api from homeassistant.components.websocket_api.connection import ActiveConnection from homeassistant.core import HomeAssistant, callback import homeassistant.helpers.config_...
timeout=msg.get(ATTR_TIMEOUT, 10), payload=msg.get(ATTR_DATA, {}), ) if result.get(ATTR_RESULT) == "error": raise hass.components.hassio.HassioAPIError(result.get("message")) except hass.components.hassio.HassioAPIError as err: _LOGGER.error("Failed to to call %...
sage=str(err) ) else: connection.send_result(msg[WS_ID], result.get(ATTR_DATA, {}))
bokeh/bokeh
tests/unit/bokeh/protocol/test_receiver.py
Python
bsd-3-clause
5,417
0.00683
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #-------------------------------------------------------------------...
with_multiple_bu
ffers() -> None: r = receiver.Receiver(proto) for N in range(10): partial = await r.consume(f'{{"msgtype": "PATCH-DOC", "msgid": "10", "num_buffers":{N}}}') partial = await r.consume('{}') partial = await r.consume('{"bar": 10}') for i in range(N): partial = await r...
atheendra/access_keys
keystone/token/providers/uuid.py
Python
apache-2.0
929
0
# Copyright 2013 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 in...
from keystone.token.providers import common class Provider(common.BaseProvider): def
__init__(self, *args, **kwargs): super(Provider, self).__init__(*args, **kwargs) def _get_token_id(self, token_data): return uuid.uuid4().hex
rybesh/pybtex
pybtex/backends/html.py
Python
mit
2,255
0.002661
# Copyright (c) 2008, 2009, 2010, 2011 Andrey Golovizin # # 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...
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from xml.sax.saxutils import escape from pybtex.backends import BaseBackend import pybt
ex.io file_extension = 'html' PROLOGUE = u"""<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html> <head><meta name="generator" content="Pybtex"> <meta http-equiv="Content-Type" content="text/html; charset=%s"> <title>Bibliography</title> </head> <body> <dl> """ class Backend(BaseBackend): name = 'html' ...
hkjallbring/pusher-http-python
pusher/util.py
Python
mit
1,209
0.014888
# -*- coding: utf-8 -*- from __future__ import (print_function, unicode_literals, absolute_import, division) import json import re import six import sys channel_name_re = re.compile('\A[-a-zA-Z0-9_=@,.;
]+\Z') app_id_re = re.compile('\A[0-9]+\Z') pusher_url_re = re.compile('\A(http|https)://(.*):(.*)@(.*)/apps/([0-9]+)\Z') socket_id_re = re.compile('\A\d+\.\d+\Z') if sys.version_info < (3,): text = 'a unicode string' else: text = 'a string' def ensure_text(obj, name): if isinstance(obj, six.te...
n obj if isinstance(obj, six.string_types): return six.text_type(obj) raise TypeError("%s should be %s" % (name, text)) def validate_channel(channel): channel = ensure_text(channel, "channel") if len(channel) > 200: raise ValueError("Channel too long: %s" % channel) if not channel_...
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-3.2/Lib/test/test_sys.py
Python
mit
32,006
0.001843
import unittest, test.support import sys, io, os import struct import subprocess import textwrap import warnings import operator import codecs # count the number of test runs, used to create unique # strings to intern in test_intern() numruns = 0 try: import threading except ImportError: threading = None cla...
self.assertTrue(not hasattr(builtins, "_")) dh(42) self.assertEqual(out.getvalue(), "42\n") self.assertEqu
al(builtins._, 42) del sys.stdout self.assertRaises(RuntimeError, dh, 42) def test_lost_displayhook(self): del sys.displayhook code = compile("42", "<string>", "single") self.assertRaises(RuntimeError, eval, code) def test_custom_displayhook(self): def baddispl...
nkripper/pynet
week1/json_intro_read.py
Python
apache-2.0
111
0.018018
#!/us
r/bin/python im
port json with open("test_json.json","r") as f: new_list = json.load(f) print new_list
mbareta/edx-platform-ft
lms/djangoapps/ccx/migrations/0009_auto_20170608_0525.py
Python
agpl-3.0
735
0.002721
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import datetime class Migration(migrations.Migration): d
ependencies = [ ('ccx', '0008_auto_20170523_0630'),
] operations = [ migrations.AlterField( model_name='customcourseforedx', name='delivery_mode', field=models.CharField(default=b'IN_PERSON', max_length=255, choices=[(b'IN_PERSON', b'In Person'), (b'ONLINE_ONLY', b'Online')]), ), migrations.AlterField( ...
sosey/ginga
ginga/misc/Datasrc.py
Python
bsd-3-clause
3,565
0.001964
# # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # import threading class TimeoutError(Exception): pass class Datasrc(object): def __init__(self, length=0): ...
if not self.newdata.isSet():
raise TimeoutError("Timed out waiting for datum") self.newdata.clear() return self.history[-1] def get_bufsize(self): with self.cond: return self.length def set_bufsize(self, length): with self.cond: self.length = length self._eje...
allure-framework/allure-python
allure-pytest/test/acceptance/attachment/attachment_step_test.py
Python
apache-2.0
622
0
""" ./examples/attachment/attachment_step.rst """ from hamcrest import assert_that from allure_commons_test.report i
mport has_test_case from allure_commons_test.result import has_step from allure_commons_test.result import has_attachment def test_step_with_attachment(executed_docstring_path): assert_that(executed_docstring_path.allure_report, has_test_case("test_step_with_attachment", ...
("step_with_attachment", has_attachment() ), ) )
keflavich/agpy
agpy/showspec.py
Python
mit
51,670
0.020302
""" showspec is my homegrown spectrum plotter, meant to somewhat follow STARLINK's SPLAT and have functionality similar to GAIA, but with an emphasis on producing publication-quality plots (which, while splat may do, it does unreproducibly) .. todo:: -add spectrum arithmetic tools (as is, you can use nump...
t these keywords passed to splat_1d MAY crop the spectrum) units - units of th
e data. At the moment, no conversions are done xunits - units of the Y axis. Can affect other procedures, like show_lines, and some unit conversion (Hz to GHz) is done erralpha - Transparency of the errorbars if plotted errstyle - style of errorbars if plotted plotpix - if ...
hupf/passwordchest
src/loxodo/twofish/twofish_ecb.py
Python
gpl-2.0
2,538
0.003546
# # Loxodo -- Password Safe V3 compatible Password Vault # Copyright (C) 2008 Christoph Sommer <mail@christoph-sommer.de> # # 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 ...
ions...." __testenc = "Passing nonsense through crypt-API, will then do assertion check" __testdec = "\x71\xbf\x8a\xc5\x8f\x6c\x2d\xce\x9d\xdb\x85\x82\x5b\x25\xe3\x8d\xd8\x59\x86\x34\x28\x7b\x58\x06\xca\x42\x3d\xab\xb7\xee\x56\x6f\xd3\x90\xd6\x96\xd5\x94\x8c\x70\x38\x05\xf8\xdf\x92\xa4\x06\x2f\x32\x7f\xbd\xd7\x...
estdec) == __testenc test_twofish_ecb()
nycholas/ask-undrgz
src/ask-undrgz/django/core/serializers/xml_serializer.py
Python
bsd-3-clause
11,755
0.003063
""" XML serializer. """ from django.conf import settings from django.core.serializers import base from django.db import models, DEFAULT_DB_ALIAS from django.utils.xmlutils import SimplerXMLGenerator from django.utils.encoding import smart_unicode from xml.dom import pulldom class Serializer(base.Serializer): """ ...
his is saved as # {m2m_accessor_attribute : [list_of_related_objects]}) m2m_data = {} # Deseralize each field. for field_node in node.getElementsByTagName("field"): # If the field is missing the name attribute, bail (are you # sensing a pattern here?) ...
name = field_node.getAttribute("name") if not field_name: raise base.DeserializationError("<field> node is missing the 'name' attribute") # Get the field from the Model. This will raise a # FieldDoesNotExist if, well, the field doesn't exist, which will #...
lukeebhert/python_crash_course
Chapter_3/dinner_guests.py
Python
gpl-3.0
740
0.005405
invites = ['Queen Elizabeth II', 'Prince Philip','Duchess Kate','Prince William'] hell
o = "Your majesty " message = ", you are invited to the Royal Dinner Party. \n- King George" rsvp_qe = hello + invites[0] + message rsvp_pp = hello + invites[1] + message rsvp_dk = hello + invites[2] + message rsvp_pw = hello + invites[3] + message print(rsvp_qe) print(rsvp_pp) print(rsvp_dk) print(rsvp_pw) # Prince P...
we are inviting Princess Margaret print('\n' + invites[1] + ' cannot make it to the dinner') invites[1] = 'Princess Margaret' rsvp_pm = hello + invites[1] + message print('\n' + rsvp_qe) print(rsvp_pm) print(rsvp_dk) print(rsvp_pw) print("\nThere are " + str(len(invites)) + " people invited to dinner.")
eomahony/Numberjack
tests/SolverTests.py
Python
lgpl-2.1
32,022
0.02339
''' Numberjack is a constraint satisfaction and optimisation library Copyright (C) 2009 Cork Constraint Computation Center, UCC This program 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; eith...
def bc_prop(obj): vars = obj.get_variables() if vars[0].get_is_instantiated() and vars[0].get_value() == 1: obj.fail() bc.rt_propogate = bc_prop model.add_constraint(bc) solver = Solver(model) assert(s...
2, var3 = (Variable(list(range(0,3))) for x in range(0,3)) model = NativeModel() model.add_variable((var1, var2, var3)) model.add_constraint(Geq((var1, var2))) model.add_constraint(Geq((var2, var3))) model.add_constraint(Geq((var1, var3))) solver = Solve...
portfoliome/postpy
postpy/base.py
Python
mit
4,942
0
from collections import namedtuple from foil.formatters import format_repr from postpy.ddl import ( compile_column, compile_qualified_name, compile_primary_key, compile_create_table, compile_create_temporary_table ) __all__ = ('Database', 'Schema', 'Table', 'Column', 'PrimaryKey', 'View') class Database: ...
(primary_key.column_names) columns = [column for column in table.columns if column.name in key_names] table = Table(name, columns, primary_key) return table def split_qualified_name(qualified_name: str, schema='public'): if '.' in qualified_name: schema, table = qualified_name.split('.') ...
le column(s) and primary key columns by specified order.""" unordered_columns = table.column_names index_order = (unordered_columns.index(name) for name in column_names) ordered_columns = [table.columns[i] for i in index_order] ordered_pkey_names = [column for column in column_names ...
uberVU/mongo-oplogreplay
oplogreplay/__init__.py
Python
mit
39
0.025641
from oplogreplayer import O
plogRe
player
keybar/keybar
src/keybar/tests/test_client.py
Python
bsd-3-clause
4,080
0.001225
import os import pytest import requests from keybar.client import TLS12SSLAdapter from keybar.tests.helpers import LiveServerTest from keybar.tests.factories.user import UserFactory from keybar.tests.factories.device import ( AuthorizedDeviceFactory, PRIVATE_KEY, PRIVATE_KEY2) from keybar.utils.http import Insecu...
est_under_downgrade_attack_to_ssl_3(self, allow_offline): """ Verify that the connection is rej
ected if the remote server (or man in the middle) claims that SSLv3 is the best supported protocol. """ url = 'https://ssl3.zmap.io/sslv3test.js' assert verify_rejected_ssl(url) def test_protocols_by_ssl_labs(self, allow_offline): session = requests.Session() session...
chandu-atina/User-Management
rfxapp/models.py
Python
mit
893
0.006719
from django.db import models from django.utils import timezone import datetime # Create your models
here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): # __unicode__ on Python 2 return self.question_text def was_published_recently(self): return self.pub_date >= time...
_recently.boolean = True was_published_recently.short_description = 'Published recently?' class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): # __unicode__ on Pyt...
QingChenmsft/azure-cli
src/azure-cli-core/azure/cli/core/tests/test_command_registration.py
Python
mit
15,404
0.003635
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
:type vm_name: str :param opt_param: Used to verify reflection correctly identifies optional params. :type opt_param: object :param expand: The expand expression to apply on the operation. :type expand: str :param dict custom_headers: headers that will be added to t...
ide the deserialized response :rtype: VirtualMachine :rtype: msrest.pipeline.ClientRawResponse if raw=True """ pass def test_register_cli_argument(self): command_table.clear() cli_command(None, 'test register sample-vm-get', '{}#Test_comm...
nil0x42/phpsploit
plugins/system/whoami/plugin.py
Python
gpl-3.0
371
0
"""Print effectiv
e userid SYNOPSIS: whoami DESCRIPTION: Print the user name associated with current remote server access rights. * PASSIVE PLUGIN: No requests are sent to server, as current user is known by $USER environment variable (`env USER`); AUTHOR: nil0x42 <http://goo.gl/kb2wf> """ from api impor...
print(environ['USER'])
nbi-opendata/metadaten-scraper
get-metadata.py
Python
mit
3,412
0.003224
import json, io, re, requests from bs4 import BeautifulSoup from datetime import datetime def get_datasets(url): r = requests.get(url.format(0)) soup = BeautifulSoup(r.text) href = soup.select('#block-system-main a')[-1]['href'] last_page = int(re.match(r'.*page=(.*)', href).group(1)) for page in...
'] = 'dataset' m['_title'] = t a
ll_metadata.append(m) for k in m.keys(): all_labels.add(k) print(json.dumps(m, sort_keys=1, ensure_ascii=False)) done_datasets.add(d) # iterate over all document urls for d, t in get_datasets(documents_url): if d in done_datasets: print('skip', d) continu...
PMBio/limix
External/nlopt/test/test_std.py
Python
apache-2.0
727
0
# #!/usr/bin/env python # # import nlopt # THIS IS NOT A PACKAGE! # import num
py as np # # print(('nlopt version='+nlopt.__version__)) # # def f(x, grad): # F=x[0] # L=x[1] # E=x[2] # I=x[3] # D=F*L**3/(3.*E*I) # return D # # n = 4 # opt = nlopt.opt(nlopt.LN_COBYLA, n) # opt.set_min_objective(f) # lb = np.array([40., 50., 30e3, 1.]) # ub = np.array([60., 60., 40e3, 10.]) ...
er_bounds(lb) # opt.set_upper_bounds(ub) # opt.set_xtol_rel(1e-3) # opt.set_ftol_rel(1e-3) # xopt = opt.optimize(x) # # opt_val = opt.last_optimum_value() # result = opt.last_optimize_result() # print(('opt_result='+str(result))) # print(('optimizer='+str(xopt))) # print(('opt_val='+str(opt_val)))
rfancn/wxgigo
wxgigo/wxmp/sdk/plugin/fshelper.py
Python
mit
5,556
0.00324
#!/usr/bin/env python # coding=utf-8 """ Copyright (C) 2010-2013, Ryan Fan <ryan.fan@oracle.com> 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 opti...
t plugin name to lowercased one module_path = "{0}.plugin".format(plugin_name.lower()) cls = load_class(module_path, WXMP_PLUGIN_CLASS_NAME) if not issubclass(cls, BasePlugin): print "Object: {
0} is not a subclass of BasePlugin".format(cls) return None except Exception,e: raise e return cls def fs_get_plugin_config_class(self, plugin_name): """ Dynamically retrieve plugin class from filesystem @param plugin_name: plugin name, it is ...
mpdevilleres/tbpc_app
tbpc/resource_mgt/utils.py
Python
mit
5,806
0.002756
#!/usr/bin/env python import copy import datetime as dt import re from decimal import Decimal, InvalidOperation from openpyxl import * from openpyxl.cell import Cell from openpyxl.utils import get_column_letter from openpyxl.worksheet import Worksheet # OPENPYXL WITH INSERT ROW # ----------------------------------...
row += cnt if row > row_idx else 0 return m.group('col') + prefix + str(row) # First, we shift all cells down cnt rows... old_cells = set() old_fas = set(
) new_cells = dict() new_fas = dict() for c in self._cells.values(): old_coor = c.coordinate # Shift all references to anything below row_idx if c.data_type == Cell.TYPE_FORMULA: c.value = CELL_RE.sub( replace, c.value ) ...
kenorb-contrib/BitTorrent
twisted/test/test_task.py
Python
gpl-3.0
6,793
0.004122
# Copyright (c) 2001-2004 Twisted Matrix Laboratories. # See LICENSE for details. from twisted.trial import unittest from twisted.internet import task, reactor, defer from twisted.python import failure class TestableLoopingCall(task.LoopingCall): def __init__(self, clock, *a, **kw): super(TestableLoopi...
eLater, d) return d def _callback_for_testStopAtOnceLater(self, d): self._lc.stop() reactor.callLater(0, d.callback, "success") def testWaitDeferred(self):
# Tests if the callable isn't scheduled again before the returned # deferred has fired. timings = [0.2, 0.8] clock = Clock() def foo(): d = defer.Deferred() d.addCallback(lambda _: lc.stop()) clock.callLater(1, d.callback, None) retu...
gnovis/swift
swift_fca/swift_core/object_fca.py
Python
gpl-3.0
131
0
class Object: def __init__(self, name): self._name = nam
e @property def name(self): return self._name
yourcelf/btb
scanblog/accounts/views.py
Python
agpl-3.0
2,880
0.002431
""" This app is a simple extension of built in auth_views which overrides login and logout to provide messages on successful login/out. """ from django.contrib.auth import views as auth_views from django.utils.translation import ugettext as _ from django.core.exceptions import PermissionDenied from django.core.urlreso...
sponse def change_password(request, user_id): """ Change the password of the user with the given user_id. Checks for permission to change users. """ if not can_edit_user(request.user, user_id): raise PermissionDenied if request.user.id ==
int(user_id): Form = PasswordChangeForm else: Form = SetPasswordForm user = User.objects.get(id=user_id) if request.POST: form = Form(user, request.POST) if form.is_valid(): form.save() messages.success(request, _("Password changed successfully.")) ...
codeka/wwmmo
website/handlers/blog.py
Python
mit
1,074
0.015829
import datetime from flask import abort, render_template, request, redirect, Response import ctrl.blog from . import handlers @handlers.route('/blog') def blog_index(): pageNo = 0 if request.args.get('page'): pageNo = int(request.args.get('page')) if pageNo < 0: pageNo = 0 posts = ctrl.blog.getP...
= ctrl.blog.getPostBySlug(int(year), int(month), slug) if not post: abort(404) return render_template('blog/post.html', post=post) @handlers.route('/blog/rss') def blog_rss(): posts = ctrl.blog.getPosts(0, 15) pubDate = datetime.time() if posts and len(posts) > 0: pubDate = posts[0].posted retu...
pubDate=pubDate.strftime('%a, %d %b %Y %H:%M:%S GMT')), content_type='application/rss+xml')
sheeshmohsin/venturesity
flexy/flexy/settings.py
Python
mit
5,241
0.000763
# Django settings for flexy project. import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django_mongodb_engine', 'NAME': 'sheesh', ...
oject.com/en/dev/ref/settings/#media-url MEDIA_URL = '/media/' # END MEDIA CONFIGURATION # Absolute path to the directory static files should be collected to. # Don't put anything in this directory
yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/var/www/example.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://example.com/static/", "http://static.example.com/" STATIC_URL = '/static/' # Additional locations of static files...
florian-f/sklearn
benchmarks/bench_sgd_regression.py
Python
bsd-3-clause
4,512
0.002216
""" Benchmark for SGD regression Compares SGD regression against coordinate descent and Ridge on synthetik data. """ print(__doc__) # Author: Peter Prettenhofer <peter.prettenhofer@gmail.com> # License: BSD Style. import numpy as np import pylab as pl import gc from time import time from sklearn.linear_model imp...
tstart = time() clf.fit(X_train, y_train) ridge_results[i, j, 0] = mean_squared_error(clf.predict(X_test),
y_test) ridge_results[i, j, 1] = time() - tstart # Plot results i = 0 m = len(list_n_features) pl.figure(figsize=(5 * 2, 4 * m)) for j in range(m): pl.subplot(m, 2, i + 1) pl.plot(list_n_samples, np.sqrt(elnet_results[:, j, 0]), ...
srijannnd/Login-and-Register-App-in-Django
simplesocial/posts/models.py
Python
mit
984
0.003049
from django.db import models from django.core.urlresolvers import reverse from django.conf import settings import misaka from groups.models import Group # Create your models here. # POSTS MODELS.PY from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): user = models.Fo...
ts', null=True, blank=True) def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = misaka.html(self.message) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('posts:single', kwargs={'username': self.user.username...
pk': self.pk}) class Meta: ordering = ['-created_at'] unique_together = ['user', 'message']
google/google-ctf
third_party/edk2/BaseTools/Source/Python/GenFds/CompressSection.py
Python
apache-2.0
3,896
0.009497
## @file # process compress section generation # # Copyright (c)
2007 - 2017, Intel Corporation. All rights reserved.<BR> # # This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which
accompanies this distribution. The full text of the license may be found at # http://opensource.org/licenses/bsd-license.php # # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. # ## # Import Modules # fr...
JaySon-Huang/WebModel
WebModel/database/databasehelper.py
Python
mit
4,676
0.032
# -*- coding: utf-8 -*- import sqlite3 VERBOSE = 0 CTABLE_DOMAIN = ''' CREATE TABLE IF NOT EXISTS Domains( did INTEGER PRIMARY KEY AUTOINCREMENT, domain VARCHAR(64) UNIQUE, indegree INTEGER, outdegree INTEGER )''' CTABLE_WEBSITE = ''' CREATE TABLE IF NOT EXISTS Websites( wid INTEGER PRIMARY KEY AUTOINCREMENT, ...
sertDomain('jaysonhwang.com') # dbcli.insertRuleset('test','jaysonhwang.com') print dbcli.robotsrulesetOfDomain('www.zol.com') print dbcli.robotsrulesetOfDomain('jayson
.com') dbcli.showAll() dbcli.close() if __name__ == '__main__': test()
artefactual/archivematica-history
src/MCPClient/lib/clientScripts/archivematicaClamscan.py
Python
agpl-3.0
2,652
0.003771
#!/usr/bin/python -OO # This file is part of Archivematica. # # Copyright 2010-2012 Artefactual Systems Inc. <http://artefactual.com> # # Archivematica 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, e...
vematica # @subpackage archivematicaClientScript # @author Joseph Perry <joseph@artefactual.com> # @version svn: $Id$ #source /etc/archivematica
/archivematicaConfig.conf import os import sys sys.path.append("/usr/lib/archivematica/archivematicaCommon") from executeOrRunSubProcess import executeOrRun from databaseFunctions import insertIntoEvents from archivematicaFunctions import escapeForCommand clamscanResultShouldBe="Infected files: 0" if __name__ == '__m...
sinomiko/project
python_project/python/PythonProj/ReadWriteFile.py
Python
bsd-3-clause
1,234
0.028363
outfile=open("helloworld.txt","w") for num1 in range(1,10): for num2 in range(1,10): if num2<=num1 : outfile.write("{}*{}={} ".format(num2, num1 ,num1 * num2)) outfi
le.write(" \n") outfile.flush() outfile.close() infile=open("helloworld.txt","r") for line in
infile.readlines(): print line infile.close() import sys sys.stdout.write("foo\n") sys.stderr.write("foo2 \n") def test_var_kwargs(farg, **kwargs): print "formal arg:", farg for key in kwargs: print "arg: {}:{}".format(key, kwargs[key]) test_var_kwargs(2,a="sd",b="ds") def return_stuff(var): ...
newhavenrc/nhrc2
tests/test_get_neighborhoods.py
Python
mit
1,060
0.007547
#!/usr/bin/env python """ PURPOSE: The routines in this file test the get_neighborhoods module. Created on 2015-04-02T21:24:17 """ from __future__ import division, print_function #import numpy as np #from types import * #from nose.tools import raises #import pandas as pd import nhrc2.backend.read_seeclickfix_api_to...
the number of issues. def test_get_neighborhoods(): """ Ensure the number in the hood list length = the number of issues """ scf_cats = rscf.read_categories(readfile=True) issues = rscf.read_issues(scf_cats, readfile=True) hoods = get_ngbrhd.get_neighborhoods() assert len(issues) == len(ho...
r) #def test_make_function_raise_value_error():
jackwluo/py-quantmod
quantmod/ta.py
Python
mit
33,467
0
"""Wrappers around Ta-Lib technical indicators Python native indicators in 'tanolib.py' file. """ import numpy as np import pandas as pd import talib from . import utils from .valid import VALID_TA_KWARGS # Overlap studies def add_MA(self, timeperiod=20, matype=0, type='line', color='secondary', **kwa...
raise Exception() utils.kwargs_check(kwargs, VALID_TA_KWARGS) if 'kind' in kwargs: kwargs['type'] = kwargs['kind'] if 'kinds' in kwargs: types = kwargs['type'] if 'type' in kwargs: types = [kwargs['type']] * 2 if 'color' in kwargs:
colors = [kwargs['color']] * 2 mama = 'MAMA({},{})'.format(str(fastlimit), str(slowlimit)) fama = 'FAMA({},{})'.format(str(fastlimit), str(slowlimit)) self.pri[mama] = dict(type=types[0], color=colors[0]) self.pri[fama] = dict(type=types[1], color=colors[1]) self.ind[mama], self.ind[fama] = tali...
andychase/classwork
cs496/assignment_3/test.py
Python
mit
2,361
0.000424
import json import uuid import unittest from main import app from app import redis class FlaskTestCase(unittest.TestCase): def setUp(self): app.config['TESTING'] = True self.app = app.test_client() self.site_host = str(uuid.uuid4()) def tearDown(self): pass # self.delete_site...
self.app.delete('/mag/delete', data={ 'site': self.site_host, 'mag_id': 1 })
self.assertDictEqual(self.get_site_data(), { 'mags': [], 'ok': True }) def test_move_magnet(self): self.make_site() self.app.put( '/mag/move', data=dict(site=self.site_host, mag_id=1, x=10, y=10) ) self.assertDictEqual(s...
cwtaylor/viper
viper/core/ui/console.py
Python
bsd-3-clause
9,307
0.002256
# This file is part of Viper - https://github.com/viper-framework/viper # See the file 'LICENSE' for copying permission. import os from os.path import expanduser import sys import glob import atexit import readline import traceback from viper.common.out import print_error, print_outpu
t from viper.common.colors import cyan, magenta, white, bold, blue from viper.core.session import __sessions__ from viper.core.plugins import __modules__ from viper.core.project import __project__ from viper.core.ui.commands import Commands from viper.core.database import Database from viper.core.config import Config, ...
pass def logo(): print(""" _ (_) _ _ _ ____ _____ ____ | | | | | _ \| ___ |/ ___) \ V /| | |_| | ____| | \_/ |_| __/|_____)_| v1.3-dev |_| """) db = Database() count = db.get_sample_count() try: db.find('all') except: print_error("...
blutjens/perc_neuron_ros_ur10
pn_ros/bjorn_ws/devel/lib/python2.7/dist-packages/rosserial_msgs/msg/_TopicInfo.py
Python
gpl-3.0
7,843
0.021293
"""autogenerated by genpy from rosserial_msgs/TopicInfo.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class TopicInfo(genpy.Message): _md5sum = "0ad51f88fc44892f8c10684077646005" _type = "rosserial_msgs/TopicInfo" _has_header = False #flag to...
struct.pack('<I%sB'%length, length, *_x)) else: buff.write(struct.pack('<I
%ss'%length, length, _x)) _x = self.md5sum length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) if python3: buff.write(struct.pack('<I%sB'%length, length, *_x)) else: buff.write(struct.pack('<I%ss'%length, length, _x))...
berdario/mutagen
mutagen/asf.py
Python
gpl-2.0
21,198
0.000849
# Copyright 2006-2007 Lukas Lalinsky # Copyright 2005-2006 Joe Wreschnig # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # $Id: asf.py 4224 2007-12-03 09:01:49Z luks $ """Read and...
-8 strings, or a single Unicode or UTF-8 string. """ if no
t isinstance(values, list): values = [values] try: del(self[key]) except KeyError: pass for value in values: if key in _standard_attribute_names: value = text_type(value) elif not isinstance(value, ASFBaseAttribute): if isinstan...
ergonomica/ergonomica
tests/stdlib/test_help.py
Python
gpl-2.0
375
0.010667
#!/usr/bin/env python # -*- coding: utf-8 -*- """ [tests/stdlib/test_help.py] Test the help command. """ im
port u
nittest #import os #from ergonomica import ergo, ENV class TestHelp(unittest.TestCase): """Tests the 'help' command.""" def test_list_commands(self): """ Tests listing all commands using the 'help commands' command. """
SOM-st/PySOM
src/som/primitives/true_primitives.py
Python
mit
1,649
0.003032
from som.interp_type import is_ast_interpreter from som.primitives.primitives import Primitives from som.vm.globals import trueObject, falseObject, nilObject from som.vmobjects.primitive import UnaryPrimitive, BinaryPrimitive, TernaryPrimitive if is_ast_interpreter(): from som.vmobjects.block_ast import AstBlock a...
tive(BinaryPrimitive("or:", _or)) self._install_instance_primitive(BinaryPrimitive("||", _or))
self._install_instance_primitive(BinaryPrimitive("and:", _and_and_if_true)) self._install_instance_primitive(BinaryPrimitive("&&", _and_and_if_true)) self._install_instance_primitive(BinaryPrimitive("ifTrue:", _and_and_if_true)) self._install_instance_primitive(BinaryPrimitive("ifFalse:...
wikimedia/integration-zuul
tests/base.py
Python
apache-2.0
52,328
0.000191
#!/usr/bin/env python # Copyright 2012 Hewlett-Packard Development Company, L.P. # # 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 # # Unles...
fn = '%s-%s' % (self.branch.replace('/', '_'), self.number) msg = self.subject + '-' + str(self.latest_patchset) c = self.add_fake_change_to_repo(msg, fn, large) ps_files = [{'file': '/COMMIT_MSG',
'type': 'ADDED'}, {'file': 'README', 'type': 'MODIFIED'}] for f in files: ps_files.append({'file': f, 'type': 'ADDED'}) d = {'approvals': [], 'createdOn': time.time(), 'files': ps_files, 'number...
dgschwend/hls_OO
TESTDATA_MAXI/data/classify.py
Python
gpl-3.0
14,639
0.012637
#!/usr/bin/env python2 # Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved. """ Classify an image using individual model files Use this script as an example to build your own tool """ import argparse import os import time import struct from google.protobuf import text_format import numpy as np impor...
utput:\n", net.blobs['conv10'].data #print "pool10 output:", pool10avg scores = np.copy(output) end = time.t
ime() print 'Inference took %f seconds ...' % (end - start) return scores def read_labels(labels_file): """ Returns a list of strings Arguments: labels_file -- path to a .txt file """ if not labels_file: return None labels = [] with open(labels_file) as infile: ...
mgp/bittorrent-dissected
Rerequester.py
Python
mit
9,039
0.006195
# Written by Bram Cohen # see LICENSE.txt for license information from zurllib import urlopen, quote from btformats import check_peers from bencode import bdecode from threading import Thread, Lock from socket import error, gethostbyname from time import time from random import randrange from binascii import b2a_hex ...
# If not the first request, append the id this tracker previously returned. s += '&trackerid=' + quote(str(
self.trackerid)) if self.howmany() >= self.maxpeers: # Don't need any more peers to connect to. s += '&numwant=0' else: # Return peer IP and port addresses in 6 binary bytes. s += '&compact=1' # Event is not specified if this request is one perform...
miho030/FoxVc
versions - 1.2.x/FoxVc Ver 1.2.7/Foxcore/matchingHashValue.py
Python
gpl-3.0
1,103
0.024679
# -*- coding: utf-8 -*- # Author : Repubic of Korea, Seoul, JungSan HS 31227 Lee Joon Sung # Author_Helper : Republic of Korea, KyungGido, Kim Min Seok # youtube : anonymous0korea0@gmail.com ;;;; tayaka # Email : miho0_0@naver.com import hashlib import logging #from FoxDBinfor import DB_Pattern def M...
ION.append(fname) # INFECTION 리스트에 추가함. return 1 return 0 except IOError as e:
logger.error("IOError : Permission denied. / No such file or directory.") logger.error(e.message) finally: pass
devs1991/test_edx_docmode
venv/lib/python2.7/site-packages/ipware/__init__.py
Python
agpl-3.0
93
0
# -*- c
oding: utf-8 -*- __version__ = '1.1.0' default_app_config = 'ipware.apps.App
Config'
ntuhpc/modulefiles
all/hide.py
Python
mit
413
0
impo
rt os root_dir = os.path.dirname(os.path.realpath(__file__)) f = open(".modulerc", "w") f.write("#%Module\n") sub_dirs = os.walk(root_dir) next(sub_dirs) for dir_name, _, file_list in sub_dirs: for file_name in file_list: module_version = file_name.rstrip("
.lua") module_name = os.path.relpath(dir_name, root_dir) f.write("hide-version %s/%s\n" % (module_name, module_version))
goldsborough/ecstasy
docs/source/conf.py
Python
mit
9,617
0.005303
# -*- coding: utf-8 -*- # # ecstasy documentation build configuration file, created by # sphinx-quickstart on Wed Aug 5 21:42:49 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # A...
ue # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated....
dex = 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 footer. Default is True. #html_show_copyright = True # If...
jtannas/NOA
app/mod_auth/__init__.py
Python
mit
613
0.001631
''' Initiation procedure for the auth module Yields: -
Initiates the Login Manager ''' # --------------------------------------------------------------------------- # Imports # --------------------------------------------------------------------------- from flask_login import LoginManager from .. import app # -------------------------------------------------------------...
er = LoginManager() login_manager.login_view = "auth.signin" login_manager.init_app(app)
andymitrich/pygask
application/views.py
Python
mit
88
0.011364
from flask import render_template def home(): return re
nder_temp
late('index.html')
MilyMilo/sci-organizer
agenda/migrations/0001_initial.py
Python
mit
1,029
0.002915
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-09 10:54 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('groups', '0001_initial'), ] op...
[ migrations.CreateModel( name='Event', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', mo
dels.CharField(max_length=30)), ('description', models.TextField()), ('subject', models.CharField(max_length=20)), ('event_type', models.CharField(choices=[('quiz', 'Quiz'), ('test', 'Test'), ('homework', 'Homework')], max_length=8)), ('due', models.DateTi...
muLAn-project/muLAn
muLAn/models/fhexaBL.py
Python
mit
2,911
0.003435
# -*-coding:Utf-8 -* # ==================================================================== # ==================================================================== # Packages # ==================================================================== import sys import numpy as np from muLAn.models.multipole import hexamag...
, dalpha, ds, t, tb) ### Parallax DsN = Ds['N']
DsE = Ds['E'] tau = (t-t0)/tE + piEN * DsN + piEE * DsE beta = u0 + piEN * DsE - piEE * DsN x, y = binrot(alpha, tau, beta) ### Conversion center of mass to Cassan (2008) x = x - s*q/(1.+q) ### Compute magnification zeta0 = x + 1j*y return np.array([hexamag(s[i], q, rho, gamma, zeta0[i]) for i...
samuelclay/NewsBlur
vendor/oauth2client/django_orm.py
Python
mit
4,342
0.008521
# Copyright (C) 2010 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 writ...
: """Write a Credentials to the datastore. Args: credentials: Credentials, the credentials to store. """ args = {self.key_name: self.key_value} entity = sel
f.model_class(**args) setattr(entity, self.property_name, credentials) entity.save() def locked_delete(self): """Delete Credentials from the datastore.""" query = {self.key_name: self.key_value} entities = self.model_class.objects.filter(**query).delete()
ikreymer/pywb
pywb/manager/aclmanager.py
Python
gpl-3.0
10,869
0.001012
import os import re import sys from pywb.manager.manager import CollectionsManager from pywb.utils.canonicalize import canonicalize from pywb.warcserver.access_checker import AccessChecker from pywb.warcserver.index.cdxobject import CDXObject # ========================================================================...
self.rules.insert(i, acl) self.save_acl() def validate_save(self, r=None, log=False): """Validates the acl rules and saves the file
:param argparse.Namespace|None r: Not used :param bool log: Should a report be printed to stdout :rtype: None """ self.validate(log=log, correct=True) def validate(self, log=False, correct=False): """Validates the acl rules returning T/F if the list should be saved ...
ruchee/vimrc
vimfiles/bundle/vim-python/submodules/pylint/tests/functional/c/condition_evals_to_constant.py
Python
mit
1,666
0.001801
"""Test that boolean conditions simplify to a constant value""" # pylint: disable=pointless-statement from unknown import Unknown # pylint: disable=import-error def func(_): """Pointless function""" CONSTANT = 100 OTHER = 200 # Simplifies any boolean expression that is coerced into a True/False value bool(CON...
CONSTANT or True else 2 # [condition-evals-to-constant] z = [x for x in range(10) if x or True] # [condition
-evals-to-constant] # Simplifies recursively assert True or CONSTANT or OTHER # [condition-evals-to-constant] assert (CONSTANT or True) or (CONSTANT or True) # [condition-evals-to-constant] # Will try to infer the truthiness of an expression as long as it doesn't contain any variables assert 3 + 4 or CONSTANT # [c...
rootio/rootio_web
alembic/versions/31d36774c549_first_and_second_sim.py
Python
agpl-3.0
673
0.007429
"""split gsm signal in two analytics, one per sim card Revision ID: 31d36774c549 Revises: 528f90a47515 Create Date: 2019-01-23 15:16:58.514742 """ # revision identifiers, used by Alembic. revision = '31d36774c549' down_revision = '528f90a47515' from alemb
ic import op import sqlalchemy as sa def upgrade(): op.alter_column('radio_stationanalytic', 'gsm_signal', new_
column_name='gsm_signal_1') op.add_column('radio_stationanalytic', sa.Column('gsm_signal_2', sa.Integer(), nullable=True)) def downgrade(): op.alter_column('radio_stationanalytic', 'gsm_signal_1', new_column_name='gsm_signal') op.drop_column('radio_stationanalytic', 'gsm_signal_2')
pafluxa/todsynth
build/lib.linux-x86_64-2.7/todsynth/calibration/calibrator.py
Python
gpl-3.0
2,810
0.025267
import todsynth import os import numpy import json import pandas class Calibrator( object ): ''' A todsynth.calibrator object is a container that stores coefficients that transform RAW dac units to physical units for a given TOD. ''' # Calibrator description. #00000000000000000000000000...
lType = caltype self.description = '' # Load file calDF = pandas.read_csv( systemPath, header=0, names=['coefficients', 'uid'], delimiter=' ' ) self.setCoeffs( calDF['coefficients'], uid = ca
lDF['uid'] ) return self
DMSC-Instrument-Data/lewis
src/lewis/core/devices.py
Python
gpl-3.0
19,330
0.004656
# -*- coding: utf-8 -*- # ********************************************************************* # lewis - a library for creating hardware device simulators # Copyright (C) 2016-2017 European Spallation Source ERIC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU G...
""" This module contains :class:`DeviceBase` as a base class for other device classes and infrastructure that can import devices from a module (:class:`DeviceRegistry`). The latter also produces factory-like objects that create device instances and interfaces based on setups (:class:`DeviceBuilder`). """ import import...
_submodules, get_members, is_compatible_with_framework @has_log class DeviceBase(object): """ This class is a common base for :class:`~lewis.devices.Device` and :class:`~lewis.devices.StateMachineDevice`. It is mainly used in the device discovery process. """ @has_log class InterfaceBase(object)...
JulyKikuAkita/PythonPrac
cs15211/SlidingWindowMedian.py
Python
apache-2.0
5,180
0.004826
__source__ = 'https://leetcode.com/problems/sliding-window-median/' # Time: O(n*logk) # Space: O() # # Description: 480. Sliding Window Median # # Median is the middle value in an ordered integer list. # If the size of the list is even, there is no middle value. # So the median is the mean of the two middle value. # #...
e1Over(minHeap, maxHeap, minHeapSize, maxHeapSize); } else if(minHeapSize[0] < minHeapCap){ move1Over(maxHeap, minHeap, maxHeapSize, minHeapSize); } res[resIdx] = getMedian(maxHeap, minHeap, maxHeapSize, minHeapSize); resIdx++; } ...
ger, Integer> smallHeap, int[] bigHeapSize, int[] smallHeapSize){ return bigHeapSize[0] > smallHeapSize[0] ? (double) bigHeap.keySet().iterator().next() : ((double) bigHeap.keySet().iterator().next() + (double) smallHeap.keySet().iterator().next()) / 2.0; } //move the top element of heap1 to heap2 ...
googleapis/python-data-fusion
google/cloud/data_fusion_v1/services/data_fusion/transports/base.py
Python
apache-2.0
8,521
0.001291
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
perations.""" raise NotImplementedError() @proper
ty def list_available_versions( self, ) -> Callable[ [datafusion.ListAvailableVersionsRequest], Union[ datafusion.ListAvailableVersionsResponse, Awaitable[datafusion.ListAvailableVersionsResponse], ], ]: raise NotImplementedError() @proper...
BoPeng/SOS
test/test_config.py
Python
gpl-3.0
5,574
0
#!/usr/bin/env python3 # # Copyright (c) Bo Peng and the University of Texas MD Anderson Cancer Center # Distributed under the terms of the 3-clause BSD License. import os import getpass import subprocess import pytest from sos import execute_workflow from sos._version import __version__ from sos.utils import env, loa...
'sos config --set cut1 0.5 2 3 -c {myconfig}', stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL, shell=Tr
ue) == 0 load_config_files(myconfig) assert env.sos_dict['CONFIG']['cut1'] == [0.5, 2, 3] # assert subprocess.call( f'sos config --set cut2 a3 -c {myconfig}', stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL, shell=True) == 0 load_config_files(myconfig) assert...
hackerpals/Python-Tutorials
Python-Intro-Workshops/Exceptions-handling/try.py
Python
gpl-3.0
890
0.001124
#!/usr/bin/python3 ''' TRY Exception SYNTAX ----------
------------------------------------------------------- try: You do your operations here; ...................... except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block. ...................... else: If there is no excepti...
ception handling!!") # except IOError: # print("Error: can\'t find file or read data") # else: # print("Written content in the file successfully") # fh.close() try: fh = open("testfile","r") fh.write("This is my test file for exception handling!!") except IOError: print("Error: cant\'t find fi...
mrmuxl/keops
keops/modules/project/models.py
Python
agpl-3.0
832
0
from django.ut
ils.translation import ugettext_lazy as _ from keops.db import models STATUS = ( ('draft', _('Draft')), ('open', _('In Progress')), ('pending', _('Pending')), ('don
e', _('Done')), ('cancelled', _('Cancelled')) ) class Category(models.Model): name = models.CharField(null=False, unique=True) class TaskType(models.Model): name = models.CharField(unique=True, null=False) description = models.TextField() status = models.CharField(max_length=16, choices=STATUS) ...
openstack/networking-nec
networking_nec/nwa/common/constants.py
Python
apache-2.0
877
0
# Copyright 2015-2016 NEC Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. NWA_DEVICE_GDV = "GeneralDev" NWA_DEVICE_TFW = "TenantFW" NWA_AGENT_TOPIC = 'nwa_agent' NWA_AGENT_TYPE = 'NEC
NWA Agent' NWA_FIREWALL_PLUGIN = 'NECNWAFWaaS' # an incremental size if the remaining size is zero. NWA_GREENPOOL_ADD_SIZE = 32
Ale-/grrr.tools
apps/views/glossary.py
Python
gpl-3.0
9,637
0.010611
from django.utils.translation import ugettext_lazy as _ def get(): """ Site glossary. """ return { 'construction' : [ { 'term' : _('Bienes'), 'text' : _('Objetos o cosas susceptibles de apropiación (art. 333 CC). Los bienes son de domino público o de propied...
entes colectividades (art. 1.1 LBRL).'), }, { 'term' : _('Oneroso'), 'text' : _('No gratuito, que exige alguna contraprestación.'), }, { 'term' : _('Valorización'), 'text' : _('Proceso para volver a hacer úti...
iduo producto de una construcción o demolición.'), }, { 'term' : _('Reutilizar'), 'text' : _('Emplear de manera útil un material simple o compuesto, utilizado anteriormente, con posibilidades de cambiar su uso, sus características o su ubicación.'), },...
johnwallace123/dx-toolkit
src/python/dxpy/bindings/dxapp.py
Python
apache-2.0
15,467
0.002069
# Copyright (C) 2013-2016 DNAnexus, Inc. # # This file is part of dx-toolkit (DNAnexus platform client libraries). # # 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.a...
n app with this name already exists) :type bill_to: string :param access: Access specification (optional) :type access: dict :param resources: Specifies what is to be p
ut into the app's resources container. Must be a string containing a project ID, or a list containing object IDs. (optional) :type resources: string or list .. note:: It is highly recommended that the higher-level module :mod:`dxpy.app_builder` or (preferably) its frontend `dx build --create...
ntt-sic/nova
nova/tests/consoleauth/test_consoleauth.py
Python
apache-2.0
7,413
0.001349
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack Foundation # Administrator of the National Aeronautics and Space Administration. # 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...
ntext, self.u_instance) class CellsConsoleauthTestCase(ConsoleauthTestCase): """Test Case for consoleauth w/ cells enabled.""" def setUp(self): super(CellsConsoleauthTestCase, self).setUp() self.flags(enable=True, group='cells') def _stub_validate_console_port(self, result): def ...
cells_rpcapi, 'validate_console_port', fake_validate_console_port)
infobloxopen/infoblox-netmri
infoblox_netmri/api/broker/v3_8_0/issue_detail_broker.py
Python
apache-2.0
78,423
0.002193
from ..broker import Broker class IssueDetailBroker(Broker): controller = "issue_details" def show(self, **kwargs): """Shows the details for the specified issue detail. **Inputs** | ``api version min:`` None | ``api version max:`` None | ``required...
various ways to query lists, using this method is most efficient. **Inputs** | ``api version min:`` 2.3 | ``api version max:`` 2.4 | ``required:`` False | ``default:`` None :param BatchID:
The internal NetMRI identifier for the job execution batch to which this issue applies, if relevant. :type BatchID: Integer | ``api version min:`` 2.5 | ``api version max:`` None | ``required:`` False | ``default:`` None :param BatchID: Th...
tensorflow/gan
tensorflow_gan/examples/mnist/infogan_eval.py
Python
apache-2.0
2,490
0.001606
# coding=utf-8 # Copyright 2022 The TensorFlow GAN Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the L
icense. # You may obtain a copy o
f the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific la...
iluxonchik/lyricist
lyricist/rapgenius/rgartist.py
Python
mit
5,427
0.006633
import re from bs4 import BeautifulSoup from ..const import constant from ..bsopener import BSOpener class RGArtist(object): """RapGeniusArtist""" class _Const(object): """ Contains constants used in outter class """ @constant def RG_ARTIST_BASE_URL(): return "http://genius...
ment with spaces replaced by "-" and "." removed. This method might return
a bogus url, since RapGenius doesn't seem to be following any convention for the names (for example, sometimes "." in names simply get removed, while in other instances they get replaced by "-"). """ return RGArtist(cls._Const().RG_ARTIST_BASE_URL + artist_name.replace(" ", "-")....
heineman/algorithms-nutshell-2ed
PythonCode/test/__init__.py
Python
mit
199
0.025126
__all__ = ["test_avl
", "test_binary", "test_bloom", "test_fortune", "test_hashtable", "test_kd", "test_kd_factory", "test_knapsack", "test_mergesor
t", "test_quad", "test_R"]
jwir3/transgression
src/transgression/test/test_config.py
Python
mpl-2.0
4,338
0.011296
import os import sys sys.path.insert(0,os.path.abspath(__file__+"/../..")) import unittest import json from transgression import config class ConfigTest(unittest.TestCase): def setUp(self): self.mJsonString = open(os.path.abspath(os.path.dirname(os.path.realpath(__file__))+"/data/testConfig.json"), 'r').read() ...
ectedPlatConfigOutput, config.PlatformConfigurationEncoder.encode(platConfig)) self.assertEquals(expectedPlatConfigOutput, json.dumps(platConfig, cls=config.PlatformConfigurationEncoder)) expectedAppConfigOutput = "{ 'Jingit': { 'platformConfigurations' : { " + expectedPlatConfigOutput + "}}}" self.assertE...
tedAppConfigOutput, config.ApplicationConfigEncoder.encode(app)) self.assertEquals(expectedAppConfigOutput, json.dumps(app, cls=config.ApplicationConfigEncoder)) expectedConfigOutput = "{ '__type__' : 'transgression-configuration', 'applications' : " + expectedAppConfigOutput + "}}" self.assertEquals(expec...
gkc1000/pyscf
pyscf/pbc/tdscf/test/test_rhf_slow.py
Python
apache-2.0
3,697
0.000541
from pyscf.pbc.gto import Cell from pyscf.pbc.scf import RHF from pyscf.pbc.tdscf import TDHF from pyscf.pbc.tdscf.rhf_slow import PhysERI, PhysERI4, PhysERI8, TDRHF from pyscf.tdscf.common_slow import eig from test_common import retrieve_m, retrieve_m_hf, assert_vectors_close import unittest from numpy import testin...
3.370137329, 0.000000000, 3.370137329 3.370137329, 3.370137329, 0.000000000''' cell.unit = 'B' cell.verbose = 5 cell.build() cls.model_rhf = model
_rhf = RHF(cell) model_rhf.kernel() cls.td_model_rhf = td_model_rhf = TDHF(model_rhf) td_model_rhf.nroots = 5 td_model_rhf.kernel() cls.ref_m_rhf = retrieve_m(td_model_rhf) @classmethod def tearDownClass(cls): # These are here to remove temporary files ...
nmayorov/scipy
scipy/_lib/_util.py
Python
bsd-3-clause
16,576
0.000241
import functools import operator import sys import warnings import numbers from collections import namedtuple from multiprocessing import Pool import inspect import math import numpy as np try: from numpy.random import Generator as Generator except ImportError: class Generator(): # type: ignore[no-redef] ...
5.]) >>> a = -np.ones_like(x) >>> _lazyselect([x < 3, x > 3], ... [lambda x, a: x**2, lambda x, a: a * x**3], ... (x, a), default=np.nan) array([ 0., 1., 4., nan, -64., -125.]) """ arrays = np.broadcast_arrays(*arrays) tcode = np.mintypecode([a.dtype....
t[index], condlist[index] if np.all(cond is False): continue cond, _ = np.broadcast_arrays(cond, arrays[0]) temp = tuple(np.extract(cond, arr) for arr in arrays) np.place(out, cond, func(*temp)) return out def _aligned_zeros(shape, dtype=float, order="C", align=None): ...
schleichdi2/OPENNFR-6.1-CORE
opennfr-openembedded-core/meta/lib/oeqa/selftest/oelib/buildhistory.py
Python
gpl-2.0
3,191
0.01943
import os import unittest import tempfile from git import Repo from oeqa.utils.commands import get_bb_var from oe.buildhistory_analysis import blob_to_dict, compare_dict_blobs class TestBlobParsing(unittest.TestCase): def setUp(self): import time self.repo_path = tempfile.mkdtemp(prefix='selftest-...
epo.git.add("--all") self.repo.git.commit(message=msg) def test_blob_to_dict(self): """ Test convertion of git blobs to dictionary """ valuesmap = { "foo" : "1", "bar" : "2" } self.commit_vars(to_add = valuesmap) blob = self.repo.head.commit.tree.blobs[0] ...
def test_compare_dict_blobs(self): """ Test comparisson of dictionaries extracted from git blobs """ changesmap = { "foo-2" : ("2", "8"), "bar" : ("","4"), "bar-2" : ("","5")} self.commit_vars(to_add = { "foo" : "1", "foo-2" : "2", "foo-3" : "3" }) blob1 = self.repo....
spottradingllc/zoom
server/zoom/www/messages/timing_estimate.py
Python
gpl-2.0
855
0
import json from zoom.common.types import UpdateType class TimeEstimateMessage(object): def __init__(self): self._message_type = UpdateType.TIMING_UPDATE self._contents = dict() @property def message_type(self): return self._message_type @property def contents(self): ...
f._contents.update(message.contents) def clear(self): self._contents.clear() def to_j
son(self): _dict = {} _dict.update({ "update_type": self._message_type, }) _dict.update(self.contents) return json.dumps(_dict)
shichao-an/ctci
chapter4/question4.1.py
Python
bsd-2-clause
1,025
0
from __future__ import print_function from tree import create_tree def get_height(root): if root is None: return 0 return max(get_height(root.left), get_height(root.right)) + 1 def is_balanced(root): """O(n^2)""" if root is None: return True lb = is_balanced(root.left) rb = i...
t(root.left) - get_height(root.right)) <= 1 return lb and rb and tb def get_height2(root): """Get height and check whether balanced""" if root is None: return 0 lh = get_height2(root.left) rh = get_height2(root.right) if lh != -1 and rh != -1: if abs(lh - rh) <= 1: ...
_test(): pass def _print(): a1 = [1, None, 2, 3] t1 = create_tree(a1) a2 = [1, 2, 3] t2 = create_tree(a2) print(is_balanced(t1)) print(is_balanced(t2)) if __name__ == '__main__': _test() _print()
yannickmartin/wellFARE
wellfare/ILM/fast_estimators.py
Python
lgpl-3.0
5,629
0.013857
""" This module implements fast estimators for the time-profiles of growth rate, promoter activity, and protein concentrations. These estimators rely on a simple model in which gene expression is modeled as a one-step process. This enables to compute the observation matrix directly using an ad-hoc formula. As a cons...
will appear smoothed compared to y. mod instance of sklearn.linear_model.RidgeCV, used for the Ridge regularization / cross-validation. Useful to get the value
of the parameter alpha used etc. """ if isinstance(curve_fluo, list): results = [ilp_synthesis_rate(f, v, ttu, degr, alphas=alphas, eps_L=eps_L) for f, v in zip(curve_fluo, curve_volume)] return zip(*results) if alphas is None: alphas = DEFAUL...
saltstack/salt
salt/modules/extfs.py
Python
apache-2.0
8,988
0.000111
""" Module for managing ext2/3/4 file systems """ import logging import salt.utils.platform log = logging.getLogger(__name__) def __virtual__(): """ Only work on POSIX-like systems """ if salt.utils.platform.is_windows(): return ( False, "The extfs execution module ...
= "Group {}".format(blkgrp) ret["
blocks"][group] = {} ret["blocks"][group]["group"] = blkgrp ret["blocks"][gro
lopiola/integracja_wypadki
scripts/statistics/speed_limit_exceeded_by_hour.py
Python
mit
817
0
#!/usr/bin/python # -*- coding: utf-8 -*- from scripts.db_api import accident def usa_query(hour): return ''' SELECT count(*), (select count(*) from accident join vehicle on(acc_id = accident.id) where country = 'USA' and vehicle.speed > accident.speed_limit and vehicle.speed > -1 and acciden...
e, dictionary): if age no
t in dictionary: return 0 return dictionary[age] if __name__ == '__main__': print('HOUR\tALL\tEXCEEDED') for i in xrange(0, 24): usa_count = accident.execute_query(usa_query(i)) print('{0}\t{1}\t{2}'.format(i, usa_count[0][0], usa_count[0][1]))
lantip/sms-komunitas
medkom/message/migrations/0001_initial.py
Python
gpl-3.0
1,783
0.002804
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('member', '0001_initial'), ] operations = [ migrations.CreateModel( name='Broadcast', fields=[ ...
dels.CharField(max_length=20)), ('phone', models.CharField(max_length=15)), ], ), migrations.CreateModel( name='Log', fields=[ (
'id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('date', models.DateTimeField()), ('message', models.CharField(max_length=200)), ('persons', models.ManyToManyField(to='member.Person')), ], ), mi...
torgartor21/solar
solar/solar/test/test_orm.py
Python
apache-2.0
15,583
0.000385
# Copyright 2015 Mirantis, 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 ...
ave(self): r = orm.DBResource(id='test1', name='test1', base_path='x')
r.save() rr = resource.load(r.id) self.assertEqual(r, rr.db_obj) def test_add_input(self): r = orm.DBResource(id='test1', name='test1', base_path='x') r.save() r.add_input('ip', 'str!', '10.0.0.2') self.assertEqual(len(r.inputs.as_set()), 1) def test_...
hongliang5623/sentry
src/sentry/api/endpoints/project_tagkey_values.py
Python
bsd-3-clause
1,277
0
from __future__ import absolute_import from sentry.api.base import DocSection from sentry.api.bases.project import ProjectEndpoint from sentry.api.exceptions import ResourceDoesNotExist from sentry.api.serializers import serialize
from sentry.models import TagKey, TagKeyStatus, TagVa
lue class ProjectTagKeyValuesEndpoint(ProjectEndpoint): doc_section = DocSection.PROJECTS def get(self, request, project, key): """ List a tag's values Return a list of values associated with this key. {method} {path} """ if key in ('release', 'user', 'f...
lahwaacz/wiki-scripts
ws/checkers/CheckerBase.py
Python
gpl-3.0
3,021
0.001655
#! /usr/bin/env python3 import contextlib import threading import mwparserfromhell import ws.ArchWiki.lang as lang from ws.utils import LazyProperty from ws.parser_helpers.title import canonicalize from ws.parser_helpers.wikicode import get_parent_wikicode, get_adjacent_node __all__ = ["get_edit_summary_tracker", "...
d finally: if text != str(wikicode): summary_parts.append(summary) return checker def localize_flag(wikicode, node,
template_name): """ If a ``node`` in ``wikicode`` is followed by a template with the same base name as ``template_name``, this function changes the adjacent template's name to ``template_name``. :param wikicode: a :py:class:`mwparserfromhell.wikicode.Wikicode` object :param node: a :py:class:`m...
brynpickering/calliope
calliope/backend/checks.py
Python
apache-2.0
6,761
0.002219
""" Copyright (C) 2013-2018 Calliope contributors listed in AUTHORS. Licensed under the Apache 2.0 License (see LICENSE file). run_checks.py ~~~~~~~~~~~~~ Checks for model consistency and possible errors when preparing run in the backend. """ import ruamel.yaml import numpy as np import pandas as pd import xarray a...
alues if (energy_cap is
not None and any(resource * resource_scale * resource_eff > energy_cap * energy_cap_scale * energy_eff)): errors.append( 'Operate mode: resource is forced to be higher than ' 'fixed energy cap for `{}`'.form...
kret0s/gnuhealth-live
tryton/server/trytond-3.8.3/trytond/modules/health_history/report/__init__.py
Python
gpl-3.0
66
0.015152
# -*- coding:
utf-8 -*-
from patient_evaluation_report import *