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 |
|---|---|---|---|---|---|---|---|---|
viranch/sam | setup.py | Python | bsd-2-clause | 495 | 0.038384 | #!/usr/bin/env python
from distutils.core import setup
import sys, shutil
def do(cmd):
if len(sys | .argv)<2: sys.argv.append(cmd)
else: sys.argv[1]=cmd
setup(
name='SAM',
version='1.0',
description='Cyberoam | Account Manager',
author='Viranch Mehta / Mohit Kothari',
author_email='viranch.mehta@gmail.com / mohitrajkothari@gmail.com',
url='http://www.butbucket.org/viranch/sam',
packages=['sam'],
scripts=['scripts/sam'],
)
do('build')
do('install')
shutil.rmtree('build')
|
RevansChen/online-judge | Codewars/6kyu/routes-in-a-square-grid/Python/test.py | Python | mit | 239 | 0.004184 | # Python - 2.7.6
test.assert_equals(routes(1), 2)
test.assert_equals(routes(2), 6)
test.assert_equals(routes(3), 20)
test.assert_equals(r | outes(4), 70)
test.assert_equals(routes(-4), 0, "If there are no squares there can't be any r | outes")
|
derekmoyes/opsy | opsy/db.py | Python | mit | 92 | 0 | from flask_sqla | lchemy import SQLAlchemy
db = SQLAlchemy() # pylint: | disable=invalid-name
|
Parallel-in-Time/pySDC | pySDC/playgrounds/other/petsc_datatype.py | Python | bsd-2-clause | 2,170 | 0.002304 | from petsc4py import PETSc
import numpy as np
class mymesh(PETSc.Vec):
__array_priority__ = 1000
def __new__(cls, init=None, val=0.0):
if isinstance(init, mymesh) or isinstance(init, PETSc.Vec):
obj = PETSc.Vec().__new__(cls)
init.copy(obj)
elif isinstance(init, PETSc.DM... | objarr = init.getVecArray(obj)
objarr[:] = val
else:
obj = PETSc.Vec().__new__(cls)
return obj
# def __rmul__(self, other):
# | print('here')
# tmp = self.getArray()
# tmp[:] *= other
# return self
def __abs__(self):
"""
Overloading the abs operator
Returns:
float: absolute maximum of all mesh values
"""
# take absolute values of the mesh values
# print(... |
eharney/cinder | cinder/volume/drivers/huawei/rest_client.py | Python | apache-2.0 | 88,507 | 0.000045 | # Copyright (c) 2016 Huawei Technologies Co., Ltd.
# 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
#
# ... | ""Send requests to server.
If fail, try another RestURL.
"""
device_id = None
old_url = self.url
result = self.do_call(url, data, method,
log_filter_flag=log_filter_flag)
error_code = result['error']['code']
if (error_code == constan... | t open the recent url, relogin.")
device_id = self.login()
if device_id is not None:
LOG.debug('Replace URL: \n'
'Old URL: %(old_url)s\n,'
'New URL: %(new_url)s\n.',
{'old_url': old_url,
'new_url': ... |
akatsoulas/mozillians | mozillians/phonebook/utils.py | Python | bsd-3-clause | 853 | 0 | import datetime
from mozillians.phonebook.models import Invite
from mozillians.users.models import IdpProfile
def redeem_invite(redeemer, code):
if code:
try:
invite = Invite.objects.get(code=code, redeemed=None)
voucher = invite.inviter
except Invite.DoesNotExist:
... | son)
invite.redeemed = datetime.datetime.now()
invite.redeemer = redeemer
invite.send_thanks()
invite.save()
def get_profile_link_by_email(ema | il):
try:
idp_profile = IdpProfile.objects.get(email=email, primary=True)
except (IdpProfile.DoesNotExist, IdpProfile.MultipleObjectsReturned):
return ''
else:
return idp_profile.profile.get_absolute_url()
|
cifvts/PyEuler | euler001.py | Python | mit | 185 | 0.005405 | #!/usr/bin/python
LIMIT = 999
|
def sumDivisibleBy(step):
p = LIMIT | // step
return step * (p * (p + 1)) // 2
print(sumDivisibleBy(3) + sumDivisibleBy(5) - sumDivisibleBy(15))
|
papercapp/django-feedmapper | feedmapper/admin.py | Python | bsd-3-clause | 963 | 0.002077 | from django.contrib import admin
from .models import Mapping
from .tasks import feedmapper_sync
def run_mapping(modeladmin, request, queryset):
"""
Initiates the `benchmarking` (TODO: ref required) of the selected epubs.
"""
for mapping in queryset.all():
feedmapper_sync.delay(mapping.id)
r... | ucceeded')
readonly_fields = ('parse_log',)
action | s = [run_mapping]
admin.site.register(Mapping, MappingAdmin)
|
ahaldane/numpy | tools/swig/test/testTensor.py | Python | bsd-3-clause | 16,439 | 0.003832 | #! /usr/bin/env python
from __future__ import division, absolute_import, print_function
# System imports
from distutils.util import get_platform
from math import sqrt
import os
import sys
import unittest
# Import NumPy
import numpy as np
major, minor = [ int(d) for d in np.__version__.split(".")[:2] ]
i... | ode)
self.assertRaises(TypeError, scale, tensor)
# Test (type INPLACE_ARRAY3[ANY][ANY][ANY]) typemap
def testScaleWrongSize(self):
"Test scale function with wrong size"
print(self.typeSt | r, "... ", end=' ', file=sys.stderr)
scale = Tensor.__dict__[self.typeStr + "Scale"]
tensor = np.array([[[1, 0], [0, 1], [1, 0]],
[[0, 1], [1, 0], [0, 1]],
[[1, 0], [0, 1], [1, 0]]], self.typeCode)
self.assertRaises(TypeError, scale, tensor)
... |
nielsbuwen/ilastik | ilastik/widgets/listView.py | Python | gpl-3.0 | 6,597 | 0.008792 | ###############################################################################
# ilastik: interactive learning and segmentation toolkit
#
# Copyright (C) 2011-2014, the ilastik developers
# <team@ilastik.org>
#
# This program is free software; you can redistribute it and/or
# mod... | click
:param modelIndex:
'''
# if (modelIndex.column() == self.model.C | olumnID.Delete and
# not self._table.model().flags(modelIndex) == Qt.NoItemFlags):
# self._table.model().removeRow(modelIndex.row())
#
def tableViewCellDoubleClicked(self, modelIndex):
'''
Reimplement this function to get interaction when single click
:param mode... |
daanwierstra/pybrain | docs/tutorials/learners.py | Python | bsd-3-clause | 5,000 | 0.011 | ############################################################################
# PyBrain Tutorial "Learners - Black Box Optimization"
#
# Author: Tom Schaul, tom@idsia.ch
############################################################################
__author__ = 'Tom Schaul, tom@idsia.ch'
""" A script that attempts to i... | be framed as a RL problem, we can use those algorithms: """
if isinstance(thetask, EpisodicTask):
print 'Episodic NAC', EpisodicRL(thetask, thenet).learn(maxEvals)
print 'REINFORCE', EpisodicRL(thetask, thenet,
sublearner = Reinforce).learn(maxEvals)
print 'Finite Differe... | rint 'SPLA', EpisodicRL(thetask, thenet, subagent = FiniteDifferenceAgent,
sublearner = SPLA).learn(maxEvals)
""" Evolutionary methods fall in the Learner framework as well.
All the following are examples.
Note that for all these we want network copies to be cheap, thus: """
thenet ... |
hazelcast/hazelcast-python-client | hazelcast/protocol/codec/list_get_codec.py | Python | apache-2.0 | 944 | 0.002119 | from hazelcast.serialization.bits import *
from hazelcast.protocol.builtin import FixSizedTypesCodec
from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer
from hazelcast.protocol.builtin import StringCodec
from hazelcast.protocol.builtin import DataCodec
from hazelcas... | l.builtin import CodecUtil
# hex: 0x050F00
_REQUEST_MESSAGE_TYPE = 331520
# hex: 0x050F01
_RESPONSE_MESSAGE_TYPE = 331521
_REQUEST_INDEX_OFFSET = REQUEST_HEADER_SIZE
_REQUEST_INITIAL_FRAME_SIZE = _REQUEST_INDEX_OFFSET + INT_SIZE_IN_BYTES
def encode_request(name, index):
buf = create_initial_buffer(_REQUEST_INIT... | TYPE)
FixSizedTypesCodec.encode_int(buf, _REQUEST_INDEX_OFFSET, index)
StringCodec.encode(buf, name, True)
return OutboundMessage(buf, True)
def decode_response(msg):
msg.next_frame()
return CodecUtil.decode_nullable(msg, DataCodec.decode)
|
DavidBarishev/DDtankFarmingBot | Ddtank_farm_bot/Framework/Clicking.py | Python | gpl-3.0 | 1,087 | 0.00184 | """This module is used to click on the screen"""
import logging
from time import sleep
import pyautogui
import Globals
import UI
log = logging.getLogger(__name__)
def click(x, y):
"""
Clicks left click one time
Args:
x (int): x to click
y (int): y to click
"""
log.debug("Clicki... | k_in_game_region_point(point):
"""
Clicks in game region
Args:
point (Tuple): (x,y) to click in
"""
click_in_game_region(point[0], point[1])
def move(x, y, duration=0.0):
pyautogui | .moveTo(x=x, y=y, duration=duration)
|
tensorflow/probability | tensorflow_probability/python/sts/default_model.py | Python | apache-2.0 | 6,799 | 0.001471 | # Copyright 2021 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | c default priors.
Default value: `tfp.sts.LocalLinearTrend`.
name: Python `str` name for ops created by this function.
Default value: `None` (i.e., 'build_default_model').
Returns:
model: instance of `tfp.sts.Sum` representing a model for the given data.
#### E | xample
Consider a series of eleven data points, covering a period of two weeks
with three missing days.
```python
import pandas as pd
import tensorflow as tf
import tensorflow_probability as tfp
series = pd.Series(
[100., 27., 92., 66., 51., 126., 113., 95., 48., 20., 59.,],
index=pd.to_datetim... |
fujicoin/fujicoin | test/functional/interface_http.py | Python | mit | 4,876 | 0.006153 | #!/usr/bin/env python3
# Copyright (c) 2014-2019 The Fujicoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the RPC HTTP basics."""
from test_framework.test_framework import FujicoinTestFramework
from tes... |
asse | rt_equal(out1.status, http.client.BAD_REQUEST)
if __name__ == '__main__':
HTTPBasicsTest ().main ()
|
dmsuehir/spark-tk | python/sparktk/dicom/dicom.py | Python | apache-2.0 | 10,173 | 0.002675 | # vim: set encoding=utf-8
# Copyright (c) 2016 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | metadata property is a sparktk frame which defines the metadata of the collection of DICOM objects.
Its schema has a column named "id" which holds a unique integer ID for the record and another column which
holds a string of XML comprised of the metadata. Users can run XQuery or invoke canned column extractio... | k frame which defines the pixeldata of the collection of DICOM objects.
Its schema has a column named "id" which holds a unique integer ID for the record and another column which
holds a matrix(internally it is a numpy.ndarray) comprised of the pixeldata. Users can run numpy supported transformations on it.
... |
arekfu/project_euler | p0016/p0016.py | Python | mit | 110 | 0.009091 | #!/usr/bin/env python3
def sum_digits(n):
return sum(int(d) for | d i | n str(n))
print(sum_digits(2**1000))
|
richbrowne/f5-openstack-agent | f5_openstack_agent/lbaasv2/drivers/bigip/test/test_lbaas_builder.py | Python | apache-2.0 | 86,393 | 0 | # coding=utf-8
# Copyright 2014-2016 F5 Networks Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | "id": "afdbfab4-de48-449c-86e8-7541ec9137bd"
},
| {
"id": "1d4590b8-c7e6-4e1b-bfa2-ec9b7d2d1905"
}
],
"loadbalancer_id": "990ba002-6eb2-40b6-9c63-f364b28a630b",
"name": "vs1",
"operating_status": "ONLINE",
"protocol": "HTTP",
"pro... |
dergraaf/xpcc | tools/device_files/device_identifier.py | Python | bsd-3-clause | 8,632 | 0.030468 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Copyright (c) 2014, Roboterclub Aachen e.V.
# All rights reserved.
#
# The file is part of the xpcc library and is released under the 3-clause BSD
# license. See the file `LICENSE` for the full license governing this code.
# ----------------------------------------------... | tring) >= 10:
self.pin_id = string[9]
if len(string) >= 11:
self.size_id = string[10]
if len(string) >= 9:
se | lf.valid = True
# AVR platform with AT90, ATtiny, ATmega and ATxmega family
elif string.startswith('at'):
self.platform = "avr"
matchString = "(?P<family>attiny|atmega|atxmega)(?P<name>\d+)"
if string.startswith('at90'):
matchString = "(?P<family>at90)(?P<type>CAN|can|PWM|pwm|USB|usb)(?P<name>\d+)[Bb]... |
voostar/hp_laserprinter_monitor | frontline/manage.py | Python | unlicense | 255 | 0 | #!/usr/bin/env python2.7
import os
import sys
if __name | __ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "frontline.settings")
from django.core.management import execute_from_command_line
execute_from | _command_line(sys.argv)
|
wkomor/pickthebook | book/admin.py | Python | apache-2.0 | 459 | 0.002179 | from dja | ngo.contrib import admin
from mptt.admin import MPTTModelAdmin
from .models import Item, Book, Genre
class ItemAdmin(MPTTModelAdmin):
list_display = ('text', 'itemtype', 'parent', 'slag')
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
li | st_display = ('title',)
list_fields = ('description', 'author', 'item')
@admin.register(Genre)
class Genre(admin.ModelAdmin):
fields = ['name']
admin.site.register(Item, ItemAdmin)
|
intelxed/xed | pysrc/actions_codegen.py | Python | apache-2.0 | 13,903 | 0.009279 | #BEGIN_LEGAL
#
#Copyright (c) 2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
#this is a mapping from a tuple to a lost of action_t objects
self.tuple2actions = self._preprocess(tuple2rule)
def _gather_all_fb(self, rules):
| ''' returns a tuple of:
(1) the super set of all the field binding
(2) the intersection of all the fb
'''
if len(rules) == 0:
return ([], [])
#create a bin of fbs, one entry per rule
fbs_bin = []
for rule in rules:
rule_fbs = set... |
pisiganesh/my_pisi_files | automake/actions.py | Python | gpl-2.0 | 1,210 | 0.004959 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Licensed under the GNU General Public License, version 3.
# See the file http://www.gnu.org/copyleft/gpl.txt
from pisi.actionsapi import autotools
from pisi.actionsapi import get
#from pisi.actionsapi import pisitools
# if pisi can't find source directory, see /var/pisi/aut... | README")
# If there is no install rule for a runnable binary, you can
# install it to binary directory.
# pisitools.dobin("automake")
# You can use these as variables, they will replace GUI values before build.
# Package Name : automake
# Version : 1.7.2
# Summary : Automake is a tool for automatically generating... | more information, you can look at the Actions API
# from the Help menu and toolbar.
# By PiSiDo 2.0.0
|
geraldoandradee/pagseguro_python_client | pagseguro_python_client/models.py | Python | gpl-2.0 | 6,611 | 0.00242 | #!/usr/bin/env python
# ! -*- coding:utf-8 -*-
from pagseguro_python_client.validators import ItemValidator
import inspect
import inflection
import json
class Base(object):
def underscore_to_camelcase(self, value, uppercase_first_letter=False):
return inflection.camelize(value, uppercase_first_letter)
... | nce=None, senderName=None,
senderAreaCode=None, senderPhone=None, senderEmail=None, shippingType=None, shippingAddressStreet=None,
shippingAddressNumber=None, shippingAddressComplement=None, shippingAddressDistrict | =None,
shippingAddressPostalCode=None, shippingAddressCity=None, shippingAddressState=None,
shippingAddressCountry=None):
self.email = email
self.token = token
self.currency = currency
self.items = [] if items is None else items
self.reference = ... |
dmlc/mxnet | example/sparse/linear_classification/train.py | Python | apache-2.0 | 5,849 | 0.002906 | # 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 u... | m, kvstore=kv)
# use accuracy as the metric
metric = mx.metric.create(['nll_loss'])
# get the sparse weight param | eter
speedometer = mx.callback.Speedometer(batch_size, 100)
logging.info('Training started ...')
for epoch in range(num_epoch):
nbatch = 0
metric.reset()
for batch in train_data:
nbatch += 1
# for distributed training, we need to manually pull sparse weights ... |
sutartmelson/girder | girder/utility/server.py | Python | apache-2.0 | 9,533 | 0.001573 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright Kitware Inc.
#
# Licensed under the Apache License, Version 2.0 ( the "License" );
# you may not use this file except in compliance with the License.
# You may obtain a copy of ... | :param curConfig: The config o | bject to update.
"""
pluginWebroots = plugin_utilities.getPluginWebroots()
girderWebroot, appconf = configureServer(test, plugins, curConfig)
routeTable = loadRouteTable(reconcileRoutes=True)
# Mount Girder
application = cherrypy.tree.mount(girderWebroot,
s... |
xiaoqiangwang/e4py | docs/source/conf.py | Python | bsd-3-clause | 9,747 | 0.000103 | # -*- coding: utf-8 -*-
#
# e4py documentation build configuration file, created by
# sphinx-quickstart on Sun Apr 16 21:21:18 2017.
#
# 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.
#
# All ... | opied after the builtin s | tatic files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['ystatic']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#
# html_extra_... |
vinoth3v/In | In/templates/html/Box.tpl.py | Python | apache-2.0 | 102 | 0.107843 | <s | ection <%= attributes %>>
<py if title: >
<%= title %>
</py>
<%= value %> <%= children %>
</section> | |
compas-dev/compas | src/compas/datastructures/network/__init__.py | Python | mit | 710 | 0 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import compas
from .o | perations import * # noqa: F401 F403
if not compas.IPY:
from .matrices import * # noqa: F401 F403
from .network import * # noqa: F401 F403
from .combinatorics import * # noqa: F401 F403
from .complementarity import * # noqa: F401 F403
from .duality import * # noqa: F401 F403
from .explode import * # noqa:... | om .traversal import * # noqa: F401 F403
__all__ = [name for name in dir() if not name.startswith('_')]
|
google/openhtf | test/core/test_record_test.py | Python | apache-2.0 | 931 | 0.005371 | # Lint as: python3
"""Unit tests for test_record module."""
import sys
import unittest
from openhtf.core import test_record
def _get_obj_size(obj):
size = 0
for attr in obj.__slots__: # pytype: disable=attribute-error
size += sys.getsizeof(attr)
size += sys.getsizeof(getattr(obj, attr))
return size
... | data, expected_data)
def test_attachment_memory_safety(self):
empty_attachment = test_record.Attachment(b'', 'text')
expected_obj_size = _get_obj_size(empty_attachment)
large_data = b'test attachment data' * 1000
attachment = test_record.Attachment(large_data | , 'text')
obj_size = _get_obj_size(attachment)
self.assertEqual(obj_size, expected_obj_size)
|
josephmfaulkner/stoqs | stoqs/utils/STOQSQManager.py | Python | gpl-3.0 | 105,831 | 0.00788 | __author__ = 'Mike McCann'
__copyright__ = '2012'
__license__ = 'GPL v3'
__contact__ = 'mccann at mbari.org'
__doc__ = '''
STOQS Query manager for building ajax responses to selections made for QueryUI
@undocumented: __doc__ parser
@status: production
@license: GPL
'''
from django.conf import settings
from d... | is import gdal
import logging
import pprint
import calendar
import re
import locale
import time
import os
import tempfile
import numpy as np
logger = logging.getLogger(__name__)
# Constants to be also used by classifiers in contrib/analysi | s
LABEL = 'label'
DESCRIPTION = 'description'
COMMANDLINE = 'commandline'
spherical_mercator_srid = 3857
class STOQSQManager(object):
'''
This class is designed to handle building and managing queries against the STOQS database.
Chander Ganesan <chander@otg-nc.com>
'''
def __init__(self, request, r... |
exocad/exotrac | contrib/checkwiki.py | Python | bsd-3-clause | 6,045 | 0.000331 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.com/license.html.
#
# This s... | -pages')
if not name.startswith('.'))
if args:
args = sorted(set(names) & set(map(os.path.basename, args)))
else:
args = names
if options.download:
download_default_pages(args, options.prefix)
env = EnvironmentStub()
load_components(env)
with env... | wiki', 'default-pages/' +
name).decode('utf-8')
if wiki.text:
wiki.save('trac', '')
else:
printout('%s: Skipped empty page' % name)
req = Mock(href=Href('/'), abs_href=Href('http://localhost/'),
perm=Mock... |
ckclark/Hackquest | 75_Bite_me_and_cook_me/75.py | Python | apache-2.0 | 386 | 0.010363 | import sys
from hashlib import md5
sys.path.append('..')
from fetch_web import fetch_web
def main():
result = fetch_web('http://hackquest.com/modules/HackQuest/hacking/9/ | challenge.php', Cookie='pass=' + md5('SickPupp | y').hexdigest())
open('result.html', 'w').write(result)
# Get the password: copacabana, enter it in enterpassword.php
if __name__ == '__main__':
main()
|
denys-duchier/Scolar | ZopeProducts/exUserFolder/GroupSources/__init__.py | Python | gpl-2.0 | 1,150 | 0.003478 | #
# Extensible User Folder
#
# (C) Copyright 2000-2004 The Internet (Aust) Pty Ltd
# ACN: 082 081 472 ABN: 83 082 081 472
# All Rights Reserved
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ` | `AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MER | CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS;... |
ping/instagram_private_api | instagram_private_api/endpoints/collections.py | Python | mit | 3,411 | 0.002052 | import json
from ..compatpatch import ClientCompatPatch
class CollectionsEndpointsMixin(object):
"""For endpoints in related to collections functionality."""
def list_collections(self):
return self._call_api('collections/list/')
def collection_feed(self, collection_id, **kwargs):
"""
... | "width": 1080,
"height": 1080
},
| ...
]
}
},
"collection_name": "A Collection"
}
"""
params = {'name': name}
if added_media_ids and isinstance(added_media_ids, str):
added_media_ids = [added_media_ids]
if added_me... |
natemurthy/marathon | tests/system/marathon_common_tests.py | Python | apache-2.0 | 39,173 | 0.001404 | """ This is a set of tests which are expected to run on root Marathon and marathon on marathon (MoM).
"""
import common
import os
import pytest
import retrying
import shakedown
import time
import uuid
from common import event_fixture
from common import (app, app_mesos, block_port, cluster_info, ensure_mom, group,
... | asks = client.get_tasks(app_id)
app = clie | nt.get_app(app_id)
assert len(tasks) == 1
assert app['container']['type'] == 'MESOS'
# this fails on 1.7, it is likely the version of marathon in universe for 1.7
# which is 1.1.5. We do not have a check for marathon version.
@dcos_1_8
def test_launch_mesos_graceperiod(marathon_service_name):
""" Test ... |
OpenSourcePolicyCenter/dynamic | ogusa/tests/test_output_plots.py | Python | mit | 9,699 | 0 | '''
Tests of output_plots.py module
'''
import pytest
import os
import numpy as np
import matplotlib.image as mpimg
from ogusa import utils, output_plots
# Load in test results and parameters
CUR_PATH = os.path.abspath(os.path.dirname(__file__))
base_ss = utils.safe_read_pickle(
os.path.join(CUR_PATH, 'test_io_d... | st_tpi_profiles(by_j):
fig | = output_plots.tpi_profiles(
base_tpi, base_params, reform_tpi, reform_params, by_j=by_j,
plot_title=' Test Plot Title')
assert fig
test_data = [(base_params, base_ss, None, None, 'levels', None),
(base_params, base_ss, reform_params, reform_ss, 'levels',
None),
... |
sony/nnabla | python/test/function/test_rnn.py | Python | apache-2.0 | 8,914 | 0.001571 | # Copyright 2019,2020,2021 Sony Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | s = False
if num_layers > 1:
w = nn.Variable.from_numpy_array(w_np, need_grad=True)
if | type(b_np) == np.ndarray:
b = nn.Variable.from_numpy_array(b_np, need_grad=True)
with_bias = True
xs.grad.zero()
h0.grad.zero()
w0.grad.zero()
if num_layers > 1:
w.grad.zero()
if with_bias:
b.grad.zero()
ys, hn = _create_fixed_length_rnn(
xs, h0, w0, w, b... |
Dhivyap/ansible | lib/ansible/modules/network/fortios/fortios_vpn_l2tp.py | Python | gpl-3.0 | 9,385 | 0.001172 | #!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lic... | ortiGate or FortiOS (FOS) device | by allowing the
user to set and modify vpn feature and l2tp category.
Examples include all parameters and values need to be adjusted to datasources before usage.
Tested with FOS v6.0.5
version_added: "2.9"
author:
- Miguel Angel Munoz (@mamunozgonzalez)
- Nicolas Thomas (@thomnico)
notes:
... |
akintolga/superdesk-aap | server/aap/macros/update_to_pass_validation.py | Python | agpl-3.0 | 2,479 | 0.004034 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
from flask i... | at_dateline_to_locmmmddsrc
from superdesk.utc import get_date
import superdesk
from superdesk.metadata.item import CONTENT_TYPE
from apps.publish.content.common import ITEM_PUBLISH
logger = logging.getLogger(__name__)
def update_to_pass_validation(item, **kwargs):
"""
This is a test macro that does what is r... | tem will pass publication validation.
It is intended to be used to test auto publishing, that is publishing directly from ingest.
At the moment virtually all content received from Reuters fails validation.
:param item:
:param kwargs:
:return:
"""
try:
lookup = {'act': ITEM_PUBLISH, '... |
erudit/zenon | eruditorg/apps/public/book/migrations/0005_auto_20180717_1615.py | Python | gpl-3.0 | 754 | 0.00266 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-07-17 21:15
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('book', '0004_auto_20180717_1547'),
]
operations = [
migrations.AddField(
... | .BooleanField(default=True, verbose_name='Contribution des auteurs de type « direction » ?'),
preserve_default=False,
),
] | |
meletakis/collato | esn/cicu/migrations/0003_initial.py | Python | gpl-2.0 | 1,222 | 0.007365 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'UploadedFile'
db.create_table(u'cicu_uploadedfile', (
(u'id', self.gf('django.db... | ef backwards(self, orm):
# Deleting model 'UploadedFile'
db.delete_table(u'cicu_uploadedfile')
models = {
u'cicu.uploadedfile': {
'Meta': {'ordering': "('id',)", 'object_name': 'UploadedFile'},
'creation_d | ate': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
}
}
complete_apps = ['cicu'] |
Telefonica/toolium | toolium/utils/driver_wait_utils.py | Python | apache-2.0 | 18,753 | 0.004586 | # -*- coding: utf-8 -*-
"""
Copyright 2022 Telefónica Investigación y Desarrollo, S.A.U.
This file is part of Toolium.
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/lice... | that must be t | he same for all of them
in order to considering the element has stopped
:returns: the web element if it is clickable or False
:rtype: selenium.webdriver.remote.webelement.WebElement or appium.webdriver.webelement.WebElement
"""
element, times = element_times
web_eleme... |
birkin/rapid_exports | rapid_app/lib/viewhelper_updatedb.py | Python | mit | 9,897 | 0.014045 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging, os, sets
from rapid_app import settings_app
from rapid_app.models import ManualDbHandler, PrintTitleDev
log = logging.getLogger(__name__)
class UpdateTitlesHelper( object ):
""" Manages views.update_production_easyA_titles() work. ... | _app.DB_CONNECTION_URL )
self.db_handler.run_sql(
sql=unicode(os.environ['RAPID__BACKUP_OLDER_INSERT_SQL']), connection_url=settings_app.DB_CONNECTION_URL )
else:
log.info( 'not backing up because count is only, ```{}```'.format(result) )
re | turn
def update_backup( self ):
""" Copies data from production table to backup table.
Called by run_update() """
result = self.db_handler.run_sql( sql=unicode(os.environ['RAPID__PRODUCTION_COUNT_SQL']), connection_url=settings_app.DB_CONNECTION_URL )
if result[0][0] > 10000: #... |
compas-dev/compas | src/compas/geometry/transformations/matrices.py | Python | mit | 41,266 | 0.000606 | from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import math
from copy import deepcopy
from compas.geometry import scale_vector
from compas.geometry import normalize_vector
from compas.geometry import subtract_vectors
from compas.geometry import cross_vecto... | = identity_matrix(4)
>>> is_matrix_square(M)
True
"""
number_of_rows = len(M)
for row in M:
if len(row) != number_of_rows:
return False
return True
def matrix_minor(M, i, j):
"""Construct the minor corresponding to an element of a matrix.
Parameters
---------... | [list[float]]
The minor.
"""
return [row[:j] + row[j + 1:] for row in (M[:i] + M[i + 1:])]
def matrix_determinant(M, check=True):
"""Calculates the determinant of a square matrix M.
Parameters
----------
M : list[list[float]]
A square matrix of any dimension.
check : bool... |
mitsuhiko/sentry | src/sentry/plugins/sentry_mail/activity/regression.py | Python | bsd-3-clause | 918 | 0.001089 | from __future__ import absolute_import
from django.utils.html import escape
from sentry.utils.http import absolute_uri
from .base import ActivityEmail
class RegressionActivityEmail(ActivityEmail):
def get_activity_name(self):
return 'Regression'
def get_description(self):
data = self.activ... | olute_uri('/{}/{}/releases/{}/'.format(
self.organization.slug,
self.project.slug,
data['version'],
)),
escape(data['version']),
)
}
| return u'{author} marked {an issue} as a regression'
|
CARocha/plasystem | plasystem/settings.py | Python | mit | 3,017 | 0.001657 | """
Django settings for plasystem project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
from loc... | h.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'es-ni'
TIME_ZONE = 'America/Managua'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en... | DIA_ROOT', os.path.join(BASE_DIR, 'media'))
MEDIA_URL = '/media/'
STATIC_ROOT = os.environ.get('STATIC_ROOT', os.path.join(BASE_DIR, 'static'))
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static_media"),
)
LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/'
SESSION_SERIALIZER = 'django.contri... |
schleichdi2/OpenNfr_E2_Gui-6.0 | Navigation.py | Python | gpl-2.0 | 15,954 | 0.02783 | from os import path
from enigma import eServiceCenter, eServiceReference, eTimer, pNavigation, getBestPlayableServiceReference, iPlayableService
from Components.ParentalControl import parentalControl
from Components.config import config
from Components.PluginComponent import plugins
from Plugins.Plugin import PluginDes... | i', 'dags', 'fulan', 'entwopia')):
print"[NA | VIGATION] FORCED DEEPSTANDBY-WORKAROUND FOR THIS BOXTYPE (%s)" %thisBox
config.workaround.deeprecord.setValue(True)
config.workaround.deeprecord.save()
config.save()
if config.workaround.deeprecord.value: #work-around for boxes where driver not sent was_timer_wakeup signal to e2
wasTimerWakeup = False
... |
JOHNKYON/DSTC | DSTC2/traindev/scripts/corpus.py | Python | mit | 346 | 0.00289 | # -*- coding:utf-8 -*-
import nl | tk
from gensim import corpora
import myLogger
__author__ = "JOHNKYON"
def input_tokenize(sentence):
| logger = myLogger.myLogger("tokenize test")
tokens = nltk.word_tokenize(sentence)
dictionary = corpora.Dictionary(tokens)
print dictionary.token2id
logger.info("dictionary test finished")
|
ANR-kamoulox/Telemeta | telemeta/util/locale_fix.py | Python | agpl-3.0 | 189 | 0 | # -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
a = _("My last changes")
a = _("All last changes")
a = _("My s | earches")
a | = _("Children")
a = _("pattern")
|
MarketGarden/CardPublisher | cardpublisher/models/publishmodels.py | Python | gpl-3.0 | 254 | 0.015748 |
import dexml
fro | m dexml import fields
class | PublishJob(dexml.Model) :
outputDirectory = fields.String(tagname="outputDirectory")
patternFile = fields.String(tagname="patternFile")
sourceFile = fields.String(tagname="sourceFile")
|
peter17/pijnu | samples/formulaParser.py | Python | gpl-3.0 | 2,616 | 0.008028 | # -*- coding: utf8 -*-
'''
Copyright 2009 Denis Derman <denis.spir@gmail.com> (former developer)
Copyright 2011-2012 Peter Potrowl <peter017@gmail.com> (current developer)
This file is part of Pijnu.
Pijnu is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public Lic... | ')(join, toReal)
ADD = Char('+', format="'+'")(drop)
MULT = Char('*', format="'*'")(drop)
LPAREN = Char('(', format="'('")(drop)
RPAREN = Char(')', format="')'")(drop)
mult **= Sequence([Choice([grup, number], format='grup/number'), MULT, Choice([grup, mult, number], format='grup/mult/number')], format='(grup/number) M... | [grup, mult, number], format='grup/mult/number'), ADD, Choice([grup, add, mult, number], format='grup/add/mult/number')], format='(grup/mult/number) ADD (grup/add/mult/number)')
grup **= Sequence([LPAREN, Choice([add, mult], format='add / mult'), RPAREN], format='LPAREN (add / mult) RPAREN')(liftNode)
formula = Choice(... |
kahst/BirdCLEF2017 | birdCLEF_test.py | Python | mit | 10,275 | 0.014696 | #!/usr/bin/env python
print "HANDLING IMPORTS...",
import os
import time
import random
import operator
import argparse
import numpy as np
import cv2
from sklearn.utils import shuffle
import itertools
import scipy.io.wavfile as wave
from scipy import interpolate
import python_speech_features as psf
from pydub impo... | in_confidence', help='confidence threshold', type=float, default=0.01)
args = parser.parse_args()
return args
################ SPECTROGRAM EXTRACTION #################
#Change sample rate if not 44.1 kHz
def changeSampleRate(sig, rate):
duration = sig.shape[0] / rate
time_old = np.linspace(0, dura... | ce(0, duration, int(sig.shape[0] * 44100 / rate))
interpolator = interpolate.interp1d(time_old, sig.T)
new_audio = interpolator(time_new).T
sig = np.round(new_audio).astype(sig.dtype)
return sig, 44100
#Get magnitude spec from signal split
def getMagSpec(sig, rate, winlen, winstep, NFFT):
#... |
jasonperk/meetingroom | meetingroom/wsgi.py | Python | apache-2.0 | 1,144 | 0.000874 | """
WSGI config for meetingroom project.
This module conta | ins the WSGI application used | by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it als... |
wreckJ/hamster | src/hamster/client.py | Python | gpl-3.0 | 11,012 | 0.007265 | # - coding: utf-8 -
# Copyright (C) 2007 Patryk Zawadzki <patrys at pld-linux.org>
# Copyright (C) 2007-2009 Toms Baugis <toms.baugis@gmail.com>
# This file is part of Project Hamster.
# Project Hamster is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as ... | t the event we use term 'fact'. For the classificator
we use term 'activity'.
The relationship is - one activity can be used in several facts.
Th | e rest is hopefully obvious. But if not, please file bug reports!
"""
__gsignals__ = {
"tags-changed": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
"facts-changed": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
"activities-changed": (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (... |
torhve/FrameworkBenchmarks | frameworks/Ruby/rails-stripped/setup_jruby.py | Python | bsd-3-clause | 1,221 | 0.011466 |
import subprocess
import sys
import os
import setup_util
def start(args, logfile, errfile):
setup_util.replace_text("rails-stripped/config/database.yml", "host: .*", "host: " + args.database_host)
try:
subprocess.check_call("cp Gemfile-jruby Gemfile", shell=True, cwd="rails-stripped", stderr=errfile, stdout=... | p Gemfile-jruby.lock Gemfile.lock", shell=True, cwd="rails-stripped", stderr=errfile, stdout=logfile)
subprocess.Popen("rvm jruby-1.7.8 do bundle exec torqbox -b 0.0.0.0 -E production", shell=True, cwd="rails-stripped", stderr=err | file, stdout=logfile)
return 0
except subprocess.CalledProcessError:
return 1
def stop(logfile, errfile):
try:
p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
out, err = p.communicate()
for line in out.splitlines():
if 'torqbox' in line:
pid = int(line.split(None, 2)[1]... |
MuckRock/muckrock | muckrock/project/filters.py | Python | agpl-3.0 | 1,057 | 0.001892 | """
Filters for the project application
"""
# Django
from django.contrib.auth.models import User
# Third Party
import django_filters
# MuckRock
from muckrock.core import autocomplete
from muckrock.project.models import Project
from muckrock.tags.models import Tag
class ProjectFilterSet(django_filters.FilterSet):
... | ch users", "data-minimum-input-length": 2},
),
)
tags = django_filters.ModelMultipleChoiceFilter(
field_name="tags__name",
queryset=Tag.objects.all(),
label="Tags",
widget=autocomplete.ModelSelect2Multiple(
url="tag-autocomplete", attrs={"data-placeholder": "S... | )
class Meta:
model = Project
fields = ["contributors"]
|
daiogo/python2perl | test09.py | Python | gpl-2.0 | 146 | 0.034247 | #!/usr/bin/python
#even or odd program in p | ython
#Written by: Diogo Garcia de Freitas
x = 5
if x % 2 == 0:
print('Even')
els | e:
print('Odd')
|
AnsonShie/system_monitor | event_handler.py | Python | apache-2.0 | 4,438 | 0.002929 | #!/usr/bin/python
__author__ = 'anson'
import optparse
import json
from lib_monitor.event_handler_default import api_setting, gen_node_event, gen_disk_event, gen_network_event
from requests.exceptions import ConnectionError
class handle_event:
def __init__(self, api):
self.api = api
def node(self, ip,... | inue
try:
res = self.api.post(api_url, data=json.dumps(json_body))
if res.status_code != 200:
return False
except ConnectionError:
return False
return True
def foo_callback(option, opt, value, parser):
setattr(pars... | %prog [options] [--parameter]",
description="Event handler for nagios state change"
)
parser.add_option("--ip",
dest="ip",
help="Node ip",
type="string",
default="127.0.0.1"
)
parser.add_option("-t", "--typ... |
josephhardinee/PyDisdrometer | pydsd/tests/testNasa2DVDReader_mc3e.py | Python | lgpl-2.1 | 1,716 | 0.002914 | import numpy as np
import unittest
from ..aux_readers import NASA_2DVD_reader
class TestNasa2DvdReaderMc3eSubcase(unittest.TestCase):
"Test module for the NASA_2DVD_reader class in pydsd.aux_io.NASA_2DVD_reader for mc3e files"
def setUp(self):
filename = "testdata/nasa_gv_mc3e_2dvd_test.txt"
... | lds["Nd"], dict, "Nd was not a dictionary.")
def test_RR_works(self):
self.dsd.calculate_RR()
self.assertIsNotNone(
self.dsd.fields["rain_rate"],
| "Rain Rate is not in fields after calculate_RR()",
)
self.assertEqual(
len(self.dsd.fields["rain_rate"]["data"]),
5,
"Wrong number of time samples in rain rate",
)
def test_can_run_calc_dsd_params(self):
self.dsd.calculate_dsd_parameteriz... |
rhcarvalho/xmppvox | tests/cmd_regexps.py | Python | gpl-3.0 | 1,897 | 0.001054 | # -*- coding: utf-8 -*-
# XMPPVOX: XMPP client for DOSVOX.
# Copyright (C) 2012 Rodolfo Henrique Carvalho
#
# This file is part of XMPPVOX.
#
# XMPPVOX 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 F... | mail.com'
assert not add.match('adicionartereza@gmail.com')
assert not add.match('atereza@gmail.com')
print '/adicionar..............ok'
to = re.compile(r'(?:p(?:ara)?)?\s*(\d*)\s*$', re.I)
assert to.match('para')
assert to.match('p')
assert to.match('')
assert to.match(' | ')
assert to.match('23')
assert to.match(' 23')
assert to.match(' 23 ')
assert to.match('23 ')
assert to.match('para 23')
assert to.match('p 23')
#assert not to.match('para23')
#assert not to.match('p23')
print '/para...................ok'
|
rootio/rootio_web | alembic/versions/4d8d18f311aa_add_deleted_bool_to_.py | Python | agpl-3.0 | 1,319 | 0.009098 | """add deleted bool to things
Revision ID: 4d8d18f311aa
Revises: 4e34b4290fbc
Create Date: 2019-02-27 21: | 31:09.575521
"""
# revision identifiers, used by Alembic.
revision = '4d8d18f311aa'
down_revision = '4e34b4290fbc'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('content_musicplaylist', sa.Column('deleted', sa.Boolean... | le=True))
op.add_column('content_podcast', sa.Column('deleted', sa.Boolean(), nullable=True))
op.add_column('content_stream', sa.Column('deleted', sa.Boolean(), nullable=True))
op.add_column('content_track', sa.Column('deleted', sa.Boolean(), nullable=True))
op.add_column('radio_person', sa.Column('dele... |
JasonJerome16/Raspberry-Pi-SenseHat-Projects | BinaryClock/BinaryClock.py | Python | mit | 1,521 | 0.022354 | # This could probably be a lot more efficient, but it works just fine.
from sense_hat import SenseHat
from time import sleep
import datetime
sense = SenseHat()
B = [0,0,255]
R = [255,0,0]
G = [0,255,0]
W = [255,255,255]
E = [0,0,0]
while(True):
curTime = datetime.datetime.now()
curSecond = curTime.s... | data_bin[counter] = E
for counter in ran | ge(len(curHourBin)):
if(curHourBin[counter] == '1'):
data_bin[counter] = R
else:
data_bin[counter] = W
for counter in range(len(curMinuteBin)):
if(curMinuteBin[counter] == '1'):
data_bin[coun... |
robertoalotufo/ia636 | ia636/iacolorhist.py | Python | bsd-3-clause | 1,449 | 0.023464 | # -*- encoding: utf-8 -*-
# Module iacolorhist
def iacolorhist(f, mask=None):
import numpy as np
from iahistogram import iahistogram
WFRAME=5
f = np.asarray(f)
if len(f.shape) == 1: f = f[np.newaxis,:]
if not f.dtype == 'uint8':
raise Exception,'error, can only process uint8 images'
... | sk)))
r,g,b = mask*r, mask*g, mask*b
hrg = np.zeros((256,256), np.int32); hbg=hrg+0; hrb= | hrg+0
img = 256*r + g; m1 = img.max()
aux = iahistogram(img.astype(np.int32)); aux[0] = aux[0] - n_zeros
np.put(np.ravel(hrg), range(m1+1), aux)
img = 256*b + g; m2 = img.max()
aux = iahistogram(img.astype(np.int32)); aux[0] = aux[0] - n_zeros
np.put(np.ravel(hbg), range(m2+1), aux)
img = 25... |
inveniosoftware/invenio-oaiserver | invenio_oaiserver/verbs.py | Python | mit | 5,930 | 0.000169 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
# Copyright (C) 2021-2022 Graz University of Technology.
# Copyright (C) 2022 RERO.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"... | e(
format='permissive', load_from='from',
data_key='from', dump_to='from')
until = DateTime(format='permissive')
set = fields.Str()
metadataPrefix = fields.Str(required=True,
validate=validate_metadata_prefix)
class ListMetadataFor... | istRecords(ListIdentifiers):
"""Arguments for ListRecords verb."""
class ListSets(OAISchema):
"""Arguments for ListSets verb."""
class ResumptionVerbs(Verbs):
"""List valid verbs when resumption token is defined."""
class ListIdentifiers(OAISchema, ResumptionTokenSchema):
"""Argu... |
pools/JaikuEngine | common/test/api.py | Python | apache-2.0 | 65,695 | 0.006013 | # Copyright 2009 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, ... | an OAUTH_ERROR
#self.assertEqual(rv['code'], exception.OAUTH_ERROR)
def | test_json_invalid_oauth_request_bad_tokens(self):
settings.API_DISABLE_VERIFICATION = False
settings.API_ALLOW_ROOT_PLAINTEXT = True
sig_method = oauth_util.PLAINTEXT
# test invalid consumer
bad_consumer = oauth.OAuthConsumer('BAD_KEY', 'BAD_SECRET')
request = oauth.OAuthRequest.from_consumer... |
PaulWay/insights-core | insights/parsers/tests/test_df.py | Python | apache-2.0 | 7,089 | 0.003668 | from insights.parsers import df, ParseException
from insights.tests import context_wrap
import pytest
DF_ALP = """
Filesystem 1024-blocks Used Available Capacity Mounted on
/dev/mapper/vg_lxcrhel6sat56-lv_root 98571884 4244032 89313940 5% /
sysfs ... | et_filesystem('/dev/sda2')[0] == r
assert len(df_list.get_filesystem('tmpfs')) == 6
assert df_ | list.get_mount('/dev').filesystem == 'devtmpfs'
assert df_list.get_mount('/run').total == '1499684'
assert df_list.get_mount('/tmp').used == '54'
assert df_list.get_mount('/boot').available == '127587'
assert df_list.get_filesystem('/dev/sda2')[0].capacity == '1%'
assert df_list.get_filesystem('/dev... |
Patchett/Leetcode-Problems | medium/3sum.py | Python | apache-2.0 | 1,318 | 0.01214 | # Author: Ryan Bridges - 9/8/2017
# Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
# Note: The solution set must not contain duplicate triplets.
# For example, given array S = [-1, 0, 1, 2, -1, -4],
# A solu... | tinue
if s < 0:
r += 1
continue
else:
result.append((array[l], array[r], array[i]))
print l,i,r
r += 1
l -= 1
while r < len(array) and l > -1:
if array[r] == array[... | -1,-1,0,1,1,1,1,2,4], 0)
|
Apogaea/voldb | volunteer/apps/shifts/migrations/0012_auto_20150312_1137.py | Python | gpl-3.0 | 2,426 | 0.002473 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
import django.db.models.deletion
from django.utils.timezone import utc
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('events', '0001_initial'),... | field=models.ForeignKey(related_name='shifts' | , on_delete=django.db.models.deletion.PROTECT, to='events.Event', null=True),
preserve_default=True,
),
migrations.AddField(
model_name='shift',
name='updated_at',
field=models.DateTimeField(default=datetime.datetime(2015, 3, 12, 18, 37, 24, 948795, tzinfo... |
zaneveld/picrust | scripts/start_parallel_jobs.py | Python | gpl-3.0 | 5,341 | 0.017974 | #!/usr/bin/env python
# File created on 10 Mar 2010
from __future__ import division
__author__ = "Greg Caporaso"
__copyright__ = "Copyright 2011-2013, The PICRUSt Project"
__credits__ = ["Greg Caporaso","Morgan Langille"]
__license__ = "GPL"
__version__ = "1.1.0"
__maintainer__ = "Greg Caporaso"
__email__ = "gregcapor... | ake_option('-m','--make_jobs',action='store_true',\
help='make the job files [default: %default]'),\
make_option('-s','--submit_jobs',action='store_true',\
help='submit the job files [default: %default]'),\
make_option('-d','--delay',action='store',type='int',default=0,
help='Number of ... | h job [default: %default]'),
make_option('-n','--num_jobs',action='store',type='int',\
help='Number of jobs to group commands into. [default: %default]',\
default=4)\
]
script_info['version'] = __version__
script_info['disallow_positional_arguments'] = False
def write_job_files(output_dir... |
Johnzyg/bletchley | lib/bletchley/blobtools.py | Python | lgpl-3.0 | 18,457 | 0.004226 | '''
A collection of tools to assist in analyzing encrypted blobs of data
Copyright (C) 2011-2013 Virtual Security Research, LLC
Author: Timothy D. Morgan, Jason A. Donenfeld
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License, version 3,
... | ing, self).__init__(dialect)
if dialect.startswith('rfc3548'):
self.c62 = b'+'
self.c63 = b'/'
self.pad = b'='
e | lif dialect.startswith('filename'):
self.c62 = b'+'
self.c63 = b'-'
self.pad = b'='
elif dialect.startswith('url1'):
self.c62 = b'-'
self.c63 = b'_'
self.pad = b'='
elif dialect.startswith('url2'):
self.c62 = b'-'
... |
dothiko/mypaint | gui/toolbar.py | Python | gpl-2.0 | 8,495 | 0.001177 | # This file is part of MyPaint.
# Copyright (C) 2011-2015 by Andrew Chadwick <a.t.chadwick@gmail.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 ... | OOLBAR_ICONS)
self.toolbar1.set_icon_size(widgets.get_toolbar_icon_size())
self.toolbar1.set_border_width(0)
self.toolbar1.set_show_arrow(True)
self.toolbar1.connect(
"popup-context-menu",
self.on_toolbar1_popup_context_menu
)
self.toolbar1_popup =... | lbar1:
if isinstance(item, gtk.SeparatorToolItem):
item.set_draw(False)
self.toolbar2 = self.app.ui_manager.get_widget('/toolbar2')
self.toolbar2.set_style(gtk.TOOLBAR_ICONS)
self.toolbar2.set_icon_size(widgets.get_toolbar_icon_size())
self.toolbar2.set_border... |
mdziurzynski/maisen_core | tests/testrunprogram.py | Python | mit | 287 | 0 | import unittest
from os import getcwd, path
from maisen_core.helpers.runprogram import run_program
class TestRunProgram(unittest.TestCase):
|
def test_outputs(self):
"Test outputs from program runner."
pass
def test_catching_pr | ogram_errors(self):
pass
|
treejames/viewfinder | backend/op/upload_episode_op.py | Python | apache-2.0 | 9,677 | 0.008474 | # Copyright 2013 Viewfinder Inc. All Rights Reserved.
"""Viewfinder UploadEpisodeOperation.
This operation creates metadata for a new episode and photos in the current user's default
viewpoint. The user's device will then upload the photos to S3.
"""
__authors__ = ['andy@emailscrubbed.com (Andy Kimball)']
import js... | _Update()
yield self._Account()
yield Ope | ration.TriggerFailpoint(self._client)
yield self._Notify()
finally:
yield gen.Task(Viewpoint.ReleaseLock, self._client, self._user.private_vp_id, lock)
@gen.coroutine
def _Check(self):
"""Gathers pre-mutation information:
1. Episode and photos to upload.
2. Checkpoints list of epi... |
cclauss/stash | bin/grep.py | Python | mit | 1,793 | 0.003346 | """Search a regular expression pattern in one or more files"""
from __future__ import print_function
import argparse
import fileinput
import os
import re
import sys
def main(args):
ap = argparse.ArgumentParser()
ap.add_argument('pattern', help='the pattern to match')
ap.add_argument('files', nargs='*', h... |
finally:
fileinput.close()
if __name | __ == "__main__":
main(sys.argv[1:])
|
waltermoreira/dockeransible | app_builder/app_builder_image/concat_roles.py | Python | mit | 3,259 | 0.000614 | #!/usr/bin/python
import glob
import os
import shutil
import subprocess
import sys
import yaml
def create_role(role):
ret = subprocess.check_output(
'ansible-galaxy init {}'.format(role).split())
if not ret.strip().endswith('created successfully'):
raise Exception('could not create role "{}"... | xplicit_start=True)
os.rename(new_main, orig_main)
def add_dependency | (src_role, target_role):
"""Add metadata saying that 'target_role' depends on 'src_role'"""
md = get_metadata(target_role)
deps = md.setdefault('dependencies', [])
deps.append(os.path.join(target_role, 'roles', src_role))
set_metadata(target_role, md)
def sub_roles(role):
try:
return ... |
IVaN4B/maugli | maugli/store/views.py | Python | gpl-3.0 | 190 | 0.005263 | from django.http i | mport HttpResponse
from django.views.generic import TemplateView
from django.conf import settings
class | CatalogView(TemplateView):
template_name = "base_catalog.html"
|
EternityForest/KaithemAutomation | kaithem/src/thirdparty/pint/quantity.py | Python | gpl-3.0 | 68,988 | 0.001522 | # -*- coding: utf-8 -*-
"""
pint.quantity
~~~~~~~~~~~~~
:copyright: 2016 by Pint Authors, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import division, unicode_literals, print_function, absolute_import
import contextlib
import copy
import datetime
imp... | otImplemented
# pandas often gets to arrays of quantities [ Q_(1,"m"), Q_(2,"m")]
# and expects Quantity * array[Quantity] shoul | d return NotImplemented
elif isinstance(other, list) and other and isinstance(other[0], type(self)):
return NotImplemented
result = f(self, *args, **kwargs)
return result
return wrapped
@contextlib.contextmanager
def printoptions(*args, **kwargs):
"""
Numpy printoptions... |
pinax/pinax-blog | pinax/blog/tests/tests.py | Python | mit | 6,575 | 0.000608 | from __future__ import absolute_import
import random
from django.core.exceptions import ValidationError
from django.http.request import HttpRequest
from django.urls import reverse
from django.utils.text import slugify
from test_plus import TestCase
from ..context_processors import scoped
from ..models import Blog, ... | self.post("pinax_blog:manage_post_create", data=post_data)
self.assertRedirects(self.la | st_response, reverse("pinax_blog:manage_post_list"))
self.assertTrue(Post.objects.get(title=post_title))
|
riggsd/zcant | zcant/conversion.py | Python | mit | 16,713 | 0.004368 | """
Algorithm for conversion of .WAV audio to zero-crossing signal.
---------------
Myotisoft ZCANT
Copyright (C) 2012-2017 Myotisoft LLC, all rights reserved.
You may use, distribute, and modify this code under the terms of the MIT License.
"""
from __future__ import division
import io
import sys
imp... | reshold = threshold_factor * signal_rms
# log.debug('RMS: %.1f threshold: %0.1f (%.1f x RMS)', signal_r | ms, threshold, threshold_factor)
# mean_signal = rolling_mean(signal, window_size)
# |
abusse/cinder | cinder/tests/backup/fake_service.py | Python | apache-2.0 | 1,422 | 0 | # Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
# 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/LICEN... | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from cinder.backup.driver import BackupDriver
from cinder.openstack.common i | mport log as logging
LOG = logging.getLogger(__name__)
class FakeBackupService(BackupDriver):
def __init__(self, context, db_driver=None):
super(FakeBackupService, self).__init__(context, db_driver)
def backup(self, backup, volume_file):
pass
def restore(self, backup, volume_id, volume_... |
mitodl/bootcamp-ecommerce | applications/apps.py | Python | bsd-3-clause | 324 | 0.003086 | """Apps for bootcamp ap | plications"""
from django.apps import AppConfig
class ApplicationConfig(AppConfig):
"""AppConfi | g for bootcamp applications"""
name = "applications"
def ready(self):
"""Application is ready"""
import applications.signals # pylint:disable=unused-import, unused-variable
|
kmpf/uap | include/sources/raw_file_sources.py | Python | gpl-3.0 | 2,778 | 0.00036 | from uaperrors import StepError
import sys
import copy
import csv
import glob
from logging import getLogger
import os
import re
import yaml
from abstract_step import AbstractSourceStep
logger = getLogger('uap_logger')
class RawFileSources(AbstractSourceStep):
def __init__(self, pipeline):
super(RawFileS... | f.is_option_set_in_config('sample_id_prefix'):
sample_id_parts.append(self.get_option('sample_id_prefix'))
sample_id_parts += list(match.groups())
sample_id = '_'.join(sample_id_parts)
if sample_id not in fo | und_files:
found_files[sample_id] = list()
found_files[sample_id].append(path)
# declare a run for every sample
for run_id, paths in found_files.items():
with self.declare_run(run_id) as run:
run.add_public_info(
"paired_end", ... |
shanghai-edu/radius-1xtest | app/utils.py | Python | apache-2.0 | 6,206 | 0.008119 | #coding=utf-8
import os
import sys
sys.path.append(sys.path[0] + "/lib/")
from werkzeug.contrib.fixers import ProxyFix
import packet
from client import Client
from dictionary import Dictionary
import mschap2
from socket import gethostname
from time import time
import random
from PIL import Image, ImageDraw, ImageFont,... | ints: 是否画干扰点
@param point_chance: 干扰点出现的概率,大小范围[0, 100]
@return: [0]: PIL Image实例
@return: [1]: 验证码图片中的字符串
"""
width, height = size # 宽, 高
img = Image.new(mode, size, bg_color) # 创建图形
draw = ImageDraw.Draw(img) # 创建画笔
def get_chars():
"""生成给定长度的字符串,返回列表格式"""
return r... | for i in range(line_num):
# 起始点
begin = (random.randint(0, size[0]), random.randint(0, size[1]))
# 结束点
end = (random.randint(0, size[0]), random.randint(0, size[1]))
draw.line([begin, end], fill=(0, 0, 0))
def create_points():
"""绘制干扰点"""
... |
gpg/gpgme | lang/python/examples/howto/add-userid.py | Python | lgpl-2.1 | 2,100 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals
# Copyright (C) 2018 Ben McGinnes <ben@gnupg.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 S... | ail address of the user ID: ")
uid_cmnt = input("Enter a comment to include (optional): ")
if homedir.startswith("~"):
if os.path.exists(os.path.expanduse | r(homedir)) is True:
c.home_dir = os.path.expanduser(homedir)
else:
pass
elif os.path.exists(homedir) is True:
c.home_dir = homedir
else:
pass
fpr = "".join(fpr0.split())
if uid_cmnt:
userid = "{0} ({1}) <{2}>".format(uid_name, uid_cmnt, uid_email)
else:
userid = "{0} <{2}>".format... |
gerencianet/gn-api-sdk-python | examples/update_subscription_metadata.py | Python | mit | 325 | 0.003077 | # | encoding: utf-8
from gerencianet import Gerencianet
from credentials import CREDENTIALS
gn = Gerencianet(CREDENTIALS)
params = {
'id': 1
}
body = {
'notification_url': 'http://yourdomain.com',
'custom_id': 'my_new_id'
}
response = gn.update_subscription_metadata(params=params, body=body)
print(respons... | |
jithinbp/pslab-desktop-apps | psl_res/GUI/D_PHYSICS/B_physics/M_RANDOM_SAMPLING.py | Python | gpl-3.0 | 3,519 | 0.046604 | #!/usr/bin/python
"""
::
This experiment is used to study.....
"""
from __future__ import print_function
from PSL_Apps.utilitiesClass import utilitiesClass
from PSL_Apps.templates import ui_template_graph_nofft as template_graph_nofft
import numpy as np
from PyQt4 import QtGui,QtCore
import pyqtgraph as pg
... | TITLE='CLEAR\nPLOT'))
self.binIcon = self.dialIcon(FUNC=self.setBins,TITLE='# of Bins',MIN=10,MAX=300)
self.binIcon.dial.setValue(200)
self.WidgetLayout.addW | idget(self.binIcon)
self.W1 = self.addWG(self.I,{'type':'W1','name':'SINE1'},self.ControlsLayout)
self.SQR1 =self.addWG(self.I,{'type':'SQR1','name':'SQR1'},self.ControlsLayout)
self.W1.dial.setMinimum(70)
self.W1.dial.setMaximum(250)
self.SQR1.dial.setMinimum(20)
self.SQR1.dial.setMaximum(150)
self.ru... |
phani-vadrevu/amico | amico_scripts/db_cleanup.py | Python | bsd-3-clause | 847 | 0.007084 | #!/usr/bin/env python
# Author: Phani Vadrevu <pvadrevu@uga.edu>
import psycopg2
import config
from config import *
# Connect to database
try:
conn = psycopg2.connect("dbname=%s host=%s user=%s password=%s"
%(db_name,db_host,db_user,db_password))
except:
print "Unable to connect | to database: "+db_name
# Use Autocommit mode for database connection
conn.set_isolation_level(0)
cursor = conn.cursor()
cursor.execute("""DROP TABLE IF EXISTS pe_dumps,virus_total_scans,
ped_vts_mapping, manual_download_checksums,bgp2asn,
weka_features, virus_total_submissions, amico_scores CASCADE"""... | o_scores, weka_features, ped_vts_mapping"""
cursor.close()
conn.close()
|
Spotipo/spotipo | tests/modules/unifi/test_main.py | Python | agpl-3.0 | 2,218 | 0.027051 | import sys
import pytest
from flask import current_app
from flask_wtf import Form
from wtforms import TextField
from faker import Faker
import arrow
import uuid
from unifispot.core.models import Wifisite,Device,Guesttrack
from tests.helpers import get_guestentry_url,randomMAC,loggin_as_admin
def test_guest_portal(se... | valid data' %res
assert 0 == Guesttrack.query.filter_by(devicemac=mac).first().demo,\
| 'Demo is not rejected for non auth visits '
#check demo is not set with auth visit
mac=randomMAC()
admin = loggin_as_admin()
res = admin.get(get_guestentry_url(site1,mac=mac,apmac=randomMAC(),demo=1)).status
assert '302 FOUND' == res , 'Getting :%s instead 302 FOUND for\
with valid ... |
deasek/freshmail-python | freshmail.py | Python | mit | 6,906 | 0.011295 | import requests
import json
import hashlib
"""
subscriber status codes for use with API: (undocumented in API)
1 active
2 activation pending
3 not activated
4 resigned
5 soft bouncing
8 hard bouncing
"""
class FreshMail(object):
"""
Custom class for Freshmail REST API
author: Dariusz Stepniak <stepniak.da... | yload=None, raw_response=False, method='POST'):
"""
Makes request to REST API. Add payload data for POST request.
:param url: API endpoint
:param payload: POST data dict
"""
if payload is None:
post_data = ''
else:
post_data = json.dumps(pa... | full_url = '%s%s%s' % (self.host, self.prefix, url,)
strSign = "%s/%s%s%s%s" % (self.api_key,
self.prefix,
url,
post_data,
self.api_secret,)
m = hashlib.sha1()
... |
ausarbluhd/EternalLLC | scripts/mallory/src/mallory.py | Python | gpl-2.0 | 21,144 | 0.010689 | #Copyright Intrepidus Group 2010
#All Rights Reserved
#Released under the following license
#
#PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
#--------------------------------------------
#
#0. This Python Software Foundation License (the "License") applies to
#any original work of authorship (the "Software") whose owner... | lory(Subject):
"""
The main Mallory class used to instantiate and start the proxy. Protocols
can be configured through methods in the main Mallory class. This is
where it all starts.
"""
def __init__(self, options):
| Subject.__init__(self)
self.log = logging.getLogger("mallorymain")
config.logsetup(self.log)
self.configured_protos = []
self.configured_plugin_managers = []
self.protoinstances = []
self.opts = options.options
self.dbname = self.opts.trafficdb
sel... |
OCA/reporting-engine | base_comment_template/tests/test_base_comment_template.py | Python | agpl-3.0 | 3,459 | 0.002025 | # Copyright 2020 NextERP Romania SRL
# Copyright 2021 Tecnativa - Víctor Martínez
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo.tests import common
from .fake_models import ResUsers, setup_test_model, teardown_test_model
class TestCommentTemplate(common.SavepointCase):
@classmeth... | setup_test_model(cls.env, ResUsers)
cls.user_obj = cls.env.ref("base.model_res_users")
cls.user = cls.env.ref("base.user_demo")
cls.user2 = cls.env.ref("base.demo_user0")
cl | s.partner_id = cls.env.ref("base.res_partner_12")
cls.partner2_id = cls.env.ref("base.res_partner_10")
cls.main_company = cls.env.ref("base.main_company")
cls.company = cls.env["res.company"].create({"name": "Test company"})
cls.before_template_id = cls.env["base.comment.template"].creat... |
chainer/chainercv | tests/links_tests/model_tests/fpn_tests/test_mask_head.py | Python | mit | 8,451 | 0.000355 | from __future__ import division
import numpy as np
import unittest
import chainer
from chainer import testing
from chainer.testing import attr
from chainercv.links.model.fpn import mask_head_loss_post
from chainercv.links.model.fpn import mask_head_loss_pre
from chainercv.links.model.fpn import MaskHead
from chaine... | , ())
self.assertEqual(gt_segms[l].dtype, np.float32)
self.assertEqual(gt_mask_labels[l].dtype, np.int32)
@unittest.skipUnless(_cv2_available, 'cv2 is not installed')
def test_mask_head_loss_pre_cpu(self):
self._check_mask_head_loss_pre(np)
@attr.gpu
@unittest.skipUnles... | import cupy
self._check_mask_head_loss_pre(cupy)
def _check_head_loss_post(self, xp):
B = 2
segms = chainer.Variable(_random_array(xp, (20, 81, 28, 28)))
mask_roi_indices = [
xp.random.randint(0, B, size=5).astype(np.int32),
xp.random.randint(0, B, size=7).... |
healthchecks/healthchecks | hc/api/management/commands/smtpd.py | Python | bsd-3-clause | 2,479 | 0.00121 | import asyncore
import email
import email.policy
import re
from smtpd import SMTPServer
from django.core.management.base import BaseCommand
from django.db import connections
from hc.api.models import Check
RE_UUID = re.compile(
"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{... | db connection in case the old one h | as timed out:
connections.close_all()
result = _process_message(peer[0], mailfrom, rcpttos[0], data)
self.stdout.write(result)
class Command(BaseCommand):
help = "Listen for ping emails"
def add_arguments(self, parser):
parser.add_argument(
"--host", help="ip addr... |
CloudBoltSoftware/cloudbolt-forge | actions/cloudbolt_plugins/aws/aws_rate/aws_rate_hook_with_cb_configured_rate_per_env.py | Python | apache-2.0 | 7,687 | 0.002342 | """
Calculates the on-demand rate for the chosen AWS instance type and CB Admin defined rate for Software, Parameter and Application per environment.
Enable this hook to see your own defined rate per environment along with on-demand rate for AWS instance type in order form cost breakdown.
Rate is displayed in the time... | ec2serverinfo:
instance_type = server.ec2serverinfo.instance_type
region_name = server.ec2serverinfo.ec2_region
| if not instance_type:
for cfv in cfvs:
if cfv.field.name == 'instance_type' and cfv.value:
instance_type = cfv.value
break
if not instance_type:
# Perhaps the instance_type is in a preconfiguration.
for pcvs in pcvss:
instance_type_cfv... |
huyphan/pyyawhois | test/record/parser/test_response_whois_fi_property_status_graceperiod.py | Python | mit | 3,795 | 0.003162 |
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# spec/fixtures/responses/whois.fi/property_status_graceperiod
#
# and regenerate the tests with the following script
#
# $ scripts/generate_tests.py
#
from nose.tools import *
from dateutil.parser import ... | )
def test_registered(self):
eq_(self.record.registered, True)
def test_created_on(self):
eq_(self.record.created_on.__class__.__name__, 'datetime')
eq_(self.record.created_on, time_parse('2012-06-21'))
def test_registrar(self):
assert_raises(yawhois.exceptions.AttributeNo... | cts(self):
eq_(self.record.registrant_contacts.__class__.__name__, 'list')
eq_(len(self.record.registrant_contacts), 1)
eq_(self.record.registrant_contacts[0].__class__.__name__, 'Contact')
eq_(self.record.registrant_contacts[0].type, yawhois.record.Contact.TYPE_REGISTRANT)
eq_(s... |
rakesh-gksr/sg_implementation | desired_capabilities.py | Python | gpl-3.0 | 1,009 | 0.002973 | """
The Desired Capabilities implementation.
"""
class DesiredCapabilities(object):
"""
Set of default supported desired capabilities.
Usage Example:
fr | om selenium import webdriver
selenium_grid_url = "http://192.168.201.164:4444/wd/hub"
# Create a desired capabilities object as a starting point.
capabilities = DesiredCapabilities.FIREFOX()
capabilities['platform'] = "MAC"
capabilities['version'] = "46"
# Instantiate an ... | command_executor=selenium_grid_url)
"""
FIREFOX = {
"browserName": "firefox",
"version": "",
"platform": "ANY",
"javascriptEnabled": True,
"marionette": False,
}
CHROME = {
"browserName": "chrome",
"version": "",
"p... |
tulir/maubot | maubot/management/api/client.py | Python | agpl-3.0 | 5,480 | 0.001277 | # maubot - A plugin-based Matrix bot system.
# Copyright (C) 2019 Tulir Asokan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any... | t.http_client)
try:
mxid = await new_client.whoami()
except MatrixInvalidToken:
return resp.bad_client_access_token
except MatrixRequestError:
return resp.bad_client_access_details
except MatrixConnectionError:
retur | n resp.bad_client_connection_details
if user_id is None:
existing_client = Client.get(mxid, None)
if existing_client is not None:
return resp.user_exists
elif mxid != user_id:
return resp.mxid_mismatch(mxid)
db_instance = DBClient(id=mxid, homeserver=homeserver, access_to... |
bdubyapee/apm | src/color.py | Python | gpl-3.0 | 5,554 | 0.012063 | #! usr/bin/env python
#
# APM - Another Python Mud
# Copyright (C) 2012 bdubyapee (BWP) p h i p p s b @ g m a i l . c o m
#
# 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 versi... | # Set foreground color to bright white
'{X': '0;40m', # Set background | color to black
'{br': '0;41m', # Set background color to red
'{bg': '0;42m', # Set background color to green
'{by': '0;43m', # Set background color to yellow
'{bb': '0;44m', # Set background color to blue
'{bp': '0;45m', # Set backgro... |
CornerstoneLabs/club-prototype | app-server/classes/migrations/0004_auto_20160915_1222.py | Python | mit | 783 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-15 12:22
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('classes', '0003_auto_20160914_2057'),
]
operations = [
migrations.AddField(... | _end',
field=models.DateField(blank=True, null=True),
),
migrations.AddField(
model_name='class',
name='sessions | _start',
field=models.DateField(blank=True, null=True),
),
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.