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 |
|---|---|---|---|---|---|---|---|---|
bgrace/wagtail-commons | wagtail_commons/core/__init__.py | Python | bsd-3-clause | 73 | 0.013699 | default_app_config = 'wagtail_commons.core.apps.WagtailCommonsCore | Con | fig' |
PaulWay/insights-core | insights/parsers/uname.py | Python | apache-2.0 | 19,809 | 0.000757 | """
Uname - ``uname -a`` command output
===================================
The ``Uname`` class reads the output of the ``uname -a`` command and
interprets it. It also does a number of handy extra things, like deriving
the RHEL release from the kernel version.
Uname objects can also be compared by their kernel versi... | in the format
``version-release``.
- `rhel_release`: A list of two elements, the major and minor RHEL product
release numbers.
"""
keys = [
'os',
'hw_platform',
'processor',
'machine',
'kernel_date',
'kernel_type',
'kernel',
'name'... | ,
'ver_rel',
'rhel_release',
'_lv_release',
'_rel_maj',
'_sv_version',
'_lv_version'
]
defaults = {k: None for k in keys}
def __init__(self, context):
super(Uname, self).__init__(context)
data = dict(self.defaults)
data.update(self.da... |
atupal/oj | topcoder/contests/tco_2015/round1a/a.py | Python | mit | 571 | 0.015762 | # -*- coding: utf-8 -*-
class Similars(object):
def maxsim(self, L, R):
s = []
for | i in xrange(L, R+1):
s.append( sorted( list(set([_ for _ in str(i)]) ) ) )
s.sort()
ans = 0
for i in xrange(len(s)-1):
t = len( set(s[i]) & set(s[i+1]))
if t > an | s:
ans = t
return ans
if __name__ == '__main__':
s = Similars()
#print s.maxsim(1, 10)
#print s.maxsim(1, 99)
#print s.maxsim(444, 454)
print s.maxsim(1, 100000)
print s.maxsim(998, 1013)
|
fernandog/Medusa | medusa/ws/MedusaWebSocketHandler.py | Python | gpl-3.0 | 1,018 | 0 | # coding=utf-8
from __future__ import print_function
from __future__ import unicode_literals
from tornado.websocket import WebSocketHandler
clients = []
backlogged_msgs = []
def push_to_web_socket(msg):
if len(clients):
for client in clients:
client.write_message(msg)
else:
# No... | ogged_msgs.append(msg)
class WebSocketUIHandler(WebSocketHandler):
def check_origin(self, origin):
return True
def open(self, *args, **kwargs):
clients.append(self)
WebSocketHandler.open(self, *args, **kwargs)
if len(clients) == 0 and len(backlogged_msgs):
# We hav... | ages and a new client
for msg in backlogged_msgs:
push_to_web_socket(msg)
def on_message(self, message):
print(u"Received: " + message)
def data_received(self, chunk):
WebSocketHandler.data_received(self, chunk)
def on_close(self):
clients.remove(self)
|
dklyle/trove-dashboard | trove_dashboard/enabled/_1710_database_panel_group.py | Python | apache-2.0 | 913 | 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... | ributed 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.
from django.utils.translation import ugettext_lazy as _
# The slug of the panel group to be added to H... | th. Required.
PANEL_GROUP_DASHBOARD = 'project'
|
denniszollo/piksi_tools | piksi_tools/fileio.py | Python | lgpl-3.0 | 6,491 | 0.013095 | #!/usr/bin/env python
# Copyright (C) 2014 Swift Navigation Inc.
# Contact: Gareth McMullin <gareth@swift-nav.com>
#
# This source is subject to the license found in the file 'LICENSE' which must
# be be distributed together with this source. All other rights reserved.
#
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" ... | = data[:chunksize]
data = data[chunksize:]
header = struct.pack("<I", offset) + filename + '\0'
self.link.send(SBP_MSG_FILEIO_WRITE, header + chunk)
reply = self.link.wait(SBP | _MSG_FILEIO_WRITE, timeout=1.0)
if not reply:
raise Exception("Timeout waiting for FILEIO_WRITE reply")
if reply != header:
raise Exception("Reply FILEIO_WRITE doesn't match request")
offset += len(chunk)
def hexdump(data):
"""
Print a hex dump.
Parameters
----------
data :... |
robin1885/algorithms-exercises-using-python | source-code-from-author-book/Listings-for-Second-Edition/listing_2_2.py | Python | mit | 123 | 0.056911 | def foo(tom):
fred = 0
| for bill in | range(1,tom+1):
barney = bill
fred = fred + barney
return fred
|
ajotwani/alfred-show-me-the-klout | development/get_twitter_details.py | Python | mit | 452 | 0.039823 | from __future__ import division
import twitter_auth #calling the Twitter auth module
def get_details(twitter_handle):
# Get the User object for twitter...
user = twitter_auth.api.get_user(twitter_handle)
#Calculating the followers vs following ratio
ff_ratio = round(int | (user.followers_count) / int(user.friends_count),2)
#Returning Twitter details as a Tuple
return (user.name,user.friends_c | ount,user.followers_count,ff_ratio,user.created_at) |
hotpxl/mxnet | example/image-classification/test_score.py | Python | apache-2.0 | 1,493 | 0.005358 | """
test pretrained models
"""
from __future__ import print_function
import mxnet as mx
from common import find_mxnet, modelzoo
from score import score
VAL_DATA='data/val-5k-256.rec'
def download_data():
return mx.test_utils.download(
'http://data.mxnet.io/data/val-5k-256.rec', VAL_DATA)
def test_imagenet... | eed = %f img/sec' % (m, r, speed))
assert r > g and r < g + .1
def test_imagenet1k_inception_bn(**kwargs):
acc = mx.m | etric.create('acc')
m = 'imagenet1k-inception-bn'
g = 0.75
(speed,) = score(model=m,
data_val=VAL_DATA,
rgb_mean='123.68,116.779,103.939', metrics=acc, **kwargs)
r = acc.get()[1]
print('Tested %s acc = %f, speed = %f img/sec' % (m, r, speed))
assert r > ... |
AsgerPetersen/QGIS | python/plugins/processing/algs/grass7/ext/r_blend_combine.py | Python | gpl-2.0 | 2,883 | 0.00139 | # -*- coding: utf-8 -*-
"""
***************************************************************************
r_blend.py
----------
Date : February 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
**************************************... | unicode(cellsize)
else:
command += ' res=' + unicode(alg.getDefaultCellsize())
alignToResolution = alg.getParameterValue(alg.GRASS_REGION_ALIGN_TO_RESOLUTION)
if alignToResolution:
command += ' -a'
alg.commands.append(c | ommand)
def processOutputs(alg):
# Keep color table
output = alg.getOutputValue(u'output')
command = u"r.out.gdal -t createopt=\"TFW=YES,COMPRESS=LZW\" input={} output=\"{}\" --overwrite".format(
alg.exportedLayers[output],
output
)
alg.commands.append(command)
alg.outputComman... |
pyannote/pyannote-generators | pyannote/generators/__init__.py | Python | mit | 1,291 | 0 | #!/usr/bin/env python
# encoding: utf-8
# The MIT License (MIT)
# Copyright (c) 2016 CNRS
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation ... | OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# AUTHORS
# Hervé BREDIN - http://herve.niderb.fr
from ._ve | rsion import get_versions
__version__ = get_versions()['version']
del get_versions
|
probml/pyprobml | scripts/transposed_conv_torch.py | Python | mit | 1,546 | 0.005175 |
# Based on http://d2l.ai/chapter_computer-vision/transposed-conv.html
import superimport
import torch
from torch import nn
import numpy as np
def trans_conv(X, K):
h, w = K.shape
Y = torch.zeros((X.shape[0] + h - 1, X.shape[1] + w - 1))
for i in range(X.shape[0]):
for j in range(X.shape[1]):
... | rans_conv(X, K)
print(Y)
X, K = X.reshape(1, 1, 2, 2), K.reshape(1, | 1, 2, 2)
tconv = nn.ConvTranspose2d(1, 1, kernel_size=2, bias=False)
tconv.weight.data = K
Y2 = tconv(X)
#print(Y2)
assert torch.allclose(Y, Y2)
'''
X, K = X.reshape(1, 1, 2, 2), K.reshape(1, 1, 2, 2)
tconv = nn.ConvTranspose2d(1, 1, kernel_size=2, padding = 1, bias=False)
tconv.weight.data = K
Y2 = tconv(X)
print('Y... |
elangaar/django-weather-forecast | weather_forecast/wsgi.py | Python | mit | 409 | 0 | """
WSGI config for weather_forecast project.
It exposes the WSGI cal | lable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "weather_forecast.settings")
application = get_... | application()
|
indico/indico | indico/core/oauth/__init__.py | Python | mit | 1,252 | 0.000799 | # This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
import os
from indico.core import signals
from indico.core.db import d | b
from .logger import logger
from .oauth2 import require_oauth
__all__ = ['require_oauth']
@signals.core.app_created.connect
def _no_ssl_required_on_debug(app, **kwargs):
if app.debug or app.testing:
os.environ['AUTHLIB_INSECURE_TRANSPORT'] = '1'
@signals.users.merged.connect
def _delete_merged_user_... | target_link = target_app_links[source_link.application]
except KeyError:
logger.info('merge: reassigning %r to %r', source_link, target)
source_link.user = target
else:
logger.info('merge: merging %r into %r', source_link, target_link)
target_link... |
viewplatgh/energybean | widgets/widgets/views.py | Python | unlicense | 98 | 0 | from django.shortcuts im | port redirect
def index(request):
return redirect('/feedback2 | 013/')
|
weblyzard/ewrt | src/eWRT/ws/wikidata/definitions/property_definitions.py | Python | gpl-3.0 | 13,203 | 0.000379 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# provides mappings property key-> English label
# for properties typically associated with
# a variety of entity types
import copy
from collections import OrderedDict, namedtuple
local_attributes = OrderedDict([ |
("P17", u"country"),
("P131", u"located in the administrative territorial entity"),
("P19", u"place of birth"),
("P27", u"country of citizenship"),
("P551", u"residence"),
("P159", u"headquarters location"),
("P740", u"location of formation"),
])
image_attributes = {
"P18": u"image",
... | mage",
"P242": u"locator map image",
"P1442": u"image of grave",
"P154": u"logo image", }
location_properties = {
"P18": u"image",
"P31": u"instance of",
"P41": u"flag image",
"P47": u"shares border with",
"P17": u"country",
"P94": u"coat of arms image",
"P131": u"located in the... |
spranesh/Redhawk | redhawk/utils/util.py | Python | bsd-2-clause | 5,087 | 0.014743 | #!/usr/bin/env python
from __future__ import absolute_import
from __future__ import print_function
import redhawk
import hashlib
import operator
import os
import sys
import traceback
from functools import reduce
def AssertWithError(condition, error):
""" If condition is false, exit with error."""
if callable(cond... | dition):
return CallIfPossible(iftrue)
else:
return CallIfPossible(iffalse)
def IndexInto(li, indices):
""" Index into a list (or list of lists) using the indices given. If the
indices a | re out of bounds, or are too many in number, return None, instead
of throwing an error. 0 is a special case."""
for i in indices:
if type(li) != list and i == 0:
return li
if type(li) != list or i >= len(li):
return None
li = li[i]
return li
def LogWarning(s, stream=sys.stderr):
""" Lo... |
gramps-project/gramps | gramps/plugins/view/geofamily.py | Python | gpl-2.0 | 22,744 | 0.000352 | # -*- python -*-
# -*- coding: utf-8 -*-
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2011-2016 Serge Noiraud
#
# 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 ver... | bel" translatable="yes">Print...</attribute>
</item>
</section>
''',
'''
<section id="AddEditBook">
<item>
<attribute name="action">win.AddBook</attribute>
<attribute name="label" translatable="yes">_Add Bookmark</attribute>
</item>
<item>
<a... | n>
''' % _('Organize Bookmarks'), # Following are the Toolbar items
'''
<placeholder id='CommonNavigation'>
<child groups='RO'>
<object class="GtkToolButton">
<property name="icon-name">go-previous</property>
<property name="action-name">win.Back</property>
<property name="too... |
spthm/glio | snapshot.py | Python | mit | 18,934 | 0.000739 | from copy import copy
import numpy as np
from .fortranio import FortranFile
from .snapview import SnapshotView
class SnapshotIOException(Exception):
"""Base class for exceptions in the the snapshot module."""
def __init__(self, message):
super(SnapshotIOException, self).__init__(message)
class Snaps... | e snapshot header from the current file."""
with FortranFile(self.fname, 'rb') as ffile:
self._load(ffile)
def to_array(self):
"""Return a structured array representing the header d | ata."""
dtype = [(k, dt, size) for k, (dt, size) in self._schema.items()]
values = tuple(getattr(self, name) for name in self.fields)
return np.array(values, dtype=dtype)
def save(self, fname=None):
"""
Write the snapshot header to the current file, overwriting the file.
... |
erikdejonge/python_for_kids | chapter07/spaceship_building.py | Python | gpl-2.0 | 227 | 0.017621 | def spaceship_building(cans):
total_cans = 0
for week in | range(1,53):
total_cans = total_cans + cans
print('Week %s = %s cans' % (week, total_cans))
spa | ceship_building(2)
spaceship_building(13) |
odejesush/tensorflow | tensorflow/python/debug/wrappers/local_cli_wrapper_test.py | Python | apache-2.0 | 13,116 | 0.002516 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | on.__init__.
"""
local_cli_wrapper.LocalCLIDebugWrapperSession.__init__(
self, sess, dump_root=dump_root, log_usage=False)
self._command_args_sequence = command_args_sequence
self._response_pointer = 0
# Observer variables.
self.observers = {
"debug_dum | ps": [],
"tf_errors": [],
"run_start_cli_run_numbers": [],
"run_end_cli_run_numbers": [],
}
def _prep_cli_for_run_start(self):
pass
def _prep_cli_for_run_end(self, debug_dump, tf_error, passed_filter):
self.observers["debug_dumps"].append(debug_dump)
self.observers["tf_erro... |
CGATOxford/CGATPipelines | CGATPipelines/pipeline_docs/pipeline_proj007/trackers/macs_replicated_unique_interval_chromatin_profile.py | Python | mit | 345 | 0 |
from CGATReport.Tracker import *
# | #########################################################################
##########################################################################
##########################################################################
class h3k4me3ProfileTracker(TrackerImage | s):
"""Chromatin profile per gene """
|
wagnerand/olympia | src/olympia/legacy_discovery/tests/test_views.py | Python | bsd-3-clause | 7,499 | 0 | from django.utils.encoding import smart_text
import mock
import six
from pyquery import PyQuery as pq
from olympia import amo
from olympia.amo.tests import (
TestCase, addon_factory, collection_factory, user_factory)
from olympia.amo.urlresolvers import reverse
from olympia.legacy_discovery import views
from oly... | t response.status_code == 200
class Test | Urls(TestCase):
def test_redirect_to_mozilla_new_page(self):
response = self.client.get('/en-US/firefox/discovery/', follow=False)
self.assertRedirects(
response,
'https://www.mozilla.org/firefox/new/',
status_code=301, fetch_redirect_response=False)
class TestP... |
gregcaporaso/q2cli | q2cli/handlers.py | Python | bsd-3-clause | 22,305 | 0 | # ----------------------------------------------------------------------------
# Copyright (c) 2016-2017, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | ction as its value."""
def __init__(self):
super().__init__('output_dir')
def get_click_options(self):
import click
import q2cli
yield q2cli.Option(
['--' + self.cli_name],
type=click.Path(exists=False, dir_oka | y=True, file_okay=False,
writable=True),
help='Output unspecified results to a directory')
def get_value(self, arguments, fallback=None):
import os
import os.path
import click
try:
path = self._locate_value(arguments, fallback=fal... |
vinodpanicker/scancode-toolkit | src/extractcode/libarchive2.py | Python | apache-2.0 | 28,804 | 0.000937 | #
# Copyright (c) 2015 nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/scancode-toolkit/
# The ScanCode software is licensed under the Apache License version 2.0.
# Data generated with ScanCode require an acknowledgment.
# ScanCode is a trademark of nexB Inc.
#
# You may not use... | n, print_function
from functools import partial
import locale
import logging
import os
import ctypes
from ctypes import c_char_p, c_wchar_p
from ctypes import c_int, c_longlong
from ctypes import c_size_t, c_ssize_t
f | rom ctypes import c_void_p
from ctypes import POINTER
from ctypes import create_string_buffer
from commoncode import command
from commoncode import paths
from commoncode import system
from commoncode import fileutils
import extractcode
from extractcode import ExtractError
from extractcode import ExtractErrorPasswordP... |
sittingbull/artefact.connectors | artefact/utils/tests/test_consume_parser.py | Python | apache-2.0 | 3,880 | 0.006959 | import unittest
import mock
from artefact.utils.consume_parser import ConsumeParser, UnconsumedDataException, ConsumeParseException, ConsumeTimeoutException
class MultiRuleTestParser(ConsumeParser):
rules = [
(r'^(?P<left>[^,]+),', False),
(r'^(?P<right>[^,]+)', False)
]
class RepeatingRule... | 'ineId=i-ba35153a;dIp=0xeff7196a7a827d99f7f6a031a24467b3;site=0x95' + \
'a8419ac1bcdf938408cdce1c7008bd;adThdIdCode=idfa;dealId=0;bsc=${CL' + \
'ICK_URL:URLENCODE};geoId=15000;inventory | Id=6684940;deviceId=44479' + \
';redir=https://ad.doubleclick.net/ddm/jump/N5079.1172840ADTHEOREN' + \
'TINC/B10153716.136107246;ord=8742a983-6d6b-11e6-9a08-123d16988b1f' + \
'?"> <IMG SRC="?" BORDER=0 WIDTH=320 HEIGHT=480 ALT="Advertisement' + \
'"></A> </NOSCRIPT><scrip... |
wzguo/youker-assistant | backends/youker-assistant-daemon/src/beautify/common.py | Python | gpl-3.0 | 6,224 | 0.001607 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2007-2011 Tualatrix Chou <tualatrix@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, ... | ched_schema_tree = {}
cached_override = {}
@classmethod
def load_override(cls):
log.de | bug("\tLoading override")
for override in glob.glob('/usr/share/glib-2.0/schemas/*.gschema.override'):
try:
cs = RawConfigSetting(override)
for section in cs.sections():
cls.cached_override[section] = {}
for option in cs.options... |
softak/webfaction_demo | utils/widgets.py | Python | bsd-3-clause | 869 | 0.001151 | from django.forms import CheckboxSelectMultiple, ClearableFileInput
class BootstrapCheckboxSelectMultiple(CheckboxSelectMultiple):
def render(self, name, value, attrs=None, choices=()):
output = super(BootstrapCheckboxSelectMultiple, self).render(
name, value, attrs, choices)
| # we don't need ul-li structure
output = output.replace('<li>', '').replace('</li>', '')\
.replace('<ul>', '').replace('</ul>', '')
# we need class="checkbox" for labels
output = output.replace('<label', '<label class="checkbox"')
return output
class Bootstra... | " class="checkbox">%(clear)s %(clear_checkbox_label)s</label>'
|
ovresko/erpnext | erpnext/education/doctype/student_group/test_student_group.py | Python | gpl-3.0 | 1,188 | 0.025253 | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies and Contributors
# See license.txt
from __future__ import unicode_literal | s
import frappe
import unittest
import erpnext.education
def get_random_group():
doc = frappe.get_doc({
"doctype": "Student Group",
"student_group_name": "_Test Student Group-" + frappe.generate_hash(le | ngth=5),
"group_based_on": "Activity"
}).insert()
student_list = frappe.get_all('Student', limit=5)
doc.extend("students", [{"student":d.name, "active": 1} for d in student_list])
doc.save()
return doc
class TestStudentGroup(unittest.TestCase):
def test_student_roll_no(self):
doc = get_random_group()
se... |
mgk/thingpin | src/thingpin/pin.py | Python | mit | 3,219 | 0 | import time
from threading import Thread
import RPi
from RPi import GPIO
from collections import Iterable
import itertools
HIGH = GPIO.HIGH
LOW = GPIO.LOW
def set_pin_mode(mode):
"""
Set pin numbering mode for all pins.
Args:
mode (str): mode to set, must be 'BOARD' or 'BCM'
"""
GPIO.set... | GPIO.input(self.pin)
now = time.time()
dt = now - self.debounce_time
if new_reading != self.last_reading:
self.debounce_time = now
if dt >= self.debounce_dela | y and new_reading != self.reading:
self.observer.update_pin(self.pin, new_reading)
self.reading = new_reading
self.last_reading = new_reading
time.sleep(sleep)
|
abztrakt/labtracker | Machine/hooks.py | Python | apache-2.0 | 2,801 | 0.006426 | import django.forms
from django.template import RequestContext
from django.template.loader import render_to_string
from IssueTracker.utils import issueHook
import models, forms
@issueHook("create")
def issueCreate(request):
"""
Given r | equest, render what extra stuff is needed for Machines
"""
args = { 'statusForm' : forms.itemStatusForm(), }
return render_to_string('issueCreate.html', args,
context_instance=RequestContext(request))
@issueHook("createSubmit")
def issueCreateSave(request, item=None, group=None):
"""
Ho... | if item == None and group == None:
return True
data = request.POST.copy()
# update the statuses for the issue
# instance passed is an issue, so we need to get the Machine out of it
form = forms.itemStatusForm(data)
if form.is_valid():
return form.save(machine=item, group=group)
... |
jlijian3/warp17 | ut/lib/warp17_ut.py | Python | bsd-3-clause | 19,475 | 0.003646 | #
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
#
# Copyright (c) 2016, Juniper Networks, Inc. All rights reserved.
#
#
# The contents of this file are subject to the terms of the BSD 3 clause
# License (the "License"). You may not use this file except in compliance
# with the License.
#
# You can obta... | ed."""
return Rate()
def get_port_cfg(self, eth_po | rt):
# No def gw
no_def_gw = Ip(ip_version=IPV4, ip_v4=0)
# Setup interfaces on port 0
pcfg = b2b_port_add(eth_port=eth_port, def_gw = no_def_gw)
for i in range(0, self.L3_INTF_COUNT):
pcfg.pc_l3_intfs.add(l3i_ip=Ip(ip_version=IPV4, ip_v4=b2b_ipv4(eth_port, i)),
... |
napalm-automation/napalm-yang | napalm_yang/models/openconfig/network_instances/network_instance/protocols/protocol/isis/levels/level/link_state_database/lsp/tlvs/tlv/extended_is_reachability/neighbors/neighbors_/subTLVs/subTLVs_/ipv6_neighbor_address/__init__.py | Python | apache-2.0 | 12,492 | 0.001201 | # -*- coding: utf-8 -*-
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListTy... | s. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: This container defines sub-TLV 13.
"""
__slots__ = ("_path_helper", "_extmethods", "__state")
_yang_name = "ipv6-neighbor-address"
_pybind_generated_by = "container"
def ... | self.__state = YANGDynClass(
base=state.state,
is_container="container",
yang_name="state",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
extensions=None,
n... |
yrunts/python-for-qa | 2-python-basics-2/examples/loop.py | Python | cc0-1.0 | 298 | 0 |
f | rom __future__ import print_function
print('starting while loop')
# loop using while
i = 0
while i < 100:
print('.', end='')
i += 1
# print for newline
print()
print('starting for in loop')
# loop using for in with range function
for i in range(0, 100):
print('.', end='')
print()
| |
w4n9H/PythonSkillTree | Storage/BigData/Zookeeper/ZKClient.py | Python | apache-2.0 | 2,203 | 0.000454 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: mango
@contact: w4n9@sina.com
@create: 16/7/4
hail hydra!
"""
__author__ = "mango"
__version__ = "0.1"
from kazoo.client import KazooClient
import logging
logging.basicConfig()
class ZookeeperClient(object):
def __init__(self, zk_host):
self.... | n 1
def create_node_file(self, nodename, configfile_path):
tr | y:
with open(configfile_path, 'r') as fp:
config = fp.read()
self.zk.create(nodename, config)
return 0
except Exception, e:
print e
return 1
def get_data(self, nodename):
data, stat = self.zk.get(nodename)
return da... |
Hodorable/0602 | openstack_dashboard/dashboards/project/images/images/tests.py | Python | apache-2.0 | 16,101 | 0 | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the... | {
'name': u'Ubuntu 11.10',
'source_type': u'file',
'description': u'Login with admin/admin',
'disk_format': u'qcow2',
'architecture': u'x86-64',
'minimum_disk': 15,
'minimum_ram': 512,
'is_public': 1}
files = {}
... | form.is_valid(), False)
@override_settings(HORIZON_IMAGES_ALLOW_UPLOAD=False)
@test.create_stubs({api.glance: ('image_list_detailed',)})
def test_image_upload_disabled(self):
filters = {'disk_format': 'aki'}
api.glance.image_list_detailed(
IsA({}), filters=filters).AndReturn(
... |
tellproject/helper_scripts | aim_server.py | Python | apache-2.0 | 1,508 | 0.011273 | #!/usr/bin/env python
from threaded_ssh import ThreadedClients
from ServerConfig import Aim
from ServerConfig import TellStore
from ServerConfig import General
from ServerConfig import Storage
from ServerConfig import Kudu
def hostToIp(host):
return General.infinibandIp[host]
def semicolonReduce(x, y):
return... | (len(Storage.servers) + len(Storage.servers1)) * Aim.numRTAClients * 16
chunkSize = ((TellStore.scanMemory // numChunks) // 8) * 8
serverExec = ""
if Storage.storage == Kudu:
serverExec = "aim_kudu -P {0} -s {1}".format((len(Storage.servers) + len(Storage.servers1)) * 2, Storage.master)
| elif Storage.storage == TellStore:
serverExec = 'aim_server -M {0} -m {1} -c "{2}" -s "{3}" --processing-threads {4}'.format(numChunks, chunkSize, TellStore.getCommitManagerAddress(), TellStore.getServerList(), Aim.serverthreads)
cmd = '{0}/watch/aim-benchmark/{3} -f {1} -b {2}'.format(Aim.builddir... |
inveniosoftware/flask-security-fork | flask_security/decorators.py | Python | mit | 4,832 | 0 | # -*- coding: utf-8 -*-
"""
flask_security.decorators
~~~~~~~~~~~~~~~~~~~~~~~~~
Flask-Security decorators module
:copyright: (c) 2012 by Matt Wright.
:license: MIT, see LICENSE for more details.
"""
from collections import namedtuple
from functools import wraps
from flask import Response, _reque... | sk_login import current_user, login_required # pragma: no flakes
from flask_principal import Identity, Permission, RoleNeed, identity_changed
from werkzeug.local import LocalProxy
from werkzeug.routing import BuildError
from . import utils
# Convenient references
_security = LocalProxy(lambda: current_app.extensions... | urity'])
_default_unauthorized_html = """
<h1>Unauthorized</h1>
<p>The server could not verify that you are authorized to access the URL
requested. You either supplied the wrong credentials (e.g. a bad password),
or your browser doesn't understand how to supply the credentials required.
</p>
"... |
googlecolab/colabtools | google/colab/_serverextension/_resource_monitor.py | Python | apache-2.0 | 3,409 | 0.01232 | """Methods for tracking resource consumption of Colab kernels.
Note that this file is run under both py2 and py3 in tests.
"""
import csv
import os
import subprocess
from google.colab import _serverextension
try:
# pylint: disable=g-import-not-at-top
import psutil
except ImportError:
psutil = None
# Track wh... | inue
kernels[pids_to_kernel_ids[proc[0]]] = int(proc[1]) * 1024
result['kernels'] = kernels
return result
def get_disk_usage(path=None):
"""Reports total disk usage.
Args:
path: path at which disk to be measured is mounted
Returns:
A dict of the form {
usage: int,
limit: in... | otal
return {'usage': usage, 'limit': limit}
|
mbohlool/client-python | kubernetes/client/models/v1beta1_external_documentation.py | Python | apache-2.0 | 3,788 | 0.001584 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.8.2
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
... | r
"""
return self._description
@description.setter
def description(self, description):
"""
Sets the description of this V1beta1ExternalDocumentation.
:param description: The description of this V1beta1ExternalDocumentation.
:type: str
"""
self._... | url(self):
"""
Gets the url of this V1beta1ExternalDocumentation.
:return: The url of this V1beta1ExternalDocumentation.
:rtype: str
"""
return self._url
@url.setter
def url(self, url):
"""
Sets the url of this V1beta1ExternalDocumentation.
... |
seung-lab/znn-release | python/cost_fn.py | Python | gpl-3.0 | 10,672 | 0.0119 | #!/usr/bin/env python
__doc__ = """
Jingpeng Wu <jingpeng.wu@gmail.com>, 2015
"""
import numpy as np
import emirt
import utils
def get_cls(props, lbls, mask=None):
"""
compute classification error.
Parameters
----------
props : dict of array, network propagation output volumes.
lbls : dict o... | count_nonzero( (prop>0.5) != (lbl>0.5) )
return c
#@jit(nopython=True)
def square_loss(props, lbls, mask=None):
"""
compute square loss
Parameters
----------
props: numpy array, forward pass output
lbls: numpy array, ground truth labeling
Return
------
err: cost energy
... | l(lbls, mask)
for name, prop in props.iteritems():
lbl = lbls[name]
grdt = prop - lbl
grdts[name] = grdt * 2
err += np.sum(np.square( grdt ))
return (props, err, grdts)
def square_square_loss(props, lbls, mask=None, margin=0.2):
"""
square-square loss (square loss wi... |
BrandonTheBuilder/thermawesome | util/plotting.py | Python | mit | 1,372 | 0.00656 | import Gnuplot
def plotData(title, xlabel, ylabel, args):
"""
args is a list of file names containing relevant data
""" |
g = Gnuplot.Gnuplot()
g.title(title)
g.xlabel(xlabel)
g.ylabel(ylabel)
g('set term png')
g('set out "plots/{}.png"'.format(title))
data = Gnuplot.Data(*args)
g.plot(data)
def plotComponent(name, data, int_p):
# Exergetic Efficiency
ef = [c.ef for c in data]
plotData('Exer... | 'Exergetic Efficiency', [int_p, ef])
work = [c.w for c in data]
yf_in = [c.yf_in for c in data]
yf_out = [c.yf_out for c in data]
ex_destroyed = [c.exergyDestroyed for c in data]
plot_work = Gnuplot.Data(int_p, work, title='Exergy lost to work', with_='lines')
plot_yf_in = Gnuplot.Data(int_p... |
plotly/python-api | packages/python/plotly/plotly/validators/waterfall/insidetextfont/_colorsrc.py | Python | mit | 472 | 0.002119 | import _plotly_utils.basevalidators
class ColorsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name="colorsrc", parent_name="waterfall.ins | idetextfont", **kwargs
):
super(ColorsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),
rol | e=kwargs.pop("role", "info"),
**kwargs
)
|
asedunov/intellij-community | python/helpers/pydev/_pydevd_bundle/pydevd_tracing.py | Python | apache-2.0 | 4,642 | 0.008186 | from _pydevd_bundle.pydevd_constants import get_frame
from _pydev_imps._pydev_saved_modules import thread, threading
try:
import cStringIO as StringIO #may not always be available @UnusedImport
except:
try:
import StringIO #@Reimport
except:
import io as StringIO
import sys #@Reimport
imp... | _func):
if TracingFunctionHolder._warn:
frame = get_frame()
if frame is not None and frame.f_back is not None:
if not frame.f_back.f_code.co_filename.lower().endswith('threading.py'):
message = \
'\nPYDEV DEBUGGER WARNING:' + \
... | top working correctly.' + \
'%s' % _get_stack_str(frame.f_back)
if message not in TracingFunctionHolder._warnings_shown:
#only warn about each message once...
TracingFunctionHolder._warnings_shown[message] = 1
s... |
Britefury/scikit-image | skimage/io/tests/test_io.py | Python | bsd-3-clause | 769 | 0 | import os
from numpy.testing import assert_array_equal, raises, run_module_suite
import numpy as np
import skimage.io as io
from skimage.io.manage_plugins import plugin_store
from skimage import data_dir
def t | est_stack_basic():
x | = np.arange(12).reshape(3, 4)
io.push(x)
assert_array_equal(io.pop(), x)
@raises(ValueError)
def test_stack_non_array():
io.push([[1, 2, 3]])
def test_imread_url():
# tweak data path so that file URI works on both unix and windows.
data_path = data_dir.lstrip(os.path.sep)
data_path = data_p... |
wasade/qiita | setup.py | Python | bsd-3-clause | 3,898 | 0 | #!/usr/bin/env python
# -----------------------------------------------------------------------------
# Copyright (c) 2013, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ---------------------------... | :: CPython
Operating System :: POSIX :: Linux
Operating System :: MacOS :: MacOS X
"""
long_description = """Qiita: Spot Patterns"""
classifiers = [s.strip() for s in classes.split('\n') if s]
setup(name='qiita-spots',
version=__version__,
long_description=long_description,
license="BSD",
| description='Qiita: Spot Patterns',
author="Qiita development team",
author_email="mcdonadt@colorado.edu",
url='https://github.com/biocore/qiita',
test_suite='nose.collector',
packages=['qiita_core',
'qiita_db',
'qiita_pet',
'qiita_pet/... |
frohoff/Empire | lib/modules/powershell/situational_awareness/network/get_sql_server_info.py | Python | bsd-3-clause | 4,512 | 0.011968 | from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Get-SQLServerInfo',
'Author': ['@_nullbind', '@0xbadjuju'],
'Description': ('Returns basic server and user information from target SQL Servers.'),
'... | LInstanceDomain',
'Required' : False,
'Value' : ''
}
}
self.mainMenu = mainMenu
for param in params:
# parameter format is [Name, Value]
option, value = param
if option in self.options:
... | alue']
password = self.options['Password']['Value']
instance = self.options['Instance']['Value']
check_all = self.options['CheckAll']['Value']
# read in the common module source code
moduleSource = self.mainMenu.installPath + "/data/module_source/situational_awareness/network/Ge... |
GregJohnStewart/NumberGuesser | numberGuesser.py | Python | mit | 7,208 | 0.034545 | #!/usr/bin/python
"""
NumberGuesser
Guesses your number!
Author: Greg Stewart
Copyright 2014 Greg Stewart
Start: 7/15/14
Tries to guess your number, interacts with you via the Raspberry pi's
16x2 CharLCDPlate
It uses a relatively simple algorithm to guess numbers:
Step 1:
Find a number that is larger tha... | un:
if lcd.buttonPressed(lcd.RIGHT):#too high
answered = True
highGuess = lastG | uess
print "\tFound another upper bounds: {0}".format(highGuess)
elif lcd.buttonPressed(lcd.LEFT):#too low
answered = True
lowGuess = lastGuess
print "\tFound another lower bounds: {0}".format(lastGuess)
elif lcd.buttonPressed(lcd.SELECT):
inStep = False
answered = True
run = False
... |
nlhepler/freetype-py3 | examples/glyph-vector.py | Python | bsd-3-clause | 2,878 | 0.008687 | # -----------------------------------------------------------------------------
#
# FreeType high-level python API - Copyright 2011 Nicolas P. Rougier
# Distributed under the terms of the new BSD license.
#
# -----------------------------------------------------------------------------
'''
Show how to access glyph ou... | ls='dashed', lw=1 )
axis.add_patch(patch)
axis.add_patch(glyph)
axis.set_xlim(x.min()-100, x.max() | +100)
plt.xticks([])
axis.set_ylim(y.min()-100, y.max()+100)
plt.yticks([])
plt.show()
|
mvanveen/cargo | cargo/dock.py | Python | mit | 2,845 | 0.01406 | import docker
from cargo.container import Container
from cargo.image import Image
# this is a hack to get `__getattribute__` working for a few reserved properties
RESERVED_METHODS = ['containers', '_client', 'images', 'info', 'start', 'stop']
class Dock(object):
"""Wrapper class for `doc | ker-py` Client instances"""
def __init__(self, *args, **kw):
super(Dock, self).__init__()
self._client = docker.Client(*args, **kw)
def __repr__(self):
return '<Dock [%s] (%s)>' % (self.base_url, self.version().get('Version'))
def | __getattribute__(self, x):
client = super(Dock, self).__getattribute__('_client')
# return client attribute if not a magic method or reserved attr
legal = not x.startswith('_') and not(x in RESERVED_METHODS)
if hasattr(client, x) and legal:
return client.__getattribute__(x)
return super(Do... |
tweksteen/compute-image-packages | gcimagebundle/gcimagebundlelib/utils.py | Python | apache-2.0 | 13,831 | 0.008242 | # Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | aise M | akeFileSystemException(dev_path)
mkfs_cmd = ['mkfs', '-t', fs_type, dev_path]
RunCommand(mkfs_cmd)
if fs_type is 'xfs':
set_uuid_cmd = ['xfs_admin', '-U', uuid, dev_path]
else:
set_uuid_cmd = ['tune2fs', '-U', uuid, dev_path]
RunCommand(set_uuid_cmd)
return uuid
def Rsync(src, dest, exclude_fil... |
aricaldeira/pyxmlsec | examples/decrypt2.py | Python | gpl-2.0 | 5,179 | 0.00753 | #!/usr/bin/env python
#
# $Id: decrypt2.py 363 2006-01-01 18:03:07Z valos $
#
# PyXMLSec example: Decrypting an encrypted file using keys manager.
#
# Decrypts encrypted XML file using keys manager and a list of
# DES key from a binary file
#
# Usage:
# decrypt2.py <xml-enc> <des-key-file1> [<des-key-file2> [...]]
#... | # Create and initialize keys manager, we use a simple list based
# keys manager, implement your own KeysStore klass if you need
# something more sophisticated
mngr = xmlsec.KeysMngr()
if mngr is None:
print "Error: failed to create | keys manager."
return None
if xmlsec.cryptoAppDefaultKeysMngrInit(mngr) < 0:
print "Error: failed to initialize keys manager."
mngr.destroy()
return None
for file in files:
if not check_filename(file):
mngr.destroy()
return None
# Load DES ... |
Rareson/LammpsRelated | gui.py | Python | gpl-3.0 | 7,329 | 0.002047 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './QtGUI.ui'
#
# Created: Sat Oct 11 18:25:23 2014
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
from gui.LrBase.main import *
try:
_fromUtf8 = QtCore... | r.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.tabWidget.setCurrentIndex(0)
QtCore.QObject.connect(self.comboBox, QtCore.SIGNAL(_fromUtf8("currentIndexChanged(int)")), self.textBrowser.reload)
QtCore.QObject.co... | Button, QtCore.SIGNAL(_fromUtf8("clicked()")), self.statusbar.show)
QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8("clicked()")), compileLr.compileMEAM_REAX)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_... |
IsoPass/isopass-python | run_isopass_cmd.py | Python | gpl-3.0 | 200 | 0 | # run | _isopass_cmd.py
# Yu Gui 1/24/2017
# *** Use this program to start IsoPass commandline ***
# Requirement: Python 3.5
im | port isopass
if __name__ == "__main__":
isopass.cmd.run()
|
kogotko/carburetor | openstack_dashboard/dashboards/project/api_access/views.py | Python | apache-2.0 | 9,052 | 0 | # Copyright 2012 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 ... | ate = 'project/api_access/clouds.yaml.template'
context = _get_openrc_credentials(request)
context['cloud_name'] = getattr(
settings | , "OPENSTACK_CLOUDS_YAML_NAME", 'openstack')
context['profile'] = getattr(
settings, "OPENSTACK_CLOUDS_YAML_PROFILE", None)
context['regions'] = [
region_tuple[1] for region_tuple in getattr(
settings, "AVAILABLE_REGIONS", [])
]
if utils.get_keystone_version() >= 3:
... |
afg984/happycoding | jinjadp/bootstrap.py | Python | mit | 1,014 | 0.002959 | import bootstrap3.forms
from jinja2 import Markup
from jinjadp.utils import safe_rendering
@object.__new__
class bootstrap:
| def __getattr__(self, name):
setattr(
self,
name,
safe_rendering(
| getattr(
bootstrap3.forms,
'render_' + name
)
)
)
return getattr(self, name)
def button(
self,
text,
class_='primary',
layout='horizontal',
type='submit'
):
assert layout == 'hori... |
fyskam/medlemsgallring | create_hash.py | Python | mit | 987 | 0.004053 | #Just a script to create hashes if not already done so
import mysql.connector as sql
import datetime
import hashlib, uuid
sql_config = {
'user': 'fyskam',
'password': 'abc123',
'host': '130.238.93.116',
'database': 'register_copy',
'raise_on_warnings': True,
}
try:
con = sql.connect(**sql_conf... | uffered=True)
query = ("SELECT id,mail from members WHERE hash<>'';")
query = ("SELECT id,mail from members WHERE hash IS NULL OR hash='';")
| update = ("UPDATE members SET hash=%s WHERE id=%s")
cursor.execute(query)
for (idn, mail) in cursor:
salt = uuid.uuid4().hex
hashed = hashlib.sha256(mail).hexdigest()
salt_hash = hashlib.sha256(mail+salt).hexdigest()
cursor2.execute(update, [salt_hash, idn])
con.commit()... |
vinipachecov/django-ecommerce | djangoecommerce/s3util.py | Python | cc0-1.0 | 266 | 0 | # coding=utf-8
from django.conf import settings
from storages.backends.s3boto import S3BotoStorage
class Stati | cStorage(S3BotoStorage):
location = settings.STATICFILES_LOCATION
class MediaStorage(S3BotoStorage):
location = settings.MEDI | AFILES_LOCATION
|
benzkji/django-admin-sort | admin_sort/admin/change_list.py | Python | mit | 10,907 | 0.000275 | from __future__ import unicode_literals
from django import forms
from django.conf import settings
from django.conf.urls import url
from django.core.exceptions import ImproperlyConfigured
from django.db import transaction
from django.forms import widgets
from django.http import (
HttpResponseBadRequest,
HttpRes... | _display
def get_list_display_links(self, request, list_display):
if (self.list_display_links or self.list_display_links is None or not list_display):
return self.li | st_display_links
else:
# Use only the second item in list_display as link
# second because first is aur drag handle
return list(list_display)[1:2]
def get_queryset(self, request):
qs = super(SortableAdminMixin, self).get_queryset(request)
return qs
d... |
AndyDiamondstein/vitess | py/vtdb/grpc_vtgate_client.py | Python | bsd-3-clause | 9,838 | 0.00864 | # Copyright 2013 Google Inc. All Rights Reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
"""A simple, direct connection to the vtgate proxy server, using gRPC.
"""
import logging
import re
from urlparse import urlparse
# Import main protobuf library firs... | f.private_key or self.certificate_chain:
creds = implementations.ssl_channel_credentials | (
self.root_certificates, self.private_key, self.certificate_chain)
channel = implementations.secure_channel(p.hostname, p.port, creds)
else:
channel = implementations.insecure_channel(p.hostname, p.port)
self.stub = vtgateservice_pb2.beta_create_Vitess_stub(channel)
def close(self):
... |
bjodah/pyodesys | pyodesys/native/odeint.py | Python | bsd-2-clause | 713 | 0 | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
import copy
from ..util import import_
from ._base import _NativeCodeBase, _NativeSysBase, _compile_kwargs
pyodeint = import_('pyodeint')
class NativeOdeintCode(_NativeCodeBase):
wrapper_name = '_odeint_wrapper'
def... | **kwargs):
self.compile_kwargs = copy.deepcopy(_compile_kwargs)
self.compile_kwargs['include_dirs'].append(pyodeint.get_include())
self.compile_kwargs['libraries'].extend(['m'])
super(NativeOdeintCode, self).__init__(*args, **kwargs)
class NativeOdeintSys(_NativeSysBase):
_NativeCo... | t'
|
kuangyh/chord | src/solo/lisp_for.py | Python | bsd-2-clause | 1,987 | 0.027177 | # -*- coding: utf-8 -*-
import lisp
import proc
import pycode
import context
def prim_for(compiler, src):
if lisp.Symbol('<-') != src[2]:
raise SyntaxError(src[:3])
matcher = src[1]
datasource = src[3]
body = src[4:]
queue_name = pycode.name('for_queue')
context.curr().setdefault('FOR_STACK... | ame)
datasource_code = compiler.compile(datasource)
if body:
body_code = compiler.compile((lisp.Symbol('env'), matcher) + body)
else:
body_code = pycode.create(matcher.name)
output_code = pycode.create(tpl, datasource_code, body_code)
else:
datasource_code = compiler.compile(datasource)
if datasourc... | .compile(for_var, matcher)
tpl = \
'%s = []\n' % (queue_name,) + \
'for %s in $#:\n' % (for_var,) + \
' try:\n' + \
' $#\n' + \
' except _ME, e:\n' + \
' continue\n' + \
' %s.append($#)\n' % (queue_name,) + \
queue_name
if body:
body_code = compiler.compile(
(lisp.Symbol('env'), ... |
luckytianyiyan/TyStrings | tystrings/strings.py | Python | mit | 6,149 | 0.001464 | import os
import re
import codecs
import subprocess
import tempfile
import shutil
from .tylogger import logger
DEFAULT_ENCODING = 'utf16'
class Strings(object):
def __init__(self, encoding=DEFAULT_ENCODING, aliases=None):
self.encoding = encoding if encoding else DEFAULT_ENCODING
self.__reference... | :
"""parsing `.strings` file.
:param filename: .strings filename
:param encoding: file encoding
:return: reference
"""
reference = dict((elem[0], elem[1]) for elem in Strings.__reference_generator(filename, encoding))
return reference
@staticmethod
def pa... | list(Strings.__reference_generator(filename, encoding))
@staticmethod
def __reference_generator(filename, encoding=DEFAULT_ENCODING):
if os.path.exists(filename):
line_end = [0]
contents = ''
with codecs.open(filename, mode='r', encoding=encoding if encoding else DE... |
cga-harvard/cga-worldmap | geonode/contrib/datatables/utils_lat_lng.py | Python | gpl-3.0 | 18,580 | 0.005005 | """
Functions for creating maps from tabular files with lat/lng columns.
Incudes creation of DataTable, Layer, and LatLngTableMappingRecord objects
"""
import datetime
import json
import sys
import traceback
import uuid
# Postgres
import psycopg2
from geonode.contrib.datatables.db_helper import get_datastore_connectio... | = "Could not find DataTable with name: %s" % (table_name)
LOGGER.error(err_msg)
return False, err_msg
# ----------------------------------------------------
# Latitude attribute
# ----------------------------------------------------
lat_col_attr = dt.get_attribute_by_name(standardize_c... | % (table_name, lat_column, standardize_column_name(lat_column))
LOGGER.error(err_msg)
return False, err_msg
is_valid, err_msg = is_valid_lat_lng_attribute(lat_col_attr)
if not is_valid:
LOGGER.error(err_msg)
return False, err_msg
# ----------------------------------... |
jrouly/stepup | stepup/settings/urls.py | Python | mit | 1,653 | 0.020569 | from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib import auth
admin.autodiscover()
urlpatterns = patterns('stepup.views',
# Examples:
# url(r'^$', 'volunteer.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
#auth
url(r'^ad... | opportunity'),
# all opportunities
url(r'^opportunity/', 'all_opportunity', name = 'view_all_opportunity'),
# organization
url(r'^organization/(?P<slug>[^\.]+)', 'organization', name = 'view_organization'),
#url(r'^tag/(?P<slug>[^\.]+)', 'tag', name = 'view_tag'),
# all organizations
... | rganization/', 'all_organizations', name = 'view_all_organization'),
# comments
url(r'^comments/', include('django.contrib.comments.urls')),
# search
url(r'^search/', 'search', name = 'view_search'),
)
#urlpatterns += patterns('',
# url(r'^login/', 'django.contrib.auth.views.login', {'template_nam... |
LucianU/django-failclose | failclose/utils.py | Python | mit | 2,530 | 0.001976 | import functools
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
from django.db.models.loading import get_app
def safe(view):
"""Marks a view as safe to be called"""
@functools.wraps(view)
def wrapper(*args, **kwargs... | :
rules = import_module(settings.PERMISSIONS_MODULE).RULES
else:
raise ImproperlyConfigured(
'You need to specify a PERMISSIONS_MODULE '
'in your settings.py'
)
_validate_rules(rules)
# retrieving the view's app name and the c... | safe_views list is empty, it means that all views
# are whitelisted
if not safe_views or view.__name__ in safe_views:
return True
if getattr(view, 'safe', None):
return True
return False
def _get_app_name(view):
path_components = view.__module__.split('.')
project... |
Sulverus/aqueduct | aqueduct/storages/basic.py | Python | mit | 4,409 | 0.000454 | #encoding: utf8
class MemoryStorage(object):
"""
Simple(dummy) in-memory storage
In production better to use some database. Written to describe the api and testing
"""
def __init__(self, config):
# configuration of channels and services provided by application
self.config = config
... | self.storage)
def add_channel(self, channel):
"""
Try to create a channel in the storage
"""
if channel in self.clients:
return False
self.clients[channel] = []
return True
def subscribe(self, client, api_key, channel):
"""
Subscribe ... | e
pair = (client, api_key)
if pair in self.clients[channel]:
return False
self.clients[channel].append(pair)
return True
def unsubscribe(self, client, channel):
"""
Unsubscribe client from the channel
N.B. we must drop all messages in queue for t... |
claudep/pootle | pootle/apps/pootle_score/migrations/0003_add_pootle_user_store_score.py | Python | gpl-3.0 | 1,645 | 0.001824 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-14 19:45
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('pootle_store', '0045_remov... | models.DateField(db_index=True)),
('score', models.FloatField(db_index=True)),
('reviewed', models.IntegerField(db_index=True, default=0)),
('suggested', models.IntegerField(db_index=True, default=0)),
('translated', models.IntegerField(db_index=True, defa... | letion.CASCADE, related_name='user_scores', to='pootle_store.Store')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='store_scores', to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
'db_table': '... |
SummerLW/Perf-Insight-Report | dashboard/dashboard/issue_tracker_service.py | Python | bsd-3-clause | 6,428 | 0.004667 | # 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.
"""Provides a layer of abstraction for the issue tracker API."""
import logging
from apiclient import discovery
from apiclient import errors
import httplib... | :
body: The request body parameter dictionary.
Returns:
A bug ID if successful, or None otherwise.
"""
request = self._service.issues().insert(projectId='chromium', body=body)
response = self._ExecuteRequest(request)
if response and 'id' in response:
return response['id']
retu... | e
def GetLastBugCommentsAndTimestamp(self, bug_id):
"""Gets last updated comments and timestamp in the given bug.
Args:
bug_id: Bug ID of the issue to update.
Returns:
A dictionary with last comment and timestamp, or None on failure.
"""
if not bug_id or bug_id < 0:
return Non... |
raurope/django-adminrestrict | adminrestrict/test_settings.py | Python | mit | 840 | 0.00119 | import os
import django
if django.VERSION[:2] >= (1, 3):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
else:
DATABASE_ENGINE = 'sqlite3'
SITE_ID = 1
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',... | jango.contrib.auth.middleware.AuthenticationMiddleware',
'adminrestrict.middleware.AdminPagesRestrictMiddleware'
)
ROOT_URLCONF = 'adminrestrict.test_urls'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
| 'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'adminrestrict',
]
SECRET_KEY = 'too-secret-for-test'
LOGIN_REDIRECT_URL = '/admin'
|
nihlaeth/voicetrainer | voicetrainer/midi.py | Python | gpl-3.0 | 42,017 | 0.002666 | # -*- coding: utf-8 -*-
# pylint: disable=too-many-lines,too-complex,too-many-branches
# pylint: disable=too-many-statements,arguments-differ
# needs refactoring, but I don't have the energy for anything
# more than a superficial cleanup.
#-------------------------------------------------------------------------------
... | ation << 8) + ord(midi_str_or_num)
return summation, midi_str[length:]
else:
mid_num = mi | di_str
summation = mid_num - ((mid_num >> (8*length)) << (8*length))
big_bytes = mid_num - summation
return summation, big_bytes
def get_variable_length_number(midi_str):
r'''
Given a string of data, strip off a the first character, or all high-byte characters
terminating with one w... |
wadester/wh_test_py | generator2.py | Python | gpl-2.0 | 2,181 | 0.008253 | #!/usr/bin/env python
# Module: generator2.py
# Purpose: sample generator classes #2
# Date: N/A
# Notes:
# 1) Test python code
# 2) Ref: https://docs.python.org/2/reference/expressions.html
import numpy as np
print "generator2.py: python generator test code #2"
# echo from the generator examples
# - ... | set xv if user calls send(n)
xv = yield iiv
# if xv is sane, change the loop number
if (xv != None):
print "g1() setting to ", xv
iiv=xv
except Exception, e:
yield e
finally:
print "g1() done... | print "x=", x
g.close()
print "Creating g1(7) and using next() and send()"
g=g1(7)
x=g.next()
print "g.next()= ", x
print "g.next()= ", g.next()
x=g.send(3)
print "g.send(3)=", x
print "g.next()= ", g.next()
print "g.next()= ", g.next()
print "numpy generator: g=(np.cos(x) for x in np.arange(0, 10, .1))"
g=(np.c... |
rebolinho/liveit.repository | script.video.F4mProxy/lib/f4mUtils/openssl_aes.py | Python | gpl-2.0 | 1,996 | 0.00501 | # Author: Trevor Perrin
# See the LICENSE file for legal information regarding use of this file.
"""OpenSSL/M2Crypto AES implementation."""
from .cryptomath import *
from .aes import *
if m2cryptoLoaded:
def new(key, mode, IV):
return OpenSSL_AES(key, mode, IV)
class OpenSSL_AES(AES):
... | m2.cipher_init(context, cipherType, self.key, self.IV, encrypt)
return context
def encrypt(self, plaintext):
|
AES.encrypt(self, plaintext)
context = self._createContext(1)
ciphertext = m2.cipher_update(context, plaintext)
m2.cipher_ctx_free(context)
self.IV = ciphertext[-self.block_size:]
return bytearray(ciphertext)
def decrypt(self, ciph... |
Scholr/scholr-roles | scholrroles/management/commands/update_roles.py | Python | bsd-3-clause | 4,576 | 0.006337 | # -*- coding: utf-8 -*-
#
# This file is part of Django appschema released under the MIT license.
# See the LICENSE for more information.
from optparse import make_option
from django.conf import settings
from django.core.management.base import BaseCommand
from django.contrib.contenttypes.models import ContentType
from ... |
to_delete = Permission.objects.exclude(pk__in=dont_delete)
if to_delete:
print """
--------------------
Delete Permissions
---------------- | ----
"""
for perm in to_delete:
print perm
to_delete.delete()
def update_perm_roles(self, perm, existing_perm):
if existing_perm.roles.filter(name__in=perm['roles']).count() < len(perm['roles']):
print " Adding roles to: {}".format(... |
AlfioEmanueleFresta/practical-ecb-lib | cp_ecb/image.py | Python | gpl-3.0 | 4,402 | 0.002045 | from PIL import Image
class InMemoryImage:
"""
A very simple class to represent an image.
"""
def __init__(self, w, h, c=3,
b=b'', encrypted=False):
"""
Instantiate a new image.
:param w: The width of the image (px).
:param h: The height of the image (... | t flagged as encrypted an | d can't be decrypted.")
image.b = function(image.b)
# Allow return list of ordinals
if type(image.b) is list:
image.b = bytes(image.b)
image.encrypted = encrypt
return image
def encrypt_image(image, function):
"""
Encrypt the content of an InMemoryImage using a given function.
... |
esetera/Objavi | tests/make_all_epubs.py | Python | agpl-3.0 | 1,437 | 0.006959 | #!/usr/bin/python
import os
# Preliminary bit to get cgi scripts working
def guess_http_host():
hostnames = {
'cloudy': 'objavi.halo.gen.nz',
'vps504': 'objavi.flossmanuals.net',
}
f = open('/etc/hostname')
host = f.read().strip()
f.close()
try:
os.environ['HTTP_HOST']... | ---------------#
import traceback
from objavi.fmbook import log, ZipBook, make_book_name
from objavi import config
from objavi.twiki_wrapper import get_book_list
def make_epub(server, bookid):
log('making epub for %s %s' % (server, bookid))
bookname = make_boo | k_name(bookid, server, '.epub')
book = ZipBook(server, bookid, bookname=bookname, project='FM')
book.make_epub(use_cache=True)
for server, settings in config.SERVER_DEFAULTS.items():
if settings['interface'] == 'Booki':
continue
books = get_book_list(server)
for book in books:
try... |
Justasic/StackSmash | StackSmash/apps/uploader/views.py | Python | bsd-2-clause | 1,444 | 0 | # -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect, Http404
from django.core.urlresolvers import reverse
from StackSmash.apps.uploader.models import Document
from StackSmash.apps.uploader.forms import DocumentF... | edirect to the document list after POST
return HttpResponseRedirect(reverse('upload:list'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page |
documents = Document.objects.all()
# Render list page with the documents and the form
return render_to_response(
'uploader/list.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
def delete(request, pk):
# Make sure the user is authe... |
MiracleWong/PythonBasic | mail/mail.py | Python | mit | 1,571 | 0.003992 | # -*- coding: utf-8 -*-
import email
from email.header import decode_header
# 只读取收件箱中的未读邮件
def get_mail(client):
mail_list = []
resp, data = client.search(None, "UNSEEN")
if data:
for num in data[0].split():
typ, data = client.fetch(int(num), "(RFC822)")
msg = data[0][1]
... | subject_info = msg.get("Subject")
subject = decode_header(subject_info)[0][0]
from_info = email.utils.parseaddr(msg.get("From"))
if len(from_info) == 2:
user = email.header.decode_header(from_in | fo[0])[0][0]
from_addr = user + "<" + from_info[1] + ">"
else:
from_addr = from_info
date = msg.get("Date")
content = None
for i in msg.walk():
content_type = i.get_content_type()
content_charset = i.get_cha... |
Outernet-Project/artexinweb | artexinweb/exceptions.py | Python | gpl-3.0 | 121 | 0 | # -*- coding: u | tf-8 -*-
class ImproperlyConfigured(Exception):
pass
class TaskHandlingError(Exception):
pass
| |
FeodorFitsner/kauri | script/emoji/__init__.py | Python | gpl-3.0 | 253 | 0 | # -*- coding: utf-8 -*-
"""
emoji
~~~~~
emoji terminal output for Python
:copyright: (c) 2014 by Taehoon Kim.
:license: BSD, see LICENSE for more details.
"""
from .emoji import emojize
__version__ = '0.1.0'
__all__ = ['emoji | ze']
| |
0xc0170/project_generator | project_generator/tools/eclipse.py | Python | apache-2.0 | 3,406 | 0.002936 | # Copyright 2014-2015 0xc0170
#
# 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,... | ,
'files': {
'proj_file': '',
'cproj': '',
'makefile': '',
}
}
def __init__(self, workspace, env_settings):
self.definitions = 0
self.exporter = MakefileGccArm(workspace, env_settings)
self.workspace = workspace
self.env_settin... | def get_toolchain():
return 'gcc_arm'
def _expand_one_file(self, source, new_data, extension):
return {"path": join('PARENT-%s-PROJECT_LOC' % new_data['output_dir']['rel_path'], normpath(source)), "name": basename(
source), "type": self.file_types[extension.lower()]}
de... |
mcepl/youtube-dl | youtube_dl/extractor/common.py | Python | unlicense | 89,946 | 0.002212 | from __future__ import unicode_literals
import base64
import datetime
import hashlib
import json
import netrc
import os
import re
import socket
import sys
import time
import math
from ..compat import (
compat_cookiejar,
compat_cookies,
compat_etree_fromstring,
compat_getpass,
compat_http_client,
... | s than default.
* http_headers A dictionary of additional HTTP headers
to add to the request.
* stretched_ratio If given and not 1, indicates that the
video's pixels are not square.
| width : height ratio as float.
* no_resume The server does not support resuming the
(HTTP or RTMP) download. Boolean.
url: Final video URL.
ext: Video filename extension.
format: The video format, defaults to ext (used ... |
PanDAWMS/panda-harvester | pandaharvester/harvesterstager/rucio_rse_direct_stager.py | Python | apache-2.0 | 11,181 | 0.00787 | from rucio.client import Client as RucioClient
from rucio.common.exception import DataIdentifierNotFound, DuplicateRule, DataIdentifierAlreadyExists, \
FileAlreadyExists
from pandaharvester.harvestercore import core_utils
from pandaharvester.harvesterstager import yoda_rucio_rse_direct_stager
from pandaharvester.h... | r_stage_out')
tmpLog.debug('executing base trigger_stage_out')
tmpStat, tmpMsg = YodaRseDirect.trigger_stage_out(self, jobspec)
tmpLog.debug('got {0} {1}'.format(tmpStat, tmpMsg))
if tmpStat is not True:
return tmpStat, tmpMsg
# Now that output files have been all cop... | dstRSE = None
datasetName = 'panda.harvester.{0}.{1}'.format(jobspec.PandaID,str(uuid.uuid4()))
datasetScope = 'transient'
# get destination endpoint
nucleus = jobspec.jobParams['nucleus']
agis = self.dbInterface.get_cache('panda_queues.json').data
dstRSE = [agis[x... |
cjparsons74/Kupfer-cjparsons74 | kupfer/plugin_support.py | Python | gpl-3.0 | 3,958 | 0.02476 | import gobject
from kupfer import pretty
from kupfer.core import settings
from kupfer.core.settings import UserNamePassword
__all__ = [
"UserNamePassword",
"PluginSettings",
"check_dbus_connection",
]
def _is_core_setting(key):
return key.startswith("kupfer_")
class PluginSettings (gobject.GObject, pretty.Outpu... | -Bus;
if this check is used, the plugin may use D-Bus and assume it
is available in the Plugin's code.
"""
global _has_dbus_connection
if _has_dbus_connection is None:
import dbus
try:
dbus.Bus()
_has_dbus_connection = True
except dbus.DBusException, err:
_has_dbus_connection = False
if not _has_db... | sion"))
|
google/llvm-propeller | lldb/test/API/lang/cpp/namespace/TestNamespace.py | Python | apache-2.0 | 9,174 | 0.002289 | """
Test the printing of anonymous and named namespace variables.
"""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class NamespaceBreakpointTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
@expectedFailureAll(bug... | .
self.expect("frame variable A::B::j", VARIABLES_DISPLAYED_CORRECTLY,
startstr='(int) A::B::j = 4',
patterns=[' = 4'])
# So should the anonymous namespace case.
self.expect(
"frame variable '(anonymous namespace)::i'",
VARIABLES_D... | startstr='(int) (anonymous namespace)::i = 3',
patterns=[' = 3'])
# rdar://problem/8660275
# test/namespace: ' |
alej0varas/estafa | src/estafa/denuncia/tests.py | Python | gpl-3.0 | 5,313 | 0.000188 | # -*- coding: utf-8 -*-
from django.test import TestCase
from django.db import IntegrityError
from django.core.urlresolvers import reverse
from models import Denuncia
# ugli import because test fails other way
from estafa.denuncia.forms import DenunciaForm
# Models
class DenunciaModelTest(TestCase):
def test_ca... | that does not does
not set `denuncia` in context.
"""
| denuncia = Denuncia.objects.create(number=98765432)
data = {'number': 9876543}
url = reverse('denuncia')
response = self.client.get(url, data)
self.assertEqual(response.status_code, 200)
self.assertFalse('denuncia' in response.context)
def test_post(self):
... |
bitmovin/bitmovin-python | bitmovin/resources/models/encodings/inputstreams/time_based_trimming_input_stream.py | Python | unlicense | 1,418 | 0.002116 | from .abstract_trimming_input_stream import AbstractTrimmingInputStream
class TimeBasedTrimmingInputStream(AbstractTrimmingInputStream):
def __init__(self, input_stream_id, offset=None, duration=None, id_=None, custom_data=None, name=None,
description=None):
super().__init__(id_=id_, cus... | bject.get('offset')
duration = json_ob | ject.get('duration')
time_based_trimming_input_stream = TimeBasedTrimmingInputStream(
input_stream_id=input_stream_id,
offset=offset,
duration=duration,
id_=id_,
custom_data=custom_data,
name=name,
description=description
... |
wadobo/timebank | user/forms.py | Python | agpl-3.0 | 5,777 | 0.006059 | # -*- coding: utf-8 -*-
# Copyright (C) 2010 Eduardo Robles Elvira <edulix AT gmail DOT com>
#
# 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 yo... | %m/%Y",))
first_name = FormCharField(label=_("Name"), required=True, max_length=30)
last_name = FormCharField(label=_("Last name"), required=True, max_length=30)
email = FormEmailField(label=_("Email address"), required=Tru | e)
address = FormCharField(label=_("Address"), required=True,
max_length=100, help_text=_("Example: Avda. Molina, 12, Sevilla"))
description = FormCharField(label=_("Personal description"), required=True,
max_length=300, widget=forms.Textarea())
land_line = FormCharField(label=_("Land line")... |
dsandersAzure/python_cowbull_server | PersistenceExtensions/File.py | Python | apache-2.0 | 1,914 | 0.00627 | from flask_helpers.ErrorHandler import ErrorHandler
from Persistence.AbstractPersister import AbstractPersister
import io
import json
import pymongo
class Persister(AbstractPersister):
def __init__(
self
):
super(Persister, self).__init__()
self.handler.module="File Persister"
... | t(key, filename))
json_return = None
try:
json_return=f.read()
except IOError as ioe:
raise KeyError("Unable to open the key file: {}".format(str(filename)))
finally:
f.close()
self.handler.log(message="F | etched {} from key {} in file: {}".format(json_return, key, filename))
return json_return
|
try-dash-now/dash-ia | lib/Database.py | Python | mit | 1,885 | 0.033422 | # -*- coding: UTF-8 -*-
__author__ = 'Sean Yu'
__mail__ = 'try.dash.now@gmail.com'
import sqlite3
def CreateTable(dbname, table,table_define):
db = sqlite3.connect(dbname)
cu=db.cursor() |
cu.execute("""create table %s ( %s )"""%(table,table_define))
db.commit()
cu.close()
db.close()
def InsertRecord(dbname, table,record):
db = sqlite3.connect(dbname)
cu=db.cursor()
cu.execute('''insert into %s values(%s)'''%(table,record))
db.commit()
cu.close()
db.close()
def ... | t status='compleded' where id = 0")
db = sqlite3.connect(dbname)
cu=db.cursor()
cu.execute('''update %s set %s where %s'''%(table,action,condition))
db.commit()
cu.close()
db.close()
def RemoveRecord(dbname,table, condition ):
#cu.execute("update tasks set status='compleded' where id = ... |
nacc/autotest | server/profiler.py | Python | gpl-2.0 | 2,528 | 0.001978 | import itertools
try:
import autotest.common as common
except ImportError:
import common
def _get_unpassable_types(arg):
""" Given an argument, returns a set of types contained in arg that are
unpassable. If arg is an atomic type (e.g. int) it either returns an
empty set (if the type is passable) ... | = "arguments of type '%s' cannot be passed to r | emote profilers"
msg %= ", ".join(t.__name__ for t in unpassable_types)
raise TypeError(msg)
class profiler_proxy(object):
""" This is a server-side class that acts as a proxy to a real client-side
profiler class."""
def __init__(self, profiler_name):
self.name = profiler_name
... |
TUBAME/migration-tool | src/tubame.portability/resources/tubame-search-modules/src/extend/__init__.py | Python | apache-2.0 | 984 | 0.009146 | # -*- coding: utf-8 -*-
"""
__init__.py
Created on 2013/06/28
Copyright (C) 2011-2013 Nippon Telegraph and Telephone 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 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 t... | ironment] Python 2.7
"""
__all__ = ["ext_search_xml_xpath","ext_report_generator","ext_search_xml_definedclass","ext_search_step_counter","ext_search_interface_method_definedxml","ext_search_xml_text","ext_search_java_api","ext_search_sql"] |
netscaler/horizon | openstack_dashboard/dashboards/admin/projects/workflows.py | Python | apache-2.0 | 33,143 | 0.000151 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# no... | domain_id = self.initial.get("domain_id", None)
project_id = ''
if 'project_id' in self.initial:
project_id = self.initial['project_id']
# Get the default role
try:
default_role = api.keystone.get_default_role(self.request)
# Default role is neces... | _role is None:
default = getattr(settings,
"OPENSTACK_KEYSTONE_DEFAULT_ROLE", None)
msg = _('Could not find default role "%s" in Keystone') % \
default
raise exceptions.NotFound(msg)
except Exception:
... |
skilstak/code-dot-org-python | tests/codestudio_tests.py | Python | unlicense | 137 | 0.021898 | import sys
sy | s.path.append('..')
import codestudio | .artist as a
from nose.tools import assert_equals
from nose.tools import assert_raises
|
MDA2014/django-abm | apps/home/urls.py | Python | mit | 195 | 0.051282 | from | django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(
regex = r'^$',
view = views.index,
name = 'vista_principal'
),
) | |
stephrdev/brigitte | brigitte/commits/views.py | Python | bsd-3-clause | 1,495 | 0.001338 | # -*- coding: utf-8 -*-
from django.http import Http404
from django.shortcuts import render
from brigitte.repositories.decorators import repository_view
@repository_view()
def commits(request, repo, branchtag):
count = 10
try:
page = int(request.GET.get('page', 1))
except ValueError:
pag... |
# archive = commit.get_archive()
# response = HttpResponse(archive['data']. | getvalue(),
# mimetype=archive['mime'])
# response['Content-Disposition'] = \
# 'attachment; filename="%s-%s.zip"' \
# % (repo.slug, archive['filename'])
# return response
# except:
# raise Http404
|
frreiss/tensorflow-fred | tensorflow/python/kernel_tests/variables_test.py | Python | apache-2.0 | 35,743 | 0.013625 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ======================
"""Tests for tf.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import operator
from absl.testing import parameterized
import numpy as np
from tensorflow.python.eager import context
from tensorflow.python.eag... | tion
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import test_util
from tensorflow.p... |
onshape-public/onshape-clients | python/onshape_client/oas/models/bt_published_workflow_id.py | Python | mit | 4,909 | 0 | # coding: utf-8
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: api-support@onshape.zendesk.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
im... | ]
)
def __init__(
self,
_check_type=True,
_from_server=False,
_path_to_item=(),
_configuration=None,
**kwargs
): # noqa: E501
"""bt_published_workflow_id.BTPublishedWorkflowId - a model defined in OpenAPI
Keyword Args:
_check_typ... | penapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill ... |
rogeriofalcone/treeio | core/api/auth/urls.py | Python | mit | 477 | 0.008386 | # | encoding: utf-8
# Copyright 2011 Tree.io Limited
# This file is part of Treeio.
# License www.tree.io/license
from django.conf.urls.defaults import *
urlpatterns = patterns('treeio.core.api.auth.views',
url(r'^get_request_token$', 'get_request_token', name="api_get_request_token"),
url(r'^authorize_request_t... | |
francisar/rds_manager | aliyun/api/rest/Ram20140214GetUserRequest.py | Python | mit | 334 | 0.02994 | '''
Created by | auto_sdk on 2015.06.23
'''
from aliyun.api.base import RestApi
class Ram20140214GetUserRequest(RestApi):
def __init__(self,domain='ram.aliyu | ncs.com',port=80):
RestApi.__init__(self,domain, port)
self.AccountSpace = None
self.UserName = None
def getapiname(self):
return 'ram.aliyuncs.com.GetUser.2014-02-14'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.