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 |
|---|---|---|---|---|---|---|---|---|
mulonemartin/kaira | kaira/wrapper.py | Python | mit | 1,431 | 0.000699 |
__all__ = ['ContextManager', 'WrapWithContextManager']
class ContextManager(object):
name = 'ContextManager'
def on_start(self, request):
pass
def on_success(self, request):
pass
def on_failure(self, request):
pass
def wrap_call(self, func):
return func
class... | t(a[0])
output = ctm.wrap_call(fnc)(*a, **b)
ctm.on_success(a[0])
return output
except:
ctm.on_failure(a[0])
raise
return g
def wrap_skip_context(fnc, ctm):
def g(*a, **... | if self.context:
for context in reversed(self.context):
if isinstance(context, ContextManager):
if context.name in self.skip_list:
f = wrap_skip_context(f, context)
else:
f = wrap(f, context)
... |
ityaptin/ceilometer | ceilometer/storage/sqlalchemy/migrate_repo/versions/006_counter_volume_is_float.py | Python | apache-2.0 | 888 | 0 | # -*- coding: utf-8 -*-
#
# Copyright 2013 eNovance SAS <[email protected]>
#
# 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... | autoload=True)
meter.c.counter | _volume.alter(type=Float(53))
|
DarioGT/docker-carra | src/rqEirq/admin.py | Python | mit | 247 | 0.036437 | from django.c | ontrib import admin
# Register your models here.
from .models import Source
from .actions import doGraphMerveille
class MySource( admin.ModelAdmin ):
| actions = [ doGraphMerveille ]
admin.site.register( Source, MySource )
|
coreycb/horizon | openstack_dashboard/test/integration_tests/tests/test_security_groups.py | Python | apache-2.0 | 4,753 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | ule
* verifies the rule appears in the rules table
* delete the newly created rule
* verifies the rule does not appear in the table after deletion
* deletes the newly created security group
| * verifies the security group does not appear in the table after
deletion
"""
self._create_securitygroup()
self._add_rule()
self._delete_rule_by_table_action()
self._delete_securitygroup()
|
fstltna/PyImp | src/empPath.py | Python | gpl-2.0 | 20,956 | 0.031733 | # Copyright (C) 1998 Ulf Larsson
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is ... | up paths
## and the second part deals with removing a source or
## destination sector.
##
## Building up paths is done by taking the best head ( or tail) path
## and crea | te new paths to the neighbours of the path's end point.
## If the neigbouring sector is *not* in __visited we add the new
## path, otherwise we try to create a __complete path. This ends
## when the total cost of the best head and tail path is higher
## then the best complete path.
##
## Removing source or destina... |
common-workflow-language/cwltool | cwltool/executors.py | Python | apache-2.0 | 18,408 | 0.000978 | """Single and multi-threaded executors."""
import datetime
import functools
import logging
import math
import os
import threading
from abc import ABCMeta, abstractmethod
from threading import Lock
from typing import (
Dict,
Iterable,
List,
MutableSequence,
Optional,
Set,
Tuple,
Union,
... | ements.append(req)
self.run_jobs(process, job_order_object, logger, runtime_context)
if (
self.final_output
and self.final_output[0] is not | None
and finaloutdir is not None
):
self.final_output[0] = relocateOutputs(
self.final_output[0],
finaloutdir,
self.output_dirs,
runtime_context.move_outputs,
runtime_context.make_fs_access(""),
... |
weqopy/blog_instance | app/api_1_0/comments.py | Python | mit | 2,341 | 0 | from flask import jsonify, request, g, url_for, current_app
from .. import db
from ..models import Post, Permission, Comment
from . import api
from .decorators import permission_required
@api.route('/comments/')
def get_comments():
page = request.args.get('page', 1, type=int)
pagination = Comment.query.order_... | ost.query.get_or_404(id)
comment = Comment.from_json(request.json)
comment.author = g.current_user
comment.post = post
db.session.add(comment)
db.session.commit()
return j | sonify(comment.to_json()), 201, \
{'Location': url_for('api.get_comment', id=comment.id,
_external=True)}
|
pbanaszkiewicz/amy | amy/workshops/migrations/0239_organization_affiliated_organizations.py | Python | mit | 441 | 0.002268 | # Generated by Django 2.2.18 on 2021-03-27 18:32
from django.db import migrations, models |
class Migration(migrations.Migration):
dependencies = [
('workshops', '0238_task_seat_public'),
]
operations = [
migrations.AddField(
model_name='organization',
name='affiliated_organizations',
field=models.ManyToManyField(to='workshops.Organization',... | ,
]
|
XiaosongWei/chromium-crosswalk | tools/telemetry/telemetry/internal/results/story_run_unittest.py | Python | bsd-3-clause | 2,653 | 0.003769 | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
from telemetry.internal.results import story_run
from telemetry.story import shared_state
from telemetry.story import story_set
from telemet... | _run.StoryRun(self.stories[0])
run.AddValue(failure.FailureValue.FromMessage(self.stories[0], 'test'))
run.AddValue(skip.SkipValue(self.stories[0], 'test'))
self.assertFalse(run.ok)
self.assertFalse(run.failed)
self.assertTrue(run.skipped)
run = story_run.StoryRun(self.stories[0])
run.AddVa... | self.assertFalse(run.ok)
self.assertFalse(run.failed)
self.assertTrue(run.skipped)
def testStoryRunSucceeded(self):
run = story_run.StoryRun(self.stories[0])
self.assertTrue(run.ok)
self.assertFalse(run.failed)
self.assertFalse(run.skipped)
run = story_run.StoryRun(self.stories[0])
... |
khchine5/lino | lino/modlib/users/desktop.py | Python | bsd-2-clause | 4,228 | 0.006623 | # -*- coding: UTF-8 -*-
# Copyright 2011-2017 Luc Saffre
# License: BSD (see file COPYING for details)
"""Desktop UI for this plugin.
Documentation is in :doc:`/specs/users` and :doc:`/dev/users`
"""
from django.conf import settings
from lino.api import dd, rt, _
from lino.core import actions
from lino.core.roles imp... | ayout = UserInsertLayout()
column_names_m = 'mobile_item *' |
@classmethod
def render_list_item(cls, obj, ar):
return "<p>{}</p>".format(obj.username)
#~ @classmethod
#~ def get_row_permission(cls,action,user,obj):
#~ """
#~ Only system managers may edit other users.
#~ See also :meth:`User.disabled_fields`.
#~ """
... |
jocelynmass/nrf51 | toolchain/arm_cm0/arm-none-eabi/lib/thumb/v7-ar/fpv3/hard/libstdc++.a-gdb.py | Python | gpl-2.0 | 2,493 | 0.006418 | # -*- python -*-
# Copyright (C) 2009-2017 Free Software Foundation, 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 License, or
# (at your option) any later versio... | directory name.
if prefix[-1] != '/':
prefix = os.path.dirname (prefix) + '/'
# Strip off the prefix.
pythondir = pythondir[len (pr | efix):]
libdir = libdir[len (prefix):]
# Compute the ".."s needed to get from libdir to the prefix.
dotdots = ('..' + os.sep) * len (libdir.split (os.sep))
objfile = gdb.current_objfile ().filename
dir_ = os.path.join (os.path.dirname (objfile), dotdots, pythondir)
if not dir_ in sys.path:
... |
veltzer/demos-python | src/examples/short/environment_variables/simple.py | Python | gpl-3.0 | 458 | 0.002183 | #!/usr/ | bin/env python
"""
A simple example of how to get or set environment variables from python
"""
import os
print(os.environ['USER'])
if 'HOSTNAME' in os.environ:
print(os.environ['HOSTNAME'])
else:
print(
'you dont have a HOSTNAME in your environment, it is probably just a shell variable')
# lets dele... | (k, v)
|
Fantomas42/django-emoticons | emoticons/tests/settings.py | Python | bsd-3-clause | 392 | 0 | """Settings for testing em | oticons"""
DATABASES = {
'default': {'NAME': 'emoticons.db',
'ENGINE': 'django.db.backends.sqlite3'}
}
TEMP | LATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
}
]
INSTALLED_APPS = [
'emoticons',
'django.contrib.staticfiles'
]
SECRET_KEY = 'secret-key'
STATIC_URL = '/'
|
alxgu/ansible | lib/ansible/modules/network/netvisor/pn_access_list_ip.py | Python | gpl-3.0 | 4,598 | 0.00087 | #!/usr/bin/python
# Copyright: (c) 2018, Pluribus Networks
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['... | ss-list-ip.
required: True
choices: ["present", "absent"]
pn_ip:
description:
- IP associated with the access list.
required: False
default: '::'
type: str
pn_name:
| description:
- Access List Name.
required: False
type: str
"""
EXAMPLES = """
- name: access list ip functionality
pn_access_list_ip:
pn_cliswitch: "sw01"
pn_name: "foo"
pn_ip: "172.16.3.1"
state: "present"
- name: access list ip functionality
pn_access_list_ip:
pn_cliswitch: "s... |
mschlaipfer/z3 | scripts/mk_mem_initializer_cpp.py | Python | mit | 1,138 | 0.002636 | #!/usr/bin/env python
"""
Scans the source directories for
memory initializers and finalizers and
emits and implementation of
``void mem_initialize()`` and
``void mem_finalize()`` into ``mem_initializer.cpp``
in the destination directory.
"""
import mk_genfile_common
import argparse
import logging
import os
import sys
... | , help="destination direct | ory")
parser.add_argument("source_dirs", nargs="+",
help="One or more source directories to search")
pargs = parser.parse_args(args)
if not mk_genfile_common.check_dir_exists(pargs.destination_dir):
return 1
for source_dir in pargs.source_dirs:
if not mk_genfile... |
hakancelik96/coogger | coogger/utils.py | Python | mit | 208 | 0 | f | rom django.shortcuts import render
from django.urls import resolve
def just_redirect_by_name(request):
url_name = resolve(request.path_info).url_name
return render(request, f"{url_name}.html", {}) | |
Alshain-Oy/Cloudsnake-Application-Server | clients/client_analytics_clear.py | Python | apache-2.0 | 451 | 0.019956 |
#!/usr/bin/env python
# Cloudsnake Application server
# Licensed under Apache Licen | se, see license.txt
# Author: Markus Gronholm <[email protected]> Alshain Oy
import libCloudSnakeClient as SnakeClient
import pprint, sys, time
client = SnakeClient.CloudSnakeClient( 'http://localhost:8500', sys.argv[ 1 ] )
mapped_object = SnakeClient.CloudSnakeMapper( client )
#pprint.p | print( mapped_object.dump_analytics() )
mapped_object.clear_analytics()
|
jorisvandenbossche/numpy | numpy/doc/constants.py | Python | bsd-3-clause | 9,291 | 0.001938 | # -*- coding: utf-8 -*-
"""
=========
Constants
=========
.. currentmodule:: numpy
NumPy includes several constants:
%(constant_list)s
"""
#
# Note: the docstring is autogenerated.
#
from __future__ import division, absolute_import, print_function
import textwrap, re
# Maintain same format as in numpy.add_newdocs
... | ements are finite (not one of Not a Number,
positive infinity and negative infinity)
Notes
-----
NumPy uses the IEEE Standard for Binary Floating-Point for Arithmetic
(IEEE 754). This means that Not a Number is not equivalent to infinity.
Also that positive infinity is not equivalent to negativ... | finity.
`Inf`, `Infinity`, `PINF` and `infty` are aliases for `inf`.
Examples
--------
>>> np.inf
inf
>>> np.array([1]) / 0.
array([ Inf])
""")
add_newdoc('numpy', 'nan',
"""
IEEE 754 floating point representation of Not a Number (NaN).
Returns
-------
y : A floa... |
jtyuan/racetrack | tests/configs/tgen-dram-ctrl.py | Python | bsd-3-clause | 3,365 | 0.005944 | # Copyright (c) 2012 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality ... | OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Andreas Hansson
import m5
from m5.objects import *
# both traffic generator and communication monitor are only available
# if we have p | rotobuf support, so potentially skip this test
require_sim_object("TrafficGen")
require_sim_object("CommMonitor")
# even if this is only a traffic generator, call it cpu to make sure
# the scripts are happy
cpu = TrafficGen(config_file = "tests/quick/se/70.tgen/tgen-dram-ctrl.cfg")
# system simulated
system = System(... |
max1k/cbs | p311/migrations/0004_auto_20150325_1306.py | Python | gpl-2.0 | 781 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('p311', '0003_auto_20150323_1217'),
]
operations = [
migrations.RenameField(
model_name='commoninfo',
| old_name='date',
new_name='mod_date',
),
migrations.AddField(
model_name='commoninfo',
name='doc_date',
field=models.DateField(null=True),
preserve_default=True,
),
migrations.AlterField(
model_name='result',... | ength=250),
preserve_default=True,
),
]
|
kaslusimoes/SummerSchool2016 | data/Multiple Variation/Scale Free/heatmap.py | Python | apache-2.0 | 712 | 0.030899 | from pickle import load
import os
import matplotlib.pyplot as plt
import numpy as np
class Data:
def __init__(self):
self.m_list1 = []
self.m_l | ist2 = []
p = './data/'
m1 = []
m2 = []
for _,_,c in os.walk(p):
for x in c:
print('\n',x,'\n')
f = open(os.path.join(p,x), 'r')
d = load(f)
lm = [x for _,_,_,_,x in d.m_list1]
hm = np.sum(lm,0)/10.
m1.append(hm)
lm = [x for _,_,_,_,x in d.m_list2]
hm = np.sum(lm,0)/10.
m2.appe... | ()
plt.show()
plt.imshow(sm2, extent=[1, 2, -1, 0], aspect="auto", origin="lower")
plt.colorbar()
plt.show()
|
neilb14/featurewise | scripts/generate_usage.py | Python | mit | 2,293 | 0.027911 | import simpy
import datetime
import random
from datetime import timedelta
end_of_time = 60*60*24*365
def working_hours(current_time):
return current_time.hour < 17 and current_time.hour > 8
def linear_increase(now, min_duration, max_duration):
time_left = end_of_time - now
return min_duration + max_duration * ... | _time
random_dura | tion = lambda x,min_duration,max_duration : random.gauss((max_duration-min_duration)/2, (max_duration-min_duration)/(6))
increasing_duration = lambda x,min_duration,max_duration : linear_increase(x,min_duration,max_duration)
decreasing_duration = lambda x,min_duration,max_duration : linear_decrease(x,min_duration,max_d... |
vicky2135/lucious | src/oscar/templatetags/basket_tags.py | Python | bsd-3-clause | 829 | 0 | from django import template
from oscar.core.compat import assignment_tag
from oscar.core.loa | ding import get_class, get_model
AddToBasketForm = get_class('basket.forms', 'AddToBasketForm')
SimpleAddToBasketForm = get_class('basket.forms', 'SimpleAddToBasketForm')
Product = get_model('catalogue', 'product')
register = template.Library()
QNT_SINGLE, QNT_MULTIPLE = 'single', 'multiple'
@assignment_tag(regist... | type='single'):
if not isinstance(product, Product):
return ''
initial = {}
if not product.is_parent:
initial['product_id'] = product.id
form_class = AddToBasketForm
if quantity_type == QNT_SINGLE:
form_class = SimpleAddToBasketForm
form = form_class(request.basket, pr... |
zhantyzgz/polaris | plugins/lastfm.py | Python | gpl-2.0 | 2,882 | 0.002434 | # Made by zhantyzgz and fixed by me (luksireiku)
from core.utils import *
commands = [
('/nowplaying', ['user'])
]
description = 'Returns what you are or were last listening to. If you specify a username, info will be returned for that username.'
shortcut = '/np'
def run(m):
username = get_input(m)
if n... | tatus_code != 200:
send_alert('<i>%s</i>\n%s' % (lang.errors.connection, res_yt.text))
return send_message(m, lang.errors.connection)
youtube = json.loads(res_yt.text)
keyboard = {}
if len(youtube['items']) > 0:
keyboard['inline_keyboard'] = [
[
{
... | ' % youtube['items'][0]['id']['videoId']
}
]
]
send_message(m, result, markup='HTML', preview=False, keyboard=keyboard)
|
abramhindle/UnnaturalCodeFork | python/testdata/launchpad/lib/lp/translations/tests/test_translationimportqueue.py | Python | agpl-3.0 | 30,965 | 0.000904 | # Copyright 2009-2011 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
__metaclass__ = type
from operator import attrgetter
import os.path
import transaction
from zope.component import getUtility
from zope.security.proxy import removeSecurityPr... | RosettaImportStatus.DELETED,
RosettaImportStatus.FAILED,
RosettaImportStatus.IMPORTED,
RosettaImportStatus.NEEDS_INFORMATION,
RosettaImportStatus.NEEDS_REVIEW,
]
self._switch_dbuser()
# Do *not* use assertContentEqual here, as the order matt... | for status in possible_statuses])
def test_canSetStatus_non_admin(self):
# A non-privileged users cannot set any status.
some_user = self.factory.makePerson()
self._assertCanSetStatus(some_user, self.entry,
# A B D F I NI NR
[False, F... |
google-research/google-research | simulation_research/traffic/file_util_test.py | Python | apache-2.0 | 5,630 | 0.002131 | # coding=utf-8
# Copyright 2022 The Google Research 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 applicab... | data['second']['B'] = [1, 2, 3]
data['second']['C'] = [1, 2, 3]
data['thi | rd']['C'] = [1, 2, 3]
data['third']['D'] = [1, 2, 3]
data['path'] = 'asdfas/asdf/asdfasdf/'
file_util.save_variable(file_path, data)
actual_variable = file_util.load_variable(file_path)
self.assertEqual(data, actual_variable)
self.assertIsInstance(actual_variable, dict)
# Case 3: Large arra... |
rohitranjan1991/home-assistant | homeassistant/components/saj/sensor.py | Python | mit | 8,049 | 0.000621 | """SAJ solar inverter interface."""
from __future__ import annotations
from datetime import date
import logging
import pysaj
import voluptuous as vol
from homeassistant.components.sensor import (
PLATFORM_SCHEMA,
SensorDeviceClass,
SensorEntity,
SensorStateClass,
)
from homeassistant.const import (
... | CONF_NAME): cv.string,
vol.Optional(CONF_TYPE, default=INVERTER_TYPES[0]): vol. | In(INVERTER_TYPES),
vol.Inclusive(CONF_USERNAME, "credentials"): cv.string,
vol.Inclusive(CONF_PASSWORD, "credentials"): cv.string,
}
)
async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoTyp... |
flaviovdf/vodlibs | vod/learn/cluster.py | Python | mit | 2,393 | 0.00794 | # -*- coding: utf8
'''
Common code for clustering tasks
'''
from __future__ import division, print_function
from sklearn.cluster import KMeans
from sklearn.cluster import MiniBatchKMeans
from sklearn.metrics import pairwise
from vod.stats.ci import half_confidence_interval_size
import numpy as np
def kmeans_betacv(... | inter_array = np.zeros(n_runs)
intra_array = np.zeros(n_runs)
for i in xrange(n_runs):
#Run K-Means
algorithm.fit(data)
centers = algorithm.cluster_centers_
labels = algorithm.labels_
#KMeans in sklearn uses euclidean
dist_centers = pairwise.... | #Inter distance
mean_dist_between_centers = np.mean(dist_centers)
inter_array[i] = mean_dist_between_centers
#Intra distance
dist_all_centers = algorithm.transform(data)
intra_dists = []
for doc_id, cluster in enumerate(labels):
dist = dist_all_center... |
bopowers/MikenetGUI | lib/tabs.py | Python | gpl-3.0 | 63,418 | 0.006339 | '''
Copyright (C) 2013-2014 Robert Powers
This file is part of MikeNetGUI.
MikeNetGUI is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Mike... | box)
#props_layout.addRow('',defau | lts_btn)
props.setLayout(props_layout)
# connect signals
script_box.editingFinished.connect(self.updateTabName)
#..............................................................
# START BUTTON
self.start_btn = StartButton(self)
self.start_btn.clicked.connect(self.... |
lmazuel/azure-sdk-for-python | azure-mgmt-relay/tests/test_azure_mgmt_wcfrelay.py | Python | mit | 7,326 | 0.006144 | # coding: utf-8
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#---------------------------------------------------------------------... | Create a Namespace |
namespace_name = "testingpythontestcaseeventhubnamespaceEventhub"
namespaceparameter = RelayNamespace(location, {'tag1': 'value1', 'tag2': 'value2'}, Sku(SkuTier.standard))
creatednamespace = self.relay_client.namespaces.create_or_update(resource_group_name, namespace_name, namespaceparameter)... |
LumPenPacK/NetworkExtractionFromImages | win_build/nefi2_win_amd64_msvc_2015/site-packages/numpy/core/function_base.py | Python | bsd-2-clause | 6,518 | 0 | from __future__ import division, absolute_import, print_function
__all__ = ['logspace', 'linspace']
from . import numeric as _nx
from .numeric import result_type, NaN
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):
"""
Return evenly spaced numbers over a specified interval.
... | in linear space, inste | ad of log space.
Notes
-----
Logspace is equivalent to the code
>>> y = np.linspace(start, stop, num=num, endpoint=endpoint)
... # doctest: +SKIP
>>> power(base, y).astype(dtype)
... # doctest: +SKIP
Examples
--------
>>> np.logspace(2.0, 3.0, num=4)
array([ 100. ... |
chemelnucfin/tensorflow | tensorflow/compiler/tests/binary_ops_test.py | Python | apache-2.0 | 57,668 | 0.004526 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | , 0, 0, 0, 6, 7, 8, 9, 10, 0, 0], dtype=dtype))
self._testBinary(
gen_nn_ops.leaky_relu_grad,
np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=dtype),
np.array([0, 0, 0, 0, 0, 0.1, 0.3, 0.5, 0.7, 0.9], dtype=dtype),
expected=np.array([0.2, 0.4, 0.6, 0.8, 1, 6, 7, 8, 9, 10],... | , dtype=dtype),
np.array([[0.1, 0.2, 0.3, 0.4], [0.4, 0.3, 0.2, 0.1]], dtype=dtype),
expected=[
np.array([1.44019, 2.44019], dtype=dtype),
np.array([[-0.067941, -0.112856, -0.063117, 0.243914],
[-0.367941, -0.212856, 0.036883, 0.543914]],
... |
quantmind/pulsar-agile | agile/plugins/docs.py | Python | bsd-3-clause | 2,024 | 0 | import os
from importlib import import_module
from pulsar import ImproperlyConfigured
from cloud import aws
from .. import core
content_types = {'fjson': 'application/json',
'inv': 't | ext/plain'}
class Docs(core.AgileCommand):
"""Requires a valid sphinx installation
"""
description = 'Compile sphinx docs and upload them to aws'
async def run(self, name, config, options):
path = os.path.join(self.repo_path, 'docs')
if not os.path.isdir(path):
raise Impro... | .execute('make', self.cfg.docs)
finally:
os.chdir(self.repo_path)
self.logger.info(text)
if self.cfg.push:
await self.upload()
async def upload(self):
"""Upload documentation to amazon s3
"""
if not self.cfg.docs_bucket:
raise Imp... |
avalentino/PyTables | examples/vlarray4.py | Python | bsd-3-clause | 626 | 0.001597 | #!/usr/bin/env python3
"""Example that shows how to easily save a variable number of atoms w | ith a
VLArray."""
import numpy as np
import tables as | tb
N = 100
shape = (3, 3)
np.random.seed(10) # For reproductible results
f = tb.open_file("vlarray4.h5", mode="w")
vlarray = f.create_vlarray(f.root, 'vlarray1',
tb.Float64Atom(shape=shape),
"ragged array of arrays")
k = 0
for i in range(N):
l = []
for j... |
cfh294/WawaGeoScraper | utils/scraping/__init__.py | Python | gpl-3.0 | 5,149 | 0.000583 | """
scraping
the utility functions for the actual web scraping
"""
import ssl
import datetime
import requests
import re
# this is the endpoint that my new version of this program will
# abuse with possible store ids. this is a much more reliable "darts at the wall"
# technique than the previous location-based one
QUE... | om testing, I have confirmed certain "series" of store IDs
# 0000 | series are all old stores in PA, NJ, MD, DE, and VA
# 5000 series are all stores in FL
# 8000 series are all new stores in PA, NJ, MD, DE, and VA
POSSIBLE_STORE_NUMS = list(range(5000, 6000))
POSSIBLE_STORE_NUMS.extend(list(range(0, 1000)))
POSSIBLE_STORE_NUMS.extend(list(range(8000, 9000)))
# currently only tracking ... |
filiperodriguez/sylvanian | sylvanian_family/config.py | Python | mit | 262 | 0.003817 | # config
#configure our database
class Configuration(object):
DATABASE = | {
'name': 'sylvanian',
'engine': 'peewee.MySQLDatabase',
'user': 'sylvanian',
'passwd': '68zL7VeS0W',
}
DEBUG = True
| SECRET_KEY = 'ssshhhh'
|
teddywing/pubnub-python | python/examples/subscribe_group.py | Python | mit | 1,925 | 0.007273 | ## www.pubnub.com - PubNub Real-time push service in the cloud.
# coding=utf8
## PubNub Real-time Push APIs and Notifications Framework
## Copyright (c) 2010 Stephen Blum
## http://www.pubnub.com/
import sys
from pubnub import Pubnub as Pubnub
publish_key = len(sys.argv) > 1 and sys.argv[1] or 'demo'
subscribe_key ... | bc', callback=callback_abc, error=error,
connect=connect_abc, reconnect=reconnect, disconnect=disconnect)
pubnub.subscribe(channels='d', callb | ack=callback_d, error=error,
connect=connect_d, reconnect=reconnect, disconnect=disconnect)
pubnub.start()
|
CloudVLab/professional-services | tools/asset-inventory/asset_inventory/export.py | Python | apache-2.0 | 7,690 | 0.00117 | #!/usr/bin/env python
#
# Copyright 2019 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 ... | = asset_v1.types.OutputConfig()
output_config.gcs_destination.uri = gcs_destination
operation = Clients.cloudasset().export_assets(
parent,
output_config,
content_type=content_type,
asset_types=asset_types)
return operation.result()
def export_to_gcs_content_types(parent, g... | asset_types):
"""Export each asset type into a GCS object with the GCS prefix.
Will call `export_to_gcs concurrently` to perform an export, once for each
content_type.
Args:
parent: Project id or organization number.
gcs_destination: GCS object prefix to export to ... |
subho007/androguard | tests/test_ins.py | Python | apache-2.0 | 5,377 | 0.015064 | #!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr>
# All rights reserved.
#
# Androguard 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,... | : {
0xe : ("invoke-virtual/range", [['v', 0], ['v', 1], ['v', 2], ['v', 3], ['v', 4], ['v', 5], ['meth@', 53, | 'Ltests/androguard/TestInvoke;', '(I I I I I)', 'I', 'TestInvoke5']]),
},
"Ltests/androguard/TestInvoke; TestInvoke5 (I I I I I)I" : {
0x10 : ("invoke-virtual/range", [['v', 0], ['v', 1], ['v', 2], ['v', 3], ['v', 4], ['v', 5], ['v', 6], ['meth@', 54, 'Ltests/a... |
interfax/interfax-python | tests/test_files.py | Python | mit | 3,313 | 0.000302 | from mimetypes import guess_extension
from uuid import UUID
from interfax.files import File, Files
from interfax.response import Document
try:
from unittest.mock import Mock, patch, call
except ImportError:
from mock import Mock, patch, call
class TestFiles(object):
def setup_method(self, method):
... | assert f.mime_type == mime_type
assert f.body == data
assert f.file_tuple() == (None, data, mime_type, None)
def test_with_uri(self, fake):
data = fake.uri()
f = File(self.client, data)
assert f.headers == {'Content-Location': data}
| assert f.mime_type is None
assert f.body is None
assert f.file_tuple() == (None, '', None, {'Content-Location': data})
def test_with_path(self, fake):
data = './tests/test.pdf'
f = File(self.client, data)
with open(data, 'rb') as fp:
content = fp.read()
... |
unnikrishnankgs/va | venv/lib/python3.5/site-packages/nbformat/v4/tests/test_json.py | Python | bsd-2-clause | 3,764 | 0.00186 | from base64 import decodestring
import json
from unittest import TestCase
from ipython_genutils.py3compat import unicode_type
from ..nbjson import reads, writes
from .. import nbjson
from .nbexamples import nb0
from . import formattest
class TestJSON(formattest.NBFormatTest, TestCase):
nb0_ref = None
ext =... | # JSON outputs should be left alone
assert json_value == output_ref[key]
def test_read_png(self):
"""PNG output data is b64 unicode"""
s = writes(nb0)
nb1 = nbjson.reads(s)
found_png = False
for cell in nb1.cells:
| if not 'outputs' in cell:
continue
for output in cell.outputs:
if not 'data' in output:
continue
if 'image/png' in output.data:
found_png = True
pngdata = output.data['image/png']
... |
vilemnovak/blendercam | scripts/addons/cam/utils.py | Python | gpl-2.0 | 65,143 | 0.003684 | # blender CAM utils.py (c) 2012 Vilem Novak
#
# ***** BEGIN GPL LICENSE BLOCK *****
#
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any... | scale.y, coord[2]/ob.scale.z))
worldCoord = mw @ Vector((coord[0], coord[1], coord[2]))
minx = min(minx, worldCoord.x)
miny = min(miny, worldCoord.y)
minz = min(minz, worldCoord.z)
maxx = max(maxx, worldCoord.x)
maxy = max(maxy, worldCoord.y)
maxz = max(maxz, worl... | turn minx, miny, minz, maxx, maxy, maxz
def getOperationSources(o):
if o.geometry_source == 'OBJECT':
# bpy.ops.object.select_all(action='DESELECT')
ob = bpy.data.objects[o.object_name]
o.objects = [ob]
ob.select_set(True)
bpy.context.view_layer.objects.active = ob
... |
shakamunyi/sahara | sahara/db/migration/alembic_migrations/versions/026_add_is_public_is_protected.py | Python | apache-2.0 | 2,335 | 0.000857 | # Copyright 2015 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 ... | sa.Column('is_public', sa.Boolean()))
op.add_column('jobs',
sa.Column('is_public', sa.Boolean()))
op.add_column('job_binary_internal',
sa.Column('is_public', sa.Boolean()))
op.add_column('job_binaries',
sa.Column('is_public', sa.Boolean(... | sa.Column('is_protected', sa.Boolean()))
op.add_column('node_group_templates',
sa.Column('is_protected', sa.Boolean()))
op.add_column('data_sources',
sa.Column('is_protected', sa.Boolean()))
op.add_column('job_executions',
sa.Column('is_prot... |
JackDanger/sentry | src/sentry/web/forms/edit_organization_member.py | Python | bsd-3-clause | 741 | 0.00135 | from __future__ import absolute_import
from sentry.models import (
AuditLogEntry,
AuditLo | gEntryEvent,
)
from sentry.web.forms.base_organization_member import BaseOrganizationMemberForm
class EditOrganizationMemberForm(BaseOrganizationMemberForm):
def save(self, actor, organization, ip_address=None):
om = super(EditOrganizationMemberForm, self).save()
self.save_team_assignments(om)
... | target_user=om.user,
event=AuditLogEntryEvent.MEMBER_EDIT,
data=om.get_audit_log_data(),
)
return om
|
xyfeng/average_portrait | face_swap.py | Python | mit | 6,296 | 0.002065 | """
This is the code behind the Switching Eds blog post:
http://matthewearl.github.io/2015/07/28/switching-eds-with-python/
See the above for an explanation of the code below.
To run the script you'll need to install dlib (http://dlib.net) including its
Python bindings, and OpenCV. You'll also need to obtain the tr... | r = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(PREDICTOR_PATH)
class TooManyFaces(Exception):
pass
class NoFaces(Exception):
pass
def get_landmarks(im):
rects = detector(im, 1)
if len(rects) > 1:
raise TooManyFaces
if len(rects) == 0:
raise NoFaces
ret... | ef annotate_landmarks(im, landmarks):
im = im.copy()
for idx, point in enumerate(landmarks):
pos = (point[0, 0], point[0, 1])
cv2.putText(im, str(idx), pos,
fontFace=cv2.FONT_HERSHEY_SCRIPT_SIMPLEX,
fontScale=0.4,
color=(0, 0, 255))
... |
potatolondon/djangoappengine-1-4 | db/compiler.py | Python | bsd-3-clause | 22,103 | 0.001086 | from functools import wraps
import sys
import logging
from django.db.models.fields import AutoField
from django.db.models.sql import aggregates as sqlaggregates
from django.db.models.sql.constants import LOOKUP_SEP, MULTI, SINGLE
from django.db.models.sql.where import AND, OR
from django.db.utils import DatabaseError,... | if not isinstance(value, (tuple, list)):
value = [value]
pks = [pk for pk in value if pk is not None]
if field.rel:
pks = [ Key.from_path(self.db_table, pk.id_or_name()) for pk in pks ]
if negated:
self.excluded_pks = pks
... | self.included_pks = pks
return
# We check for negation after lookup_type isnull because it
# simplifies the code. All following lookup_type checks assume
# that they're not negated.
if lookup_type == 'isnull':
if (negated and value) or not value:
|
RalfBarkow/Zettelkasten | venv/lib/python3.9/site-packages/pip/_vendor/distlib/compat.py | Python | gpl-3.0 | 41,408 | 0.002198 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2017 Vinay Sajip.
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
from __future__ import absolute_import
import os
import re
import sys
try:
import ssl
except ImportError: # pragma: no cover
s... | with('xn--'):
# RFC 6125, section 6.4.3, subitem 3.
# The client SHOULD NOT attempt to match a presented identifier
# where the wildcard character is embedded within an A-label or
# U-label of an internationalized domain name.
pats.append(re.escape(leftmost))
... | tmost).replace(r'\*', '[^.]*'))
# add the remaining fragments, ignore any wildcards
for frag in remainder:
pats.append(re.escape(frag))
pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE)
return pat.match(hostname)
def match_hostname(cert, hostname):
... |
yannrouillard/weboob | modules/ina/backend.py | Python | agpl-3.0 | 1,901 | 0.001578 | # -*- coding: utf-8 -*-
# Copyright(C) 2010-2011 Christophe Benz
#
# This file is part of weboob.
#
# weboob 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 yo... | fero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
| # along with weboob. If not, see <http://www.gnu.org/licenses/>.
from weboob.capabilities.video import ICapVideo
from weboob.tools.backend import BaseBackend
from .browser import InaBrowser
from .video import InaVideo
__all__ = ['InaBackend']
class InaBackend(BaseBackend, ICapVideo):
NAME = 'ina'
MAINTAI... |
OnroerendErfgoed/skosprovider_getty | setup.py | Python | mit | 1,278 | 0 | import os
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
CHANGES | = open(os.path.join(here, 'CHANGES.rst')).read()
| packages = [
'skosprovider_getty'
]
requires = [
'skosprovider>=1.1.0',
'requests',
'rdflib'
]
setup(
name='skosprovider_getty',
version='1.0.0',
description='Skosprovider implementation of the Getty Vocabularies',
long_description=README + '\n\n' + CHANGES,
long_description_conten... |
wzhfy/spark | python/pyspark/__init__.py | Python | apache-2.0 | 4,687 | 0.00192 | #
# 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 us... | class:`SparkFiles`:
Access files shipped with jobs.
- :class:`StorageLevel`:
Finer-grained cache persistence levels.
- :class:`TaskContext`:
Information about th | e current running task, available on the workers and experimental.
- :class:`RDDBarrier`:
Wraps an RDD under a barrier stage for barrier execution.
- :class:`BarrierTaskContext`:
A :class:`TaskContext` that provides extra info and tooling for barrier execution.
- :class:`BarrierTaskInfo`:
Inform... |
esarafianou/rupture | backend/breach/tests/test_views.py | Python | mit | 8,595 | 0.001862 | from django.test import Client, TestCase
from django.core.urlresolvers import reverse
from breach.models import Target, Victim, Round, SampleSet
from breach.views import TargetView, VictimListView
import json
from binascii import hexlify
class ViewsTestCase(TestCase):
def setUp(self):
self.client = Client... | recordscardinality=1,
method=1
)
self.target2 = Target.objects.create(
name='ruptureit2',
endpoint='https://ruptureit.com/test.php?reflection=%s',
prefix='imper',
alphabet='abcdefghijklmnopqrstuvwxyz',
| secretlength=9,
alignmentalphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZ',
recordscardinality=1,
method=2
)
self.target1_data = {
'name': 'ruptureit',
'endpoint': 'https://ruptureit.com/test.php?reflection=%s',
'prefix': 'imper',
... |
Distrotech/yum | yum/__init__.py | Python | gpl-2.0 | 305,350 | 0.004375 | #!/usr/bin/python -tt
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that i... | ndation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# Copyright 2005 Duke University
"""
The Yum RPM software updater.
"""
import os
import os.path
import rpm
import sys
def _rpm_ver_atleast(vertup):
""" Check if rpm is at least the current vertup. Can return False/True/Non | e
as rpm hasn't had version info for a long time. """
if not hasattr(rpm, '__version_info__'):
return None
try:
# 4.8.x rpm used strings for the tuple members, so convert.
vi = tuple([ int(num) for num in rpm.__version_info__])
return vi >= vertup
except:
retu... |
savi-dev/heat | heat/tests/test_neutron.py | Python | apache-2.0 | 46,371 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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... | tributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mox
from testtools import skipIf
from heat.engine import clients
from heat.common import exce... | esources.neutron import net
from heat.engine.resources.neutron import subnet
from heat.engine.resources.neutron import router
from heat.engine.resources.neutron.neutron import NeutronResource as qr
from heat.openstack.common.importutils import try_import
from heat.tests.common import HeatTestCase
from heat.tests import... |
pythondigest/pythondigest | digest/tests/test_import_importpython.py | Python | mit | 2,657 | 0.001505 | from django.test import TestCase
from mock import patch
from digest.management.commands.import_importpython import ImportPythonParser
from digest.utils import MockResponse, read_fixture
class ImportPythonWeeklyTest(TestCase):
def setUp(self):
self.url = "http://importpython.com/newsletter/no/60/"
... | self.assertEqual(block['title'],
"Project Jupyter and IPython Podcast Interview")
self.assertEqual(block['content'],
| "One of the fastest growing areas in Python is scientific computing. In scientific computing with Python, there are a few key packages that make it special. These include NumPy / SciPy / and related packages. The one that brings it all together, visually, is IPython (now known as Project Jupyter). ... |
claesenm/HPOlib | HPOlib/format_converter/convert.py | Python | gpl-3.0 | 4,811 | 0.003326 | #!/usr/bin/env python
##
# wrapping: A program making it easy to use hyperparameter
# optimization software.
# Copyright (C) 2013 Katharina Eggensperger and Matthias Feurer
#
# 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
# ... | er
import os
from string import upper
import sys
import tempfile
import smac_to_spearmint
import tpe_to_smac
__authors__ = ["Katharina Eggensperger", "Matthias Feurer"]
__contact__ = "automl.org"
def smac_to_spearmint_helper(space, save=""):
# print "Convert %s from SMAC to SPEARMINT" % space
return smac_t... | f smac_to_tpe_helper(space, save=""):
print "This is not yet implemented"
def spearmint_to_smac_helper(space, save=""):
print "This is not yet implemented"
def spearmint_to_tpe_helper(space, save=""):
print "This is not yet implemented"
def tpe_to_spearmint_helper(space, save=""):
try:
imp... |
florianfesti/boxes | boxes/generators/dispenser.py | Python | gpl-3.0 | 4,538 | 0.001544 | #!/usr/bin/env python3
# Copyright (C) 2013-2016 Florian Festi
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.... | tion="store", type=ArgparseEdgeType("Fh"),
choices=list("Fh"), default="F",
help="edges used for holding the front panels and back")
def render(self):
x, y, h, hs = self.x, self.y, self.h, self.slotheight
hb = self.bottomheight
t = self.thickness
se = self.... | = hb + 0.5*t
with self.saved_context():
self.rectangularWall(x, y, [fe, "f", "f", "f"],
label="Floor", move="right")
self.rectangularWall(x, y, "eeee", label="Lid bottom", move="right")
self.rectangularWall(x, y, "EEEE", label="Lid top", move... |
paulhtremblay/boto_emr | examples/process_crawl_text1.py | Python | mit | 1,482 | 0.013495 | from pyspark.sql import Row
#import boto_emr.parse_marc as parse_marc
from pyspark import SparkContext
import datetime
def process_by_fields(l):
host = None
date = None
text = None
ip_address = None
warc_type = None
for line in l[1]:
fields = line.split(':', 1)
if fields and le... | ip_address = fields[1].strip()
elif fields[0] == 'WARC-Type':
warc_type = fields[1].strip()
else:
text = line
return Row(host =host, date = date, text = text,
ip_address = ip_address, warc_type = warc_type)
def process_file(my_iter):
the_id ... | es = chunk[1].split("\n")
for line in lines:
if line[0:15] == 'WARC-Record-ID:':
the_id = line[15:]
final.append(Row(the_id = the_id, line = line))
return iter(final)
def get_hdfs_path():
return "/mnt/temp"
sc = SparkContext(appName = "test crawl {0}".format(d... |
xlqian/navitia | source/jormungandr/jormungandr/interfaces/v1/decorators.py | Python | agpl-3.0 | 1,461 | 0.000684 | # This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and open public transport:
# a non ending quest to the responsive locomotion way of traveling!
#... | s published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# G... | not, see <http://www.gnu.org/licenses/>.
#
# Stay tuned using
# twitter @navitia
# channel `#navitia` on riot https://riot.im/app/#/room/#navitia:matrix.org
# https://groups.google.com/d/forum/navitia
# www.navitia.io
from __future__ import absolute_import, print_function, unicode_literals, division
from jormungandr.... |
wooga/play-deliver | playdeliver/listing.py | Python | mit | 1,526 | 0 | """This module helps for uploading and downloading listings from/to play."""
import os
import json
from file_util import mkdir_p
from file_util import list_dir_abspath
def upload(client, source_dir):
"""Upload listing files in source_dir. folder herachy."""
print('')
print('upload store listings')
pri... | '')
print('download store listings')
print('---------------------')
listings = client.list('listings')
for listing in listings:
path = os.path.join(target_dir, 'listings', listing['language'])
mkdir_p(path)
with open(os.path.join(path, 'listing.json'), 'w') as outfile | :
print("save listing for {0}".format(listing['language']))
json.dump(
listing, outfile, sort_keys=True,
indent=4, separators=(',', ': '))
|
richardcornish/django-itunespodcast | podcast/migrations/0007_auto_20170920_2212.py | Python | bsd-3-clause | 429 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09 | -20 22:12
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('podcast', '0006_auto_20170920_1833'),
]
operations = [
migrati | ons.RenameField(
model_name='episode',
old_name='summary',
new_name='notes',
),
]
|
hes19073/hesweewx | bin/user/hausWD.py | Python | gpl-3.0 | 15,327 | 0.004176 | # -*- coding: utf-8 -*-
##This program is free software; you can redistribute it and/or modify it under
##the terms of the GNU General Public License as published by the Free Software
##Foundation; either version 2 of the License, or (at your option) any later
##version.
##
##This program is distributed in the hope tha... | acket.update(data_x)
def new_archive_ | record(self, event):
data_x = {}
if 'gasTotal' in event.record:
data_x['gasZ_m3'] = event.record['gasTotal']
data_x['gasZ_kWh'] = event.record['gasTotal'] * self.BrennWert * self.ZustandsZahl
data_x['gasZ_preis'] = event.record['gasTotal'] * self.BrennWert * self.Zus... |
zhaobin19918183/zhaobinCode | zhaobin/mysite/photologue/management/commands/plcache.py | Python | gpl-3.0 | 1,406 | 0.002134 | from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
from photologue.models import PhotoSize, ImageModel
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--reset', '-r', action='store_true', dest='reset', help='Reset phot... | return create_cache(args, options)
def create_cache(sizes, options):
"""
Creates | the cache for the given files
"""
reset = options.get('reset', None)
size_list = [size.strip(' ,') for size in sizes]
if len(size_list) < 1:
sizes = PhotoSize.objects.filter(pre_cache=True)
else:
sizes = PhotoSize.objects.filter(name__in=size_list)
if not len(sizes)... |
3dfxsoftware/cbss-addons | product_do_merge/wizard/__init__.py | Python | gpl-2.0 | 26 | 0 | import base_product_merg | e
| |
xeroc/python-graphenelib | tests/test_transactions.py | Python | mit | 11,452 | 0.001834 | # -*- coding: utf-8 -*-
import unittest
from pprint import pprint
from binascii import hexlify
from datetime import datetime, timedelta, timezone
from .fixtures import (
formatTimeFromNow,
timeformat,
Account_create,
Operation,
Signed_Transaction,
MissingSignatureForKey,
PrivateKey,
Pu... | "ac1896bd7c3d610500000000000000000120508168b9615d48bd1184"
"6b3b9bcf000d1424a7915fb1cfa7f61150b5435c060b3147c056a1f8"
"89633c43d1b88cb463e8083fa2b62a585af9e1b7a7c23d83ae78"
)
self.doit()
| def test_create_account_sort_keys(self):
self.op = Account_create(
**{
"fee": {"amount": 1467634, "asset_id": "1.3.0"},
"registrar": "1.2. |
won21kr/pydokan | src/old/dokanMemTools.py | Python | gpl-3.0 | 1,950 | 0.029744 | from ctypes import *
debug = False
def setDwordByPoint(valueAddress, value):
'''
valueAddress[0] = value && 0xff
valueAddress[1] = (value >> 8) && 0xff
'''
i = 0
while i < 4:
#print value, i
memset(valueAddress+i, value&0xff | , 1)
i += 1
value >>= 8
return valueAddress + 4
def setLongLongByPoint(valueAddress, value):
setDwordByPoint(valueAddress, value & 0xffffffff)
setDwordByPoint(valueAddress+4, (value>>32) & 0xffffffff)
return valueAddress + 8
def setStringByPoint(valueAddress, value, length):
cnt = 0
for i in... | 2 > length:
break
#0061: u'a' -> 0x00000000: 61, 0x00000001: 00
memset(valueAddress, ord(i)&0xff, 1)
valueAddress += 1
memset(valueAddress, (ord(i)>>8)&0xff, 1)
valueAddress += 1
memset(valueAddress, 0, 1)
valueAddress += 1
memset(valueAddress, 0, 1)
return valueAddress + length
def setFil... |
coderiot/pyexchange | pyexchange/exchange/bitstamp.py | Python | gpl-2.0 | 2,316 | 0 | #!/usr/bin/env python
# encoding: utf-8
from datetime import datetime
from pyexchange.exchange import models
base_url = "https://www.bitstamp.net/api"
class Bitstamp(models.Exchange):
"""Docstring for Bitstamp """
_markets_map = {'btc_usd': 'btc_usd'}
def __init__(self, market="btc_usd"):
| """@todo: to be defined1
:currency: @todo
"""
self.market = market
def depth(self):
"""@todo: Docstring for depth
:r | eturns: @todo
"""
url = "/".join([base_url, 'order_book/'])
resp = self._request('GET', url).json()
asks = []
for p, a in resp['asks']:
asks.append(models.Order(price=self._create_decimal(p),
amount=self._create_decimal(a)))
... |
sevein/archivematica | src/dashboard/src/components/api/views.py | Python | agpl-3.0 | 22,892 | 0.002272 | # This file is part of Archivematica.
#
# Copyright 2010-2013 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, either version 3 of the ... | lter(sipuuid=unit_uuid).filter(jobtype='Create SIP from transfer objects').exists():
ret['status'] = 'COMPLETE'
# Get SIP UUID
sips = models.File.objects.filter(transfer_id=unit_uuid, sip__isnull=False).values('sip').distinct()
if sips:
ret['sip_uuid'] = sips[0]['sip']
el... | ret['sip_uuid'] = 'BACKLOG'
else:
ret['status'] = 'PROCESSING'
return ret
def status(request, unit_uuid, unit_type):
# Example: http://127.0.0.1/api/transfer/status/?username=mike&api_key=<API key>
if request.method not in ('GET',):
return django.http.HttpResponseNotAllowed(['GET'])
... |
kellinm/blivet | blivet/flags.py | Python | gpl-2.0 | 3,954 | 0.000506 | # flags.py
#
# Copyright (C) 2013 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that... | True
self.ibft = True
self.noiswmd = False
self.gfs2 = True
self.jfs = True
self.reiserfs = True
self.arm_platform = None
se | lf.gpt = False
self.multipath_friendly_names = True
# set to False to suppress the default LVM behavior of saving
# backup metadata in /etc/lvm/{archive,backup}
self.lvm_metadata_backup = True
# whether to include nodev filesystems in the devicetree (only
# meaningful ... |
pyamg/pyamg | pyamg/util/linalg.py | Python | mit | 18,547 | 0.000324 | """Linear Algebra Helper Routines."""
from warnings import warn
import numpy as np
from scipy import sparse
from scipy.sparse.linalg import aslinearoperator
from scipy.linalg import lapack, get_blas_funcs, eig, svd
from .params import set_tol
def norm(x, pnorm='2'):
"""2-norm of a vector.
Parameters
-... | ector
Notes
-----
- currently 1+ order of magnitude faster tha | n scipy.linalg.norm(x), which
calls sqrt(numpy.sum(real((conjugate(x)*x)),axis=0)) resulting in an
extra copy
- only handles the 2-norm and infinity-norm for vectors
See Also
--------
scipy.linalg.norm : scipy general matrix or vector norm
"""
x = np.ravel(x)
if pnorm == '2':
... |
demisto/content | Packs/Vectra/Integrations/Vectra_v2/Vectra_v2.py | Python | mit | 28,976 | 0.003176 | from CommonServerPython import *
# IMPORTS #
import json
import requests
import urllib3
from typing import Dict, List, Union
# Disable insecure warnings
urllib3.disable_warnings()
# CONSTANTS #
MAX_FETCH_SIZE = 50
DATE_FORMAT = "%Y-%m-%dT%H%M" # 2019-09-01T1012
PARAMS_KEYS = {
"threat_score": "t_score",
"th... | mapping protocol to the URL of the proxy.
:param fetch_size: Max number of incidents to fetch in each cycle
:param first_fetch: Fetch only Detections newer than this date
:param c_score_gte: Fetch only Detections with greater/equal Certainty score
| :param t_score_gte: Fetch only Detections with greater/equal Threat score
:param state: Fetch only Detections with matching State (e.g., active, inactive, ignored)
"""
self.state = state
self.t_score_gte = t_score_gte
self.c_score_gte = c_score_gte
self.fetch_size = f... |
mpirnat/adventofcode | day23/day23.py | Python | mit | 2,854 | 0.00035 | #!/usr/bin/env python
"""
Solve day 23 of Advent of Code.
http://adventofcode.com/day/23
"""
class Computer:
def __init__(self):
"""
Our computer has 2 registers, a and b,
and an instruction pointer so that we know
which instruction to fetch next.
"""
self.a = 0
... | lace(',', '').split()
return instruction, arg | s
def hlf(self, register):
"""
Set the register to half its current value,
then increment the instruction pointer.
"""
setattr(self, register, getattr(self, register)//2)
self.ip += 1
def tpl(self, register):
"""
Set the register to triple its cu... |
jasonwee/asus-rt-n14uhp-mrtg | src/lesson_the_internet/urllib_request_upload_files.py | Python | apache-2.0 | 3,434 | 0 | import io
import mimetypes
from urllib import request
import uuid
class MultiPartForm:
"""Accumulate the data to be used when posting a form."""
def __init__(self):
self.form_fields = []
self.files = []
# Use a large random byte string to separate
# parts of the MIME data.
... | a file to be uploaded."""
body = fileHandl | e.read()
if mimetype is None:
mimetype = (
mimetypes.guess_type(filename)[0] or
'application/octet-stream'
)
self.files.append((fieldname, filename, mimetype, body))
return
@staticmethod
def _form_data(name):
return ('Conte... |
XENON1T/pax | pax/plugins/ZLE.py | Python | bsd-3-clause | 6,092 | 0.00394 | import numpy as np
from pax import plugin, datastructure
from pax.dsputils import find_intervals_above_threshold_no_splitting
import matplotlib.pyplot as plt
class SoftwareZLE(plugin.TransformPlugin):
"""Emulate the Zero-length encoding of the CAEN 1724 digitizer
Makes no attempt to emulate the 2-sample wo... | , samples_for_baseline)]
w = np.mean(bs) - w
else:
# This is how the digitizer does it (I think?? | ?)
# Subtract the reference baseline, invert
w = self.config['digitizer_reference_baseline'] - w
if self.debug:
plt.plot(w)
# Get the ZLE threshold
# Note a threshold of X digitizer bins actually means that the data acquisition
... |
markokr/cc | cc/daemon/__init__.py | Python | bsd-2-clause | 1,635 | 0.016514 | import sys
import types
import skytools
from cc.job import CCJob
from cc.daemon.plugins import CCDaemonPlugin
#
# Base class for daemons
#
class CCDaemon (CCJob):
log = skytools.getLogger ('d:CCDaemon')
def find_plugins (self, mod_name, probe_func = None):
""" plugin lookup helper """
p = [... | emonPlugin) and
av.__module__ == m.__name__):
if not probe_func or probe_func (av):
p += [av]
else:
self.log.debug ("plugin %s probing negative", an) |
if not p:
self.log.info ("no suitable plugins found in %s", mod_name)
return p
def load_plugins (self, *args, **kwargs):
""" Look for suitable plugins, probe them, load them.
"""
self.plugins = []
for palias in self.cf.getlist ('plugins'):
pc... |
glenngillen/dotfiles | .vscode/extensions/ms-python.python-2021.5.842923320/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_pytest2.py | Python | mit | 10,660 | 0.002251 | from _pydev_runfiles import pydev_runfiles_xml_rpc
import pickle
import zlib
import base64
import os
from pydevd_file_utils import canonical_normalized_path
import pytest
import sys
import time
try:
from pathlib import Path
except:
Path = None
#==================================================... | py_test_accept_filter = os.environ.get('PYDEV_PYTEST_SKIP')
if py_test_accept_filter:
py_test_accept_filter = pickle. | loads(
zlib.decompress(base64.b64decode(py_test_accept_filter)))
if Path is not None:
# Newer versions of pytest resolve symlinks, so, we
# may need to filter with a resolved path too.
new_dct = {}
for filename, value in... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2021_05_01/operations/_express_route_ports_locations_operations.py | Python | mit | 7,987 | 0.005008 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | at)
return pipeline_response
return ItemPaged(
get_next, extract_data
| )
list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/ExpressRoutePortsLocations'} # type: ignore
def get(
self,
location_name, # type: str
**kwargs # type: Any
):
# type: (...) -> "_models.ExpressRoutePortsLocation"
"""Retrie... |
tensorflow/addons | tensorflow_addons/seq2seq/tests/beam_search_decoder_test.py | Python | apache-2.0 | 22,072 | 0.000951 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | , 0, 2])
res = gather_tree(
predicted_ids,
parent_ids,
max_sequence_lengths=max_sequence_lengths,
end_token=11,
)
np.testing.assert_equal(expected_result, res)
def _test_gather_tree_from_array(depth_ndims=0, merged_batch_beam=False):
array = np.array(
[
... | 5, 6, 7], [8, 9, 10], [11, 12, 0]],
]
).transpose([1, 0, 2])
parent_ids = np.array(
[
[[0, 0, 0], [0, 1, 1], [2, 1, 2], [-1, -1, -1]],
[[0, 0, 0], [1, 1, 0], [2, 0, 1], [0, 1, 0]],
]
).transpose([1, 0, 2])
expected_array = np.array(
[
[... |
Juniper/nova | nova/tests/unit/virt/libvirt/volume/test_iscsi.py | Python | apache-2.0 | 3,046 | 0.000328 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | dev'
connection_info = {'data': {'device_path': device_path}}
conf = libvirt_driver.get_config(connection_ | info, self.disk_info)
tree = conf.format_dom()
self.assertEqual('block', tree.get('type'))
self.assertEqual(device_path, tree.find('./source').get('dev'))
self.assertEqual('raw', tree.find('./driver').get('type'))
self.assertEqual('native', tree.find('./driver').get('io'))
... |
awsdocs/aws-doc-sdk-examples | python/example_code/dynamodb/GettingStarted/MoviesDeleteTable.py | Python | apache-2.0 | 626 | 0.003195 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to delete an Amazon DynamoDB ta | ble.
"""
# snippet-start:[dynamodb.python.codeexample.MoviesDeleteTable]
import boto3
def delete_movie_table(dynamodb=None):
if not dynamodb:
dynamodb = boto3.resource('dynamodb', endpoint_url="http://localhost:8000")
table = dynamodb.Table('Movies')
table.delete()
if __name__ == ... | e.MoviesDeleteTable]
|
GoogleCloudPlatform/cloud-ops-sandbox | tests/provisioning/test_runner.py | Python | apache-2.0 | 830 | 0 | #!/usr/bin/env python3
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this fil | e except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under | the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
test_suite = unittest.TestLoader().discover(pattern='*_test.py', start_dir=... |
cmoutard/mne-python | mne/viz/epochs.py | Python | bsd-3-clause | 62,694 | 0.000175 | """Functions to plot epochs data
"""
# Authors: Alexandre Gramfort <[email protected]>
# Denis Engemann <[email protected]>
# Martin Luessi <[email protected]>
# Eric Larson <[email protected]>
# Jaakko Leppakangas <[email protected]... | None, defaults to `scalings=dict(eeg=1e6, grad=1e13, mag=1e15,
eog=1e6)`
cmap : matplotlib colormap
Colormap.
fig : matplotlib figure | None
Figure instance to draw the image to. Figure must contain two axes for
drawing the single trials and evoked responses. If None a new figure... | ated. Defaults to None.
overlay_times : array-like, shape (n_epochs,) | None
If not None the parameter is interpreted as time instants in seconds
and is added to the image. It is typically useful to display reaction
times. Note that it is defined with respect to the order
of epochs s... |
111pontes/ydk-py | cisco-ios-xe/ydk/models/cisco_ios_xe/_meta/_CISCO_SUBSCRIBER_SESSION_TC_MIB.py | Python | apache-2.0 | 2,087 | 0.01677 |
import re
import collections
from enum import Enum
from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REF | ERENCE_LIST, REFERENCE_LEAFLIST, REFERENCE_IDENTITY_CLASS, REFERENCE_ENUM_CLASS, REFERENCE_BITS, REFERENCE_UNION, ANYXML_CLASS
from ydk.errors import YPYError, YPYModelError
from ydk.providers._importer import _yang_ns
_meta_table = {
'SubsessiontypeEnum' : _MetaInfoEnum('SubsessiontypeEnum', 'ydk.models.cisco... | all':'all',
'other':'other',
'pppSubscriber':'pppSubscriber',
'pppoeSubscriber':'pppoeSubscriber',
'l2tpSubscriber':'l2tpSubscriber',
'l2fSubscriber':'l2fSubscriber',
'ipInterfaceSubscriber':'ipInterfaceSubscriber',
'ipPktSubscriber':'i... |
petrjasek/superdesk-core | superdesk/publish/formatters/__init__.py | Python | agpl-3.0 | 5,788 | 0.001209 | # -*- 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
import loggi... | ormatter # NOQA
from .ninjs_formatter import NINJSFormatter, NINJS2Formatter # NOQA
from .newsml_1_2_formatter import NewsML12Formatter # NOQA
from .newsml_g2_formatter import NewsMLG2Formatter # NOQA
from .email_formatter import EmailFormatter # NOQA
from .ninjs_newsroom_formatter import NewsroomNinjsFormatter #... | er # NOQA
from .imatrics import IMatricsFormatter # NOQA
|
cfriedt/gnuradio | grc/core/Block.py | Python | gpl-3.0 | 30,996 | 0.001226 | """
Copyright 2008-2015 Free Software Foundation, Inc.
This file is part of GNU Radio
GNU Radio Companion is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any l... | key = sink.ge | t_key()
# Test against repeated keys
if key in self.get_sink_keys():
raise Exception('Key "{0}" already exists in sinks'.format(key))
# Store the port
self.get_sinks().append(sink)
self.back_ofthe_bus(self.get_sinks())
self.current_bus_stru... |
opendatateam/udata | udata/sitemap.py | Python | agpl-3.0 | 977 | 0 | from functools import wraps
from flask import current_app, request
from flask_sitemap import Sitemap, sitemap_page_needed
from udata.app import cache
sitemap = Sitemap()
CACHE_KEY = 'sitemap-page-{0}'
@sitemap_page_needed.connect
def create_page(app, page, urlset):
key = CACHE_KEY.format(page)
cache.set(k... | key = CACHE_KE | Y.format(page)
return cache.get(key) or fn(*args, **kwargs)
return loader
def set_scheme(fn):
@wraps(fn)
def set_scheme_on_call(*args, **kwargs):
scheme = 'https' if request.is_secure else 'http'
current_app.config['SITEMAP_URL_SCHEME'] = scheme
return fn(*args, **kwargs)
... |
mwcraig/conda-build | conda_build/metadata.py | Python | bsd-3-clause | 20,286 | 0.004091 | from __future__ import absolute_import, division, print_function
import os
import re
import sys
from os.path import isdir, isfile, join
from conda.compat import iteritems, PY3, text_type
from conda.utils import memoized, md5_file
import conda.config as cc
from conda.resolve import MatchSpec
from conda.cli.common impo... | startswith('linux-'),
linux32 = bool(plat == 'linux-32'),
linux64 = bool(plat == 'linux-64'),
arm = plat.startswith('linux-arm'),
osx = plat.startswith('osx-'),
unix = plat.startswith(('linux-', 'osx-')),
win = plat.startswith('win-'),
win32 = bool(plat == 'win-32... | py2k = bool(20 <= py < 30),
py26 = bool(py == 26),
py27 = bool(py == 27),
py33 = bool(py == 33),
py34 = bool(py == 34),
py35 = bool(py == 35),
np = np,
os = os,
environ = os.environ,
)
for machine in cc.non_x86_linux_machines:
d[machine] = ... |
allevin/PyGithub | scripts/add_attribute.py | Python | lgpl-3.0 | 6,009 | 0.00649 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
############################ Copyrights and license ############################
# #
# Copyright 2013 Vincent Jacques <[email protected]> #
# Copyright 2014 Thialfihar <t... | the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied w... | #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# ... |
arendst/Sonoff-Tasmota | pio/http-uploader.py | Python | gpl-3.0 | 412 | 0.004854 | Import("env")
import os
# pio < 4.0.0
# from base64 import b64decode
# env.Replace(UPLOADER="pio\espupload.py")
# env.Replace(U | PLOADERFLAGS="")
# env.Replace(UPLOADCMD="$UPLOADER -u " + b64decode(ARGUMENTS.get("UPLOAD_PORT")) + " -f $SOURCES")
# pio >= 4.0.0
env.Replace(UPLOADER=os.path.join("pio", "espupload.py"))
env.Replace(UPLOADERFLAGS="")
env.Replace(UPLOADCMD="$UPLOADER -u $UPLOAD_PORT -f $S | OURCES")
|
owaiskhan/Retransmission-Combining | gnuradio-examples/python/network/vector_source.py | Python | gpl-3.0 | 2,271 | 0.004844 | #!/usr/bin/env python
#
# Copyright 2006,2010 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your opt... | at it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see | the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
from gnuradio import gr
from gnuradio.eng_option import eng_option
from optparse import OptionParser
class vector_source(gr.top_block):
def __init__(self, host, port, pkt_size, eof):
... |
ashwinreddy/rlg | rlg/tasks/snake.py | Python | mit | 106 | 0.009434 | fr | om task import Task
class SnakeTask(Task):
def __init__(s | elf):
Task.__init__(self, 'snake')
|
liyueshining/moon | mocorderconverter/MocOrder.py | Python | mit | 4,028 | 0.000993 | from xml.dom.minidom import parseString
from xml.dom import minidom
from MocNode import MocNode
import os
import sys
radioTypes = ['GSM', 'UMTS', 'TD', 'AG', 'MCE']
def getMocOrder(path):
files = os.listdir(path)
for afile in files:
if afile.lower().endswith("-mocinfo-sdrm.xml"):
mocinfoX... | f dealWithMocs(self):
for mocNode in self.mocNodes:
name = self.mocNodes[mocNode].name
refmocs = self.mocNodes[mocNode].refmoc
if len(refmocs) | == 0:
continue
for refmoc in refmocs:
if refmoc not in self.mocs:
continue
if self.mocs.index(refmoc) < self.mocs.index(name):
continue
if self.mocNodes[refmoc].parent == name:
continu... |
foobarbazblarg/stayclean | stayclean-2019-october/update-google-chart.py | Python | mit | 8,223 | 0.002311 | #!/usr/bin/python
# TODO: issues with new oauth2 stuff. Keep using older version of Python for now.
# #!/usr/bin/env python
import json
import gspread
from oauth2client.client import SignedJwtAssertionCredentials
import datetime
from participantCollection import ParticipantCollection
# Edit Me!
participantFileNames =... | '../stayclean-2016-july/participants.txt',
'../stayclean-2016-august/participants.txt',
'../stayclean-2016-september/particip | ants.txt',
'../stayclean-2016-october/participants.txt',
'../stayclean-2016-november/participants.txt',
'../stayclean-2016-december/participants.txt',
'../stayclean-2017-january/participants.txt',
'..... |
xieyaxiongfly/Atheros_CSI_tool_OpenWRT_src | scripts/dl_github_archive.py | Python | gpl-2.0 | 14,504 | 0.001241 | #!/usr/bin/env python
#
# Copyright (c) 2018 Yousong Zhou <[email protected]>
#
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.
import argparse
import calendar
import datetime
import errno
import fcntl
import hashlib
import json
import os
import os.pa... | args = ('tar', '-C' | , into, '-xzf', path, '--no-same-permissions')
subprocess.check_call(args, preexec_fn=lambda: os.umask(0o22))
dirs = os.listdir(into)
if len(dirs) == 1:
return dirs[0]
else:
raise PathException('untar %s: expecting a single subdir, got %s' % (path, dirs))
@st... |
mindbody/API-Examples | SDKs/Python/test/test_add_client_request.py | Python | bsd-2-clause | 956 | 0 | # coding: utf-8
" | ""
MINDBODY Public API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: v6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
impor... | _client_request import AddClientRequest # noqa: E501
from swagger_client.rest import ApiException
class TestAddClientRequest(unittest.TestCase):
"""AddClientRequest unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testAddClientRequest(self):
"""Test Add... |
P4ELTE/t4p4s | src/compiler.py | Python | apache-2.0 | 22,115 | 0.004251 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
# Copyright 2016-2020 Eotvos Lorand University, Budapest, Hungary
import argparse
from hlir16.hlir import *
from compiler_log_warnings_errors import *
import compiler_log_warnings_errors
from compiler_load_p4 import load_from_p4
fr... | am}) "'
return (fmt, expr)
def replace_insert(insert):
simple = re.split(r'^\$([a-zA-Z_][a-zA-Z_0-9]*)$', insert)
if len(simple) == 3:
yield (simple[1],)
return
# replace $$[light][text1]{expr}{text2} inserts, where all parts except {expr} are optional
m = re.match(r'(?P<type>\$\... | \[(?P<light>[^\]]+)\])?(\[(?P<text1>[^\]]+)\])?{\s*(?P<expr>[^}]*)\s*}({(?P<text2>[^}]+)})?', insert)
if not m:
yield insert
return
light = m.group("light")
txt1 = m.group('text1') or ''
expr = m.group('expr')
txt2 = m.group('text2') or ''
# no highlighting
if m.group("t... |
jesusbriales/rgbd_benchmark_tools | src/rgbd_benchmark_tools/plot_graph.py | Python | bsd-2-clause | 2,247 | 0.010681 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 17 09:02:31 2015
@author: jesus
"""
import argparse
import numpy as np
import h5py
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='''
Plot mean precision (averaged from samples) for different cases wrt sampling ratio.... | :
# lines[case] = np.em | pty(numOfRatios)
# Store values in the lines dictionary
for case in cases:
caseGroup = ratioGroup[case]
dset = caseGroup['eval/'+unit+'/'+metric]
lines[case][x] = np.mean( dset[:] )
# Plot the graph
import matplotlib
matplotli... |
patrys/opbeat_python | tests/instrumentation/django_tests/template_tests.py | Python | bsd-3-clause | 5,153 | 0.002911 | import pytest # isort:skip
pytest.importorskip("django") # isort:skip
from os.path import join
import django
from django.test import TestCase
import mock
import pytest
from conftest import BASE_TEMPLATE_DIR
from opbeat.contrib.django.models import get_client, opbeat
try:
# Django 1.10+
from django.urls i... | ] for t in traces]),
set(kinds))
# Reorder acc | ording to the kinds list so we can just test them
kinds_dict = dict([(t['kind'], t) for t in traces])
traces = [kinds_dict[k] for k in kinds]
self.assertEqual(traces[0]['kind'], 'transaction')
self.assertEqual(traces[0]['signature'], 'transaction')
self.assertEqual(traces[0]['tr... |
ericmjl/bokeh | tests/unit/bokeh/core/property/test_instance.py | Python | bsd-3-clause | 3,539 | 0.006499 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... | bcpi.Instance(_TestModel)
assert prop.readonly == False
def test_valid(self) -> None:
prop = bcpi.Instance(_TestModel)
assert prop.is_valid(None)
assert prop.is_valid(_TestModel())
def test_invalid(self) -> None:
prop = bcpi.Instance(_TestModel)
assert not pro... | id(True)
assert not prop.is_valid(0)
assert not prop.is_valid(1)
assert not prop.is_valid(0.0)
assert not prop.is_valid(1.0)
assert not prop.is_valid(1.0+1.0j)
assert not prop.is_valid("")
assert not prop.is_valid(())
assert not prop.is_valid([])
a... |
StefanKjartansson/Cloudstack-Python-Client | cloudstack/baseclient.py | Python | apache-2.0 | 6,613 | 0.00378 | import urllib2
import urllib
import hashlib
import json
import time
import socket
import os
import logging
import hmac
import base64
from cloud_exceptions import CloudException
from dataobject import *
__all__ = ['BaseClient', 'DataObject', 'CloudException']
logger = logging.getLogger('cloud_com.baseclient')
cla... | self.url + '?' + urllib.urlencode(params)).read())
except urllib2.HTTPError as (errno):
raise CloudException(errno.code)
def process_async(self, comma | nd, kwargs, _class=DataObject):
logger.debug(
'Processing asynchronous command %s with arguments: %s' % (
command, str(kwargs)))
data = self.__execute__(command, kwargs, True)
if data['queryasyncjobresultresponse']['jobresulttype'] == u'object':
obj = [v[0] fo... |
xtream1101/web-scraper | main.py | Python | mit | 1,737 | 0.001727 | import os
import sys
import argparse
import configparser
from utils.process import Process
# They are imported as all lowercase
# so it is case insensitive in the config file
from modules.tuebl import Tuebl as tuebl
from modules.itebooks import ItEbooks as itebooks
from modules.wallhaven import Wallhaven as wallhaven... | iting
"""
for site in scrape:
print(scrape[site].log("Exiting..."))
scrape[site].stop()
sys.exit(0)
if __name__ == "__main__":
# Read co | nfig file
if not os.path.isfile(args.config):
print("Invalid config file")
sys.exit(0)
config.read(args.config)
# Parse config file
scrape = {}
for site in config.sections():
if config[site]['enabled'].lower() == 'true':
try: # If it not a class skip it
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.