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 |
|---|---|---|---|---|---|---|---|---|
bmilde/ambientsearch | python/wiki_search_es.py | Python | apache-2.0 | 6,033 | 0.010774 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Jonas Wacker, Benjamin Milde'
from elasticsearch import Elasticsearch
import nltk
import traceback
import nltk.data
wiki_index = 'simple_en_wiki'
default_type = 'page'
sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')
# Currently using a pu... | ip2c > 0:
skip2c -= 1
elif i == '}'and skip3c > 0:
skip3c -= 1
elif | i == '|'and skip4c > 0:
skip4c -= 1
elif skip1c == 0 and skip2c == 0 and skip3c == 0 and skip4c == 0:
ret += i
return ret
# Extracts the first n words from the given text.
def get_summary_from_text(text, n=50):
#print '-> fulltext:',text[:500]
text = clean_wiki_brackets(text)
#... |
Finntack/pootle | tests/pootle_fs/fs_response.py | Python | gpl-3.0 | 6,794 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
import pyte... | rt resp.context == context
assert resp.response_types == FS_RESPONSE.keys()
assert resp.has_failed is False
assert resp.made_changes is False
assert list(resp.failed()) == []
assert list(resp. | completed()) == []
assert str(resp) == (
"<ProjectFSResponse(<DummyContext object>): No changes made>")
assert list(resp) == []
with pytest.raises(KeyError):
resp["DOES_NOT_EXIST"]
def _test_item(item, item_state):
assert isinstance(item, ProjectFSItemResponse)
assert item.kwargs["... |
collaj/MusicServer | scripts/test_script_delete.py | Python | agpl-3.0 | 404 | 0.00995 | import os
import time
import sys
FOLD | ERPATH = sys.argv[1]
#os.chdir(FOLDERPATH)
walk = os.walk(FOLDERPATH)
FSEVENT = "delete"
for item in walk:
FILEPATHPREFIX = item[0] + "\\"
for song in item[2]:
if song | .endswith(".mp3"):
FILEPATH = "%s%s" % (FILEPATHPREFIX, song)
os.system('python script.py "' + song + '" "' + FILEPATH + '" "' + FSEVENT + '"') |
proversity-org/problem-builder | problem_builder/step.py | Python | agpl-3.0 | 9,949 | 0.002714 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2014-2015 Harvard, edX & OpenCraft
#
# This software's license gives you freedom; you can copy, convey,
# propagate, redistribute and/or modify this program under the terms of
# the GNU Affero General Public License (AGPL) as published by the Free
# Software Foundation (FSF), e... | display_name=_("Step Title"),
help=_('Leave blank to use sequential numbering'),
default="",
scope=Scope.content
)
# U | ser state
student_results = List(
# Store results of student choices.
default=[],
scope=Scope.user_state
)
next_button_label = String(
display_name=_("Next Button Label"),
help=_("Customize the text of the 'Next' button."),
default=_("Next Step")
)
m... |
AleksNeStu/ggrc-core | test/unit/ggrc_workflows/models/test_workflow.py | Python | apache-2.0 | 2,585 | 0.002321 | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Unit Tests for Workflow model and WorkflowState mixin
"""
from datetime import date
import unittest
from freezegun import freeze_time
from ggrc_workflows.models import cycle_task_group_object_task as c... | k_states": ["Verified", "Assigned", "Assigned"],
"result": "InProgress"
},
{
"task_states": ["InProgress", "InProgress", "InProgress"],
"result": "InProgress"
},
{
"task_states": ["Finished", "InProgress", "Assigned"],
"result":... | ,
{
"task_states": ["Finished", "Declined", "Assigned"],
"result": "InProgress"
},
{
"task_states": ["Finished", "Finished", "Finished"],
"result": "Finished"
},
{
"task_states": ["Verified", "Finished", "Finished"],
... |
rimbalinux/MSISDNArea | docutils/parsers/rst/directives/body.py | Python | bsd-3-clause | 5,963 | 0 | # $Id: body.py 5618 2008-07-28 08:37:32Z strank $
# Author: David Goodger <[email protected]>
# Copyright: This module has been placed in the public domain.
"""
Directives for additional body elements.
See `docutils.parsers.rst.directives` for API details.
"""
__docformat__ = 'reStructuredText'
impor... | n elements:
if isinstance(element, nodes.block_quote):
element['classes'] += self.classes
return elements
class Epigraph(BlockQuote):
classes = ['epigraph']
class Highlights(BlockQuote):
classes = ['highlights']
class PullQuote(BlockQuote):
clas... | _has_content()
text = '\n'.join(self.content)
node = nodes.compound(text)
node['classes'] += self.options.get('class', [])
self.state.nested_parse(self.content, self.content_offset, node)
return [node]
class Container(Directive):
required_arguments = 0
optio... |
asposecells/Aspose_Cells_Java | Plugins/Aspose-Cells-Java-for-Python/tests/WorkingWithFiles/Excel2PdfConversion/Excel2PdfConversion.py | Python | mit | 668 | 0.007485 | # To change t | his license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
#if __name__ == "__main__":
# print "Hello World"
from WorkingWithFiles import Excel2PdfConversion
import jpype
import os.path
asposeapispath = os.path.... | a/")
print "You need to put your Aspose.Cells for Java APIs .jars in this folder:\n"+asposeapispath
#print dataDir
jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.ext.dirs=%s" % asposeapispath)
hw = Excel2PdfConversion(dataDir)
hw.main() |
MSLNZ/msl-equipment | msl/examples/equipment/picotech/picoscope/open_unit_async.py | Python | mit | 1,130 | 0.002655 | """
This example opens the connection in async mode (does not work properly in Python 2.7).
"""
import os
import time
from msl.equipment import (
EquipmentRecord,
ConnectionRecord,
Backend,
)
record = EquipmentRecord(
manufacturer='Pico Technology',
model='5244B', # update for your PicoScope
... | roperties={'open_async': True}, # opening in async mode is done in the properties
)
)
# optional: ensure that the PicoTech DLLs are available on PATH
os.environ['PATH'] += os.pathsep + r'C:\Program Files\Pico Technology\SDK\lib'
t0 = time.time()
scope = record.connect()
while True:
now = time.time()
pro... | :
break
time.sleep(0.02)
print('Took {:.2f} seconds to establish a connection to the PicoScope'.format(time.time()-t0))
# flash the LED light for 5 seconds
scope.flash_led(-1)
time.sleep(5)
|
arriqaaq/hackerrank | Algo- Warmup/cavity-rank.py | Python | apache-2.0 | 508 | 0.037402 | def cavity(l,n):
for i in xrange(1,n-1):
for j in xrange(1,n-1):
if l[i-1][j]!='X' and l[i][j-1]!='X' and l[i+1][j]!='X' and l[i][j+1]!='X' and l[i][j]>l[i-1][j] and l[i][j]>l[i+1][j] and l[i][j]>l[i][j-1] and l[i][j]>l[i][j+1]:
l[i][j]='X'
if __name__ == '__main__':
n = inp... | line = list(raw_input())
p.append(line)
|
cavity(p, n)
for line in p:
print ''.join(line)
|
with-git/tensorflow | tensorflow/python/kernel_tests/variables_test.py | Python | apache-2.0 | 25,860 | 0.014811 | # 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... | (1.1, var1.eval())
def testInitializationOrder(self):
with self.test_session():
rnd = variables.Variable(random_ops.random_uniform([3, 6]), name="rnd")
self.assertEqual("rnd:0", rnd.name)
self.assertEqual([ | 3, 6], rnd.get_shape())
self.assertEqual([3, 6], rnd.get_shape())
self.assertEqual([3, 6], rnd.shape)
dep = variables.Variable(rnd.initialized_value(), name="dep")
self.assertEqual("dep:0", dep.name)
self.assertEqual([3, 6], dep.get_shape())
self.assertEqual([3, 6], dep.get_shape())... |
glennyonemitsu/funkybomb | funkybomb/node.py | Python | apache-2.0 | 5,062 | 0 | from copy import deepcopy
from funkybomb.exceptions import ChildNodeError
class Node:
"""
The building block of tree based templating.
"""
def __init__(self):
"""
Initialize the Node.
"""
self._children_ = []
def __getattr__(self, key):
if key in self.__... | elf._append_(*nodes)
return self
def _wash_nodes_(self, *nodes):
for node in nodes:
yield node
def _append_(self, *nodes):
if len(nodes) == 1 and type(nodes[0]) is list:
nodes = nodes[0]
self._children_.extend(list(self._wash_nodes_(*nodes)))
class Ren... | self._tag_ = None
self._attrs_ = attrs
def __getattr__(self, key):
# required for a bunch of magic methods quirks like with deepcopy()
if key.startswith('__') and key.endswith('__'):
return super().__getattr__(key)
if hide_attribute(key):
return None
... |
mick-d/nipype_source | tools/checkspecs.py | Python | bsd-3-clause | 17,253 | 0.003362 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Attempt to check each interface in nipype
"""
# Stdlib imports
import inspect
import os
import re
import sys
import tempfile
import warnings
from nipype.interfaces.base import BaseInterface
# Functio... | None or sequence of {strings, regexps}
Sequence of strings giving URIs of packages to be excluded
Operates on the package path, starting at (including) the
first dot in the package path, after *package_name* - so,
if *package_name* is ``sphinx``, then ``sphinx.util`` will... | ['\.tests$']
module_skip_patterns : None or sequence
Sequence of strings giving URIs of modules to be excluded
Operates on the module name including preceding URI path,
back to the first dot after *package_name*. For example
``sphinx.util.console`` results in t... |
SMALLplayer/smallplayer-image-creator | storage/.xbmc/addons/script.module.urlresolver/lib/urlresolver/plugins/daclips.py | Python | gpl-2.0 | 3,494 | 0.005724 | """
urlresolver XBMC Addon
Copyright (C) 2011 t0mm0
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.
... | See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from t0mm0.common.net import Net
from urlresolver.plugnplay.interfaces import UrlResolver
from urlresolver.plug... | VOINAGE, BSTRDMKR, ELDORADO
error_logo = os.path.join(common.addon_path, 'resources', 'images', 'redx.png')
class DaclipsResolver(Plugin, UrlResolver, PluginSettings):
implements = [UrlResolver, PluginSettings]
name = "daclips"
def __init__(self):
p = self.get_setting('priority') or 100
s... |
Pinecast/pinecast | assets/admin.py | Python | apache-2.0 | 1,531 | 0.003919 | from django.contrib import admin
from django.utils.safestring import mark_safe
from .models import Asset
from dashboard.models import AssetImportRequest
class AssetImportRequestInline(admin.TabularInline):
model = AssetImportRequest
fk_name = 'asset'
readonly_fields = ('resolved', 'failed', )
extra =... | _url.short_description = 'URL'
def is_superseded(self, instance):
return 'Yes' if instance.is_superseded() else 'No'
is_superseded.short_description = 'Is superseded'
def superseded_by(self, instance):
try:
return Asset.objects.get(supersedes=instance.uuid)
except Excepti... | |
wlach/treeherder | treeherder/log_parser/utils.py | Python | mpl-2.0 | 4,995 | 0.000801 | import logging
import urllib2
import simplejson as json
from django.conf import settings
from treeherder import celery_app
from treeherder.client import (TreeherderArtifactCollection,
TreeherderClient)
from treeherder.credentials.models import Credentials
from treeherder.log_parser.arti... |
credentials = Credentials.objects.get(client_id=settings.ETL_CLIENT_ID)
client = TreeherderClient(
protocol=settings.TREEHERDER_REQUEST_PROTOCOL,
host=settings.TREEHERDER_REQUEST_HOST,
client_id=credentials.client_id,
secret=str(credentials.secret),
)
try:
arti... | l'],
job_guid)
except Exception as e:
client.update_parse_status(project, job_log_url['id'], 'failed')
# unrecoverable http error (doesn't exist or permission denied)
# (apparently this can happen somewhat often with taskcluster if
# the j... |
scienceopen/CVutils | morecvutils/getaviprop.py | Python | mit | 1,520 | 0 | #!/usr/bin/env python
"""
gets basic info about AVI file using OpenCV
input: filename or cv2.Capture
"""
from pathlib import Path
from struct import pack
from typing import Dict, Any
import cv2
def getaviprop(fn: Path) -> Dict[str, Any]:
if isinstance(fn, (str, Path)): # assuming filename
fn = Path(fn).... | cv2.VideoCapture(str(fn))
if v is None:
raise OSError(f'could not read {fn}')
else: # assuming cv2.VideoCapture object
v = fn
if not v.isOpened():
raise OSError(f'cannot read {fn} probable codec issue')
vidparam = {
'nframe': int(v.get(cv2.CAP_PROP_FRAME_COUN... | GHT)),
),
'fps': v.get(cv2.CAP_PROP_FPS),
'codec': fourccint2ascii(int(v.get(cv2.CAP_PROP_FOURCC))),
}
if isinstance(fn, Path):
v.release()
return vidparam
def fourccint2ascii(fourcc_int: int) -> str:
"""
convert fourcc 32-bit integer code to ASCII
"""
ass... |
mmunko/skuskovy-system | manage.py | Python | gpl-3.0 | 259 | 0 | #!/usr/bin/env python3
import os
import sys
if __name__ == "__main__":
os.environ.se | tdefault("DJANGO_SETTINGS_MODULE", "skuskovy_system.settings")
from django.core.management import execute_from_command_line
|
execute_from_command_line(sys.argv)
|
neva-nevan/ConfigPy | ConfigPy-Portable/ConfigPy/cgi-bin/restore.py | Python | mit | 516 | 0 | import os
import shutil
from glob import glob
print 'Content-type:text/html\r\n\r\n'
print '<html>'
| found_pages = glob('archive/*.py')
if found_pages:
path = "/cgi-bin/archive/"
moveto = "/cgi-bin/pages/"
files = os.listdir(path)
files.sort()
for f in files:
src = path+f
dst = moveto+f
shutil.move(src, dst)
print 'All pages restored'
print '<meta http-equiv="refres... | rint '</html>'
# EOF
|
trilliumtransit/oba_rvtd_monitor | oba_rvtd_monitor/problems.py | Python | apache-2.0 | 216 | 0 | from transitfeed im | port TYPE_ERROR, TYPE_WARNING, TYPE_NOTICE
from oba_rvtd_monitor.feedvalidator import LimitPerTypeProblemAccumulator
class MonitoringProblemAccumulator(LimitPerTypeProblemAccumulat | or):
pass
|
shoopio/shoop | shuup_workbench/settings/__init__.py | Python | agpl-3.0 | 1,411 | 0.000709 | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
import os
from django.core.exceptions import ImproperlyConfigured
... | exec")
exec(compiled, local_settings_ns)
if "configure" not in local_settings_ns:
raise ImproperlyConfigured("Error! No configure in local_settings.")
local_configure = local_settings_ns["configure"]
local_configure(set | up)
return setup
globals().update(Setup.configure(configure))
|
scls19fr/python-lms-tools | tests/test_gift.py | Python | mit | 15,672 | 0.003563 | from lms_tools.aiken import AikenQuiz, AikenQuestion
from lms_tools.gift import GiftQuiz, GiftQuestion, GiftDistractor
def test_gift_question_to_string():
q = GiftQuestion("L'appareil servant à mesurer la vitesse du vent au sol s'appelle :", name="0001", comment="question: 1 name: 0001")
q.append_distractor(G... | ose des vents.")
q.append_distr | actor("un baromètre.")
q.append_distractor("un anémomètre.")
q.set_correct_answer(3)
assert not q.is_correct_answer(0)
assert not q.is_correct_answer(1)
assert not q.is_correct_answer(2)
assert q.is_correct_answer(3)
def test_gift_question_to_string_with_escaped_char():
q = GiftQuestion("I... |
artzers/MachineLearning | LinearRegression/SimpleLinearReg.py | Python | mit | 588 | 0.032313 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 18 09:23:01 2017
@author: zhouhang
"""
import numpy as np
from matplotlib import pyplot as plt
X = np.arange(-5.,9.,0.1)
print X
X=np.random.permutation(X)
print X
b=5.
y=0.5 * X ** 2.0 +3. * X + b + np.random.random(X.shape)* 10.
#plt.scatter(... | = np.mat(X).T
X_ = np.hstack((np.square(X_) , X_))
X_ = np.hstack((X_, np.mat(np.ones(len(X))).T))
A=(X_.T*X_).I*X_.T * np.mat(y).T
y_ = X_ * A
plt.hold(True)
plt.plot(X,y,'r.',fillstyle='none')
plt.plot(X,y_,'bo',fillstyle= | 'none')
plt.show() |
vathpela/anaconda | pyanaconda/core/timer.py | Python | gpl-2.0 | 3,465 | 0.001443 | # Timer class for scheduling methods after some time.
#
# Copyright (C) 2018 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.
# Th... | seconds, idle_add, source_remove
class Timer(object):
"""Object to schedule functions and methods to the GLib event loop.
Everything scheduled by Timer is ran on the main thread!
"""
def __init__(self):
self._id = 0
def timeout_sec(self, seconds, callback, *args, **kwargs):
"""S... | ly called until the callback will return False or
`cancel()` is called.
:param seconds: Number of seconds after which the callback will be called.
:type seconds: int
:param callback: Callback which will be called.
:type callback: Function.
:param args: Arguments pa... |
girisagar46/flask_restipy | api/companies/unittest/update_company_test.py | Python | mit | 558 | 0.008961 | from api.lib.testutils import BaseTestCase
import api.companies.unittest
class TestUpdateCompany(BaseTestCase):
def test_update_company(self):
resp = self.app.put('/companies/exponential',
data='{"name": "Exponential.io", "city": "Menlo Park"}',
he... | assert 'Palo Alto' not in resp.data
assert 'Menlo Park' in resp.data
if __name__ == "__mai | n__":
api.companies.unittest.main() |
hazrpg/calibre | src/calibre/customize/profiles.py | Python | gpl-3.0 | 26,074 | 0.011506 | # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
__license__ = 'GPL 3'
__copyright__ = '2009, Kovid Goyal <[email protected]>'
__docformat__ = 'restructuredtext en'
from itertools import izip
from calibre.customize import Plugin as _Plugin
FONT_SIZES = [('xx-small', 1),
... | short_name = 'sony900'
description = _('This profile is intended for the SONY PRS-900.')
screen_size = (584, 978)
class MSReaderInput(InputProfile):
name = 'Microsoft Reader'
short_name = 'msreader'
description = _('This profile is intended for the Microsoft Reader.')
... | 2, 26]
class MobipocketInput(InputProfile):
name = 'Mobipocket Books'
short_name = 'mobipocket'
description = _('This profile is intended for the Mobipocket books.')
# Unfortunately MOBI books are not narrowly targeted, so this information is
# quite likely to be spurious
screen_size ... |
kevroy314/msl-iposition-pipeline | cogrecon/core/cogrecon_globals.py | Python | gpl-3.0 | 991 | 0 | # File globals
data_coordinates_file_suffix = 'position_data_coordinates.txt'
actual_coordinates_file_suffix = 'actual_coordinates.txt'
category_file_suffix = 'categories.txt'
order_file_suffix = 'order.txt'
# Parameter globals
default_z_value = 1.96
default_pipeline_flags = 3
default_dimensions = 2
# Visualization g... | ion = 2
default_animation_ticks = 20
default_visualization_transformed_points_c | olor = 'b'
default_visualization_transformed_points_alpha = 0.5
default_visualization_actual_points_color = 'g'
default_visualization_data_points_color = 'r'
default_visualization_actual_points_size = 50
default_visualization_data_points_size = 50
default_visualization_font_size = 20
default_visualization_accuracies_co... |
bckwltn/SickRage | sickbeard/metadata/mediabrowser.py | Python | gpl-3.0 | 22,239 | 0.002248 | # Author: Nic Wolfe <[email protected]>
# | URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage 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.
#
# SickRage is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more de... |
hryamzik/ansible | lib/ansible/modules/clustering/k8s/_kubernetes.py | Python | gpl-3.0 | 16,555 | 0.001993 | #!/usr/bin/python
# Copyright: (c) 2015, Google Inc. All Rights Reserved.
# 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': ['deprecated'],
'supported_by': 'community'}
DOCUM | ENTATION = '''
---
module: kubernetes
version_added: "2.1"
deprecated:
removed_in: "2.9"
why: This module used the oc command line tool, where as M(k8s_raw) goes over the REST API.
alternative: Use M(k8s_raw) instead.
short_description: Manage Kubernetes resources
description:
- This module can manage Kuberne... |
Jycraft/jycraft-web | servedir.py | Python | bsd-3-clause | 212 | 0.004717 | import Simp | leHTTPServer
import SocketServer
PORT = 8000
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at | port", PORT
httpd.serve_forever() |
joakim-hove/ert | res/simulator/simulation_context.py | Python | gpl-3.0 | 6,507 | 0.000768 | from res.job_queue import JobQueueManager, ForwardModelStatus
from res.enkf import ErtRunContext, EnkfSimulationRunner
from res.enkf.enums import EnkfRunType, HookRuntime
from threading import Thread
from time import sleep
class SimulationContext(object):
def __init__(self, ert, sim_fs, mask, itr, case_data):
... | m_thread.is_alive() or self._queue_manager.isRunning()
def getNumPending(self):
return self._queue_manager.getNumPending()
def getNumRunning(self):
return self._queue_manager.getNumRunning()
def getNumSuccess(self):
return self._queue_manager.getNumSuccess()
def getNumFailed(... | NumFailed()
def getNumWaiting(self):
return self._queue_manager.getNumWaiting()
def didRealizationSucceed(self, iens):
queue_index = self.get_run_args(iens).getQueueIndex()
return self._queue_manager.didJobSucceed(queue_index)
def didRealizationFail(self, iens):
# For the ... |
dims/nova | nova/cmd/api_metadata.py | Python | apache-2.0 | 1,706 | 0 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a ... | .
"""Starter script for Nova Metadata API."""
import sys
from oslo_log import log as logging
from oslo_reports import guru_meditation_report as gmr
from nova.conducto | r import rpcapi as conductor_rpcapi
import nova.conf
from nova import config
from nova import objects
from nova.objects import base as objects_base
from nova import service
from nova import utils
from nova import version
CONF = nova.conf.CONF
CONF.import_opt('enabled_ssl_apis', 'nova.service')
def main():
confi... |
jbaber/bup | lib/bup/hashsplit.py | Python | lgpl-2.1 | 7,757 | 0.002578 | import math, os
from bup import _helpers, helpers
from bup.helpers import sc_page_size
_fmincore = getattr(helpers, 'fmincore', None)
BLOB_MAX = 8192*4 # 8192 is the "typical" blob size for bupsplit
BLOB_READ_SIZE = 1024*1024
MAX_PER_TREE = 256
progress_callback = None
fanout = 16
GIT_MODE_FILE = 0100644
GIT_MODE... | start = i
else:
count = i - start
if in_core:
yield (start, count)
start = None
elif max_region_len and count >= max_region | _len:
yield (start, count)
start = i
if start is not None:
yield (start, len(status_bytes) - start)
def _uncache_ours_upto(fd, offset, first_region, remaining_regions):
"""Uncache the pages of fd indicated by first_region and
remaining_regions that are before offset... |
Feawel/MachineLearningProject | demo_good.py | Python | mit | 3,204 | 0.01623 | # -*- coding: utf-8 -*-
import collections, itertools
import nltk.classify.util, nltk.metrics
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import movie_reviews, stopwords
from nltk.collocations import BigramCollocationFinder
from nltk.metrics import BigramAssocMeasures
from nltk.probability import F... | ts)*3/4
trainfeats = negfeats[:negcutoff] + posfeats[:poscutoff]
testfeats = negfeats[negcutoff:] + posfeats[poscutoff:]
classifier = NaiveBayesClassifier.train(trainfeats)
refsets = collections.defaultdict(set)
testsets = collections.defaultdict(set)
for i, (feats, label) in enumerate(testfeats):
refsets[la... | precision(refsets['pos'], testsets['pos'])
print 'pos recall:', nltk.metrics.recall(refsets['pos'], testsets['pos'])
print 'neg precision:', nltk.metrics.precision(refsets['neg'], testsets['neg'])
print 'neg recall:', nltk.metrics.recall(refsets['neg'], testsets['neg'])
classifier.show_most_informative_features()
... |
meissnert/StarCluster-Plugins | Pysam_0_8_4.py | Python | mit | 905 | 0.022099 | from starcluster.clustersetup import ClusterSetup
from starcluster.logger import log
class PysamInstaller(ClusterSetup):
def run(self, nodes, master, user, user_shell, volumes):
for node in nodes:
log.info("Installing PySam 0.8.4 on %s" % (node.alias))
node.ssh.execute('mkdir -p /opt/software/pysam')
... | /v0.8.4.tar.gz')
node.ssh.execute('mkdir -p /usr/local/Modules/applications/pysam/;touch /usr/local/Modules/applications/pysam/0.8.4')
node.ssh.execute('echo "#%Module" >> /usr/local/Modules/applications/pysam/0.8.4')
node.ssh.execute('echo "set root /opt/software/pysam/pysam-0.8.4" >> /usr/local/Modules/appli... | tions/pysam/0.8.4')
node.ssh.execute('echo -e "prepend-path\tPATH\t\$root" >> /usr/local/Modules/applications/pysam/0.8.4')
|
drzax/databot | app/config.py | Python | mit | 1,253 | 0.003192 | """ file: config.py (syns)
author: Jess Robertson
description: Config file for running Flask app, lifted and lightly modified from
Miguel's 'Flask Web Development' book.
"""
import os
BASEDIR = os.path.abspath(os.path.dirname(__file__))
class Config:
""" Base configuration class
"""
... | = 'measurements'
MEASUREMENT_LIST_MAX_LENGTH = 100
@staticmethod
def init_app(app):
pass
class DevelopmentConfig(Config):
""" Configuration for development environment
"""
DEBUG = True
REDIS_URL = "redis://localhost:6379/0"
USE_UUID_NAMESPACE = False
class TestingConfig(Co... | STING = True
REDIS_URL = "redis://localhost:6379/0"
class ProductionConfig(Config):
""" Configuration for production
"""
REDIS_URL = "redis://localhost:6379/0"
config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'default': Develop... |
android-ia/platform_external_chromium_org | tools/telemetry/telemetry/core/platform/android_device.py | Python | bsd-3-clause | 2,217 | 0.004511 | # Copyright 2014 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 logging
from telemetry.core import util
from telemetry.core.backends import adb_commands
from telemetry.core.platform import device
from telemetry.cor... | resents information for connecting to an android device.
|
Attributes:
device_id: the device's serial string created by adb to uniquely
identify an emulator/device instance. This string can be found by running
'adb devices' command
enable_performance_mode: when this is set to True, android platform will be
set to high performance mode after browser i... |
ddcatgg/dglib | dglib/qt/qt_utils2.py | Python | mit | 27,371 | 0.028785 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import re
import time
import threading
import win32process
import win32con
import functools
from PyQt4 import QtGui, QtCore
import sip
UM_SHOW = win32con.WM_USER + 100
__all__ = ['UM_SHOW', 'TrayMixIn', 'QssMixIn', 'EmitCallMixIn'... | = GET_X_LPARAM(msg.lParam) - self.frameGeometry().x()
y = GET_Y_LPARAM(msg.lParam) - self.frameGeometry().y()
# 判断是否RESIZE区域
is_rszpos = check_resize_pos(self, x, y)
if is_rszpos and self.qss_allow_maximize() and not self.isMaximized():
return True, is_rszpos
# 标题栏区域为扩展后的fraTop区域(包括窗口的... | t(0)
rect.setWidth(self.width())
# 判断标题栏区域时排除标题栏的按钮
if rect.contains(x, y) and \
not isinstance(self.childAt(x, y), QtGui.QPushButton):
# 如果窗口已经最大化,为避免被拖动,必须返回不在非客户区。
# 同时为了实现双击标题栏还原,需要处理 WM_LBUTTONDBLCLK。
if not self.isMaximized():
return True, win32con.HTCAPTION
el... |
RobertoMaurizzi/waliki | waliki/management/commands/moin_migration_cleanup.py | Python | bsd-3-clause | 6,418 | 0.00187 | import re
from waliki.signals import page_saved
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from waliki.models import Page
from django.utils.translation import ugettext_lazy as _
from django.utils.text import get_text_list
try:
from waliki.attachments.models im... | ters:
raw = email(raw)
if 'title | _level' in filters:
raw = title_level(raw)
if 'code' in filters:
if not pandoc:
print('The filter "code" need Pandoc installed in your system. Ignoring')
else:
raw = code(raw)
if 'title' in filters and not p... |
rrwen/google_streetview | google_streetview/helpers.py | Python | mit | 2,418 | 0.016129 | # -*- coding: utf-8 -*-
from itertools import product
import requests
import shutil
def api_list(apiargs):
"""Google Street View Image API results.
Constructs a list of `Google Street View Image API queries <https://developers.google.com/maps/documentation/streetview/>`_
from a dictionary.
Args:
ap... | Dict containing `street view URL parameters <https://developers.google.com/maps/documentation/streetview/intro>`_.
Each parameter can have multiple values if separated by ``;``.
Returns:
A ``listof dict`` containing single query requests per dictionary for Google Street View Image API.
Examples:
... | _streetview for the api and helper module
import google_streetview.api
import google_streetview.helpers
# Create a dictionary with multiple parameters separated by ;
apiargs = {
'location': '46.414382,10.013988;40.720032,-73.988354',
'size': '640x300;640x640',
'hea... |
ArchiFleKs/magnum | magnum/conf/octavia.py | Python | apache-2.0 | 1,970 | 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
# distributed under the... | e',
help=_('Region in | Identity service catalog to use for '
'communication with the OpenStack service.')),
cfg.StrOpt('endpoint_type',
default='publicURL',
help=_('Type of endpoint in Identity service catalog to use '
'for communication with the OpenStack service.... |
mdwint/hype | hype/cloud/amazon.py | Python | mit | 1,420 | 0.010563 | from hype.cloud.cloudprovider import CloudProvider
from boto import ec2
class AmazonEC2(CloudProvider):
def __init__(self, cfg):
CloudProvider.__in | it__(self, cfg)
self.conn = ec2.connect_to_region(str(self.cfg["region"]),
aws_access_key_id=str(self.cfg["access-key-id"]),
aws_secret_access_key=str(self.cfg["secret-access-key"]))
def __del__(self):
self.conn.close()
def get_started_no | des(self):
running = []
for i in self.pending:
try:
i.update()
except boto.exception.EC2ResponseError:
continue
for node in [i for i in self.pending if i.state == "running"]:
self.pending.remove(node)
running.append(node)
self.running.extend(running)
return [i... |
ionomy/ion | test/functional/test_framework/__init__.py | Python | mit | 465 | 0.002151 | # Copyright (c) 2018 The Bitcoin Unlimited developers
# Copyright (c) 2020 The Ion Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.ionlib i | mport init, bin2hex, signTxInput, randombytes, pubkey, spendscript, addrbin, txid, SIGHA | SH_ALL, SIGHASH_NONE, SIGHASH_SINGLE, SIGHASH_ANYONECANPAY, ScriptMachine, ScriptFlags, ScriptError, Error, ION
|
kiyukuta/chainer | chainer/functions/evaluation/r2_score.py | Python | mit | 2,473 | 0 | from chainer import cuda
from chainer import function
from chainer.utils import type_check
class R2_score(function.Function):
def __init__(self, sample_weight, multioutput):
if sample_weight is not None:
raise NotImplementedError()
if multioutput in ['uniform_average', 'raw_values']:
... | pred, true, sample_weight=None, multioutput='uniform_average'):
"""Computes R | ^2(coefficient of determination) regression score function.
Args:
pred(Variable): Variable holding a vector, matrix or tensor of
estimated target values.
true(Variable): Variable holding a vector, matrix or tensor of
correct target values.
sample_weight: This... |
DarkPurpleShadow/ConnectFour | urwid/font.py | Python | bsd-3-clause | 24,937 | 0.008535 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Urwid BigText fonts
# Copyright (C) 2004-2006 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1... | utf8_required = True
out.append(segment + " " * fill)
jl[k] = j
start_col = end_col
dout[c] = (y + fill, out)
c = None
return dout, utf8_required
_all_fonts = []
def get_all_fonts():
"""
Return a list of (font name, font class) tuples.
... | onts.append((name, cls))
class Font(object):
def __init__(self):
assert self.height
assert self.data
self.char = {}
self.canvas = {}
self.utf8_required = False
for gdata in self.data:
self.add_glyphs(gdata)
def add_glyphs(self, gdata):
... |
carvalhomb/tsmells | guess/Tools/jythonc/PythonVisitor.py | Python | gpl-2.0 | 17,603 | 0.003522 | # Copyright (c) Corporation for National Research Initiatives
from org.python.parser import Visitor, SimpleNode
from org.python.parser.PythonGrammarTreeConstants import *
from org.python.parser import SimpleNode
from org.python.compiler import Future
comp_ops = {JJTLESS_CMP : 'lt',
JJ... | eturn s
if s[:2] = | = '__' and s[-2:] != '__' and self.walker.className:
s = "_%s%s" % (self.walker.className, s)
return s
def walk(self, node):
self.suite(node)
def startnode(self, node):
self.walker.setline(node.beginLine)
def suite(self, node):
return self.walker.sui... |
ScreamingUdder/mantid | Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLEnergyTransfer.py | Python | gpl-3.0 | 17,107 | 0.006079 | from __future__ import (absolute_import, division, print_function)
import os
import numpy as np
from mantid import config, mtd, logger
from mantid.kernel import StringListValidator, Direction
from mantid.api import PythonAlgorithm, MultipleFileProperty, FileProperty, \
WorkspaceGroupProperty, FileAction, Progress
... | end :: end bin of workspace to be extracted
"""
CropWorkspace(InputWorkspace=ws, OutputWorkspace=ws_out, XMin=x_start, XMax=x_end)
ScaleX(InputWorkspace=ws_out, OutputWorkspace=ws_out, Factor=-x_start, Operation='Add')
class IndirectILLEnergyTransfer(PythonAlgorithm):
_run_file = None
_map_file... | strument_name = None
_instrument = None
_analyser = None
_reflection = None
_dead_channels = None
_ws = None
_red_ws = None
_psd_int_range = None
_use_map_file = None
_spectrum_axis = None
_efixed = None
def category(self):
return "Workflow\\MIDAS;Workflow\\Inelastic... |
Weasyl/weasyl | weasyl/controllers/moderation.py | Python | apache-2.0 | 6,202 | 0.002904 | import arrow
from pyramid.httpexceptions import HTTPSeeOther
from pyramid.response import Response
from weasyl import define, macro, moderation, note, profile, report
from weasyl.controllers.decorators import moderator_only, token_checked
from weasyl.error import WeasylError
# Moderator control panel functions
@mod... | if not target_userid:
raise WeasylError("userRecordMissing")
submissions = moderation.submissionsbyuser(target_userid) if 's' in form.features else []
characters = moderation.charactersbyuser(target_userid) if 'c' in form.features else []
journals = moderation.journalsbyuser(target_userid) if '... | ions + characters + journals, key=lambda item: item['unixtime'], reverse=True),
], title=form.name + "'s Content"))
@moderator_only
@token_checked
def modcontrol_massaction_(request):
form = request.web_input(action='', name='', submissions=[], characters=[], journals=[])
if form.action.startswith("zap-")... |
atodorov/anaconda | pyanaconda/payload/dnf/payload.py | Python | gpl-2.0 | 71,993 | 0.001389 | # DNF/rpm software payload management.
#
# Copyright (C) 2019 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 ... | _to_failure_limbo, do_transaction, get_df_map, pick_mount_point
from pyanaconda.payload. | dnf.download_progress import DownloadProgress
from pyanaconda.payload.dnf.repomd import RepoMDMetaHash
from pyanaconda.payload.errors import MetadataError, PayloadError, NoSuchGroup, DependencyError, \
PayloadInstallError, PayloadSetupError
from pyanaconda.payload.image import findFirstIsoImage, mountImage, verify_... |
Zhong-Lab-UCSD/Genomic-Interactive-Visualization-Engine | includes/constants_template.py | Python | apache-2.0 | 175 | 0.028571 | _CPB_EDIT_HOST='CPB_EDIT_HOST'
_CPB_EDIT_USER='CPB_EDIT_USE | R'
_CPB_EDIT_PASS='CPB_EDIT_PASS'
_NCBI_URI='https://ftp.ncbi. | nih.gov'
_NCBI_PATH='/gene/DATA/GENE_INFO/Mammalia/'
|
erudit/eruditorg | eruditorg/apps/public/journal/viewmixins.py | Python | gpl-3.0 | 15,146 | 0.002905 | import json
import string
import structlog
from django.db.models import Q
from django.urls import reverse
from django.http import Http404
from django.http.response import HttpResponseRedirect
from django.utils import timezone
from django.utils.crypto import get_random_string
from django.utils.functional import cached_... | if issu | e:
# If the issue is in open access or if it's not embargoed, the access should always be
# granted.
if issue.journal.open_access or not issue.embargoed:
return True
# If the issue is not published, the access should only be granted if a valid
... |
andreimaximov/algorithms | codeforces/mister-b-and-flight-to-the-moon/main.py | Python | mit | 2,960 | 0.000338 | #!/usr/bin/env python3
from collections import defaultdict
DEBUG = False
def main():
if DEBUG:
test()
n = int(input())
paths = cycles(n)
print(len(paths))
for p in paths:
print('%d %s' % (len(p), ' '.join([str(v) for v in p])))
def cycles(n):
"""Builds a set of cycles fo... | return even(n)
else:
return odd(n)
def even(n):
"""Builds a set of cycles that a graph with even vertices."""
assert n % 2 == 0
# Base case for complete graph such that V = {1, 2, 3, 4}.
cycles = [[1, 2, 3], [2, 3, 4], [3, 4, 1], [4, 1, 2]]
for i in range(6, n + 1, 2):
... | s += [[a, 1, b], [a, 2, b], [a, 1, b, 2]]
# Similar to odd(...) as we are left with 2n - 2 edges to use
# connected to i - 4 of the vertices V' = {3 ... i - 2}. Notice that
# |V'| is even so we can apply the same strategy as in odd(...).
for k in range(3, i - 1, 2):
c, d = k... |
Smarties89/Jockle | jockle.py | Python | mit | 8,737 | 0.00412 | #!/bin/python
# coding: utf-8
# Standard libraries
import logging
from sys import argv
from urlparse import urljoin
from zipfile import ZipFile
from flask import render_template, Flask, request, redirect, Response, make_response
from fest.decorators import requireformdata
import requests
from statuscodes import statu... | low
# http://stackoverflow.com/questions/10999990/get-raw-post-body-in-python-flask-regardless-of-content-type-header
class WSGICopyBody(object):
def __init__(self, app | lication):
self.application = application
def __call__(self, environ, start_response):
from cStringIO import StringIO
length = environ.get('CONTENT_LENGTH', '0')
length = 0 if length == '' else int(length)
body = environ['wsgi.input'].read(length)
environ['body_cop... |
thedanotto/google-maps-urlerator | manage.py | Python | mit | 264 | 0.003788 | #!/usr/bin/ | env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "google_maps_urlerator.setti | ngs")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
ftrautsch/testEvolution | parser/resultparser.py | Python | apache-2.0 | 2,937 | 0.012938 | '''
Created on 03.02.2016
@author: fabian
'''
import os
import collections
import csv
class ResultParser(object):
'''
classdocs
'''
def __init__(self, resultFolder):
'''
Constructor
'''
self.resultFolder = resultFolder
def getAllCommitsWithJacocoErro... | lf.getAllCommitsWithPitErrors()
result = {}
for commit in self.getImmediateSubdirectories(self.resultFolder):
if(not os.listdir(self.resultFolder+"/"+commit) == []):
parts = | commit.split("-")
result[int(parts[0])] = {'hash': parts[1],'jacocoError' : (commit in jacocoErrors), 'pitError' : (commit in pitErrors)}
sortedResults = collections.OrderedDict(sorted(result.items()))
writer = csv.writer(open(outputFile, 'w'))
writer.w... |
yrunts/python-for-qa | 3-python-intermediate/examples/file.py | Python | cc0-1.0 | 148 | 0 |
f = open('test_content.txt', | 'r')
print(f.read())
f.close()
# using context manager |
with open('test_content.txt', 'r') as f:
print(f.read())
|
ARMmbed/yotta_osx_installer | workspace/lib/python2.7/site-packages/requests/packages/urllib3/util/connection.py | Python | apache-2.0 | 3,341 | 0 | import socket
try:
from select import poll, POLLIN
except ImportError: # `poll` doesn't exist on OSX and other platforms
poll = False
try:
from select import select
except ImportError: # `select` doesn't exist on AppEngine.
select = False
def is_connection_dropped(conn): # Platform-... | xcept socket.error as e:
err = e
if sock is not None:
sock.close()
sock = None
if err is not None:
raise err
raise socket.error("getaddrinfo returns an empty list")
def _set_socket_options(sock, options):
if options is None:
return
... | in options:
sock.setsockopt(*opt)
|
lxki/pjsip | tests/pjsua/scripts-sendto/331_srtp_prefer_rtp_avp.py | Python | gpl-2.0 | 827 | 0.020556 | # $Id: 331_srtp_prefer_rtp_avp.py 2081 2008-06-27 21:59:15Z bennylp $
import inc_sip as sip
import inc_sdp as sdp
# W | hen SRTP is NOT enabled in pjsua, it should prefer to use
# RTP/AVP media line if there are multiple m=audio lines
sdp = \
"""
v=0
o=- 0 0 IN IP4 127.0.0.1
s=-
c=IN IP4 127.0.0.1
t=0 0
m=audio 5000 RTP/SAVP 0
a=crypto:1 aes_cm_128_hmac_sha1_80 inline:WnD7c1ksDGs+dIefCEo8omPg4uO8DYIinNGL5yxQ
m=audio 4000 RTP/AVP 0
"""
... | er 200 --use-srtp 0"
extra_headers = ""
include = ["Content-Type: application/sdp", # response must include SDP
"m=audio 0 RTP/SAVP[\\s\\S]+m=audio [1-9]+[0-9]* RTP/AVP"
]
exclude = ["a=crypto"]
sendto_cfg = sip.SendtoCfg("Prefer RTP/SAVP", pjsua_args, sdp, 200,
extra_headers=extra_headers,
resp_in... |
peterayeni/rapidsms | rapidsms/contrib/handlers/handlers/keyword.py | Python | bsd-3-clause | 4,432 | 0 | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import re
from django.core.exceptions import ObjectDoesNotExist
from ..exceptions import HandlerError
from .base import BaseHandler
class KeywordHandler(BaseHandler):
"""
This handler type can be subclassed to create simple keyword-based
handlers. Whe... | # it along to the handle method. the instance can always find
# the original text via self.msg if it really needs it.
text = match.group(1)
if text is not None and text.strip() != "":
try:
inst.handle(text)
# special case: if an object was expected bu... | # catching the exception within the ``handle`` method.
except ObjectDoesNotExist as err:
return inst.respond_error(
str(err))
# another special case: if something was miscast to an int
# (it was probably a string from the ``text``), ret... |
pytrainer/pytrainer | pytrainer/extension.py | Python | gpl-2.0 | 5,489 | 0.032246 | # -*- coding: utf-8 -*-
#Copyright (C) Fiz Vazquez [email protected]
#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.
#T... | e("pytrainer-extension","helpfile")
type = info.getValue("pytrainer-extension","type")
if not os.path.isfile(extensiondir+"/"+code+"/conf.xml"):
status = 0
else:
info = XMLParser(extensiondir+"/"+code+"/conf.xml")
status = info.getValue("pytrainer-extension","status")
#print name,description,status,h... | info = XMLParser(pathExtension+"/conf.xml")
code = info.getValue("pytrainer-extension","extensioncode")
extensiondir = self.pytrainer_main.profile.extensiondir
params = {}
if not os.path.isfile(extensiondir+"/"+code+"/conf.xml"):
prefs = info.getAllValues("conf-values")
prefs.append(("status","0"))
for... |
ddalex/python-prompt-toolkit | examples/multi-column-autocompletion.py | Python | bsd-3-clause | 955 | 0.002094 | #!/usr/bin/env python
"""
Similar to the autocompletion example. But display all the completions in multiple columns.
"""
from __future__ import unicode_literals
from prompt_toolkit.contrib.completers import WordCompleter
from prompt_toolkit.shortcuts import get_input
animal_completer = WordCompleter([
'alligato... | 'butterfly',
'cat',
'chicken',
'crocodile',
'dinosaur',
'dog',
'dolphine',
'dove',
'duck',
'eagle',
'elephant',
'fish',
'goat',
'gorilla',
'kangoroo',
'leopard',
'lion',
'mouse' | ,
'rabbit',
'rat',
'snake',
'spider',
'turkey',
'turtle',
], ignore_case=True)
def main():
text = get_input('Give some animals: ', completer=animal_completer, display_completions_in_columns=True)
print('You said: %s' % text)
if __name__ == '__main__':
main()
|
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247971765/PyQt4/QtGui/QPicture.py | Python | gpl-2.0 | 3,567 | 0.00841 | # encoding: utf-8
# module PyQt4.QtGui
# from /usr/lib/python3/dist-packages/PyQt4/QtGui.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
# no doc
# imports
import PyQt4.QtCore as __PyQt4_QtCore
from .QPaintDevice import QPaintDevice
class QPicture(QPaintDevice):
"""
QPicture(int formatVersion=-1)
Q... | ture.isDetached() -> bool """
return False
def isNull(self): # real sign | ature unknown; restored from __doc__
""" QPicture.isNull() -> bool """
return False
def load(self, *__args): # real signature unknown; restored from __doc__ with multiple overloads
"""
QPicture.load(QIODevice, str format=None) -> bool
QPicture.load(str, str format=None) -> b... |
takeshineshiro/python-novaclient | novaclient/tests/functional/test_keypairs.py | Python | apache-2.0 | 4,555 | 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... | ile
def test_create_keypair(self):
key_name = self._create_keypair()
keypair = self._show_keypair(key_name)
self.assertIn(key_name, keypair)
return keypair
def _test_import_keypair(self, fingerprint, **create_kwargs):
key_name = self._create_keypair(**create_kwargs)
... | self.assertIn(key_name, keypair)
self.assertIn(fingerprint, keypair)
return keypair
def test_import_keypair(self):
pub_key, fingerprint = fake_crypto.get_ssh_pub_key_and_fingerprint()
pub_key_file = self._create_public_key_file(pub_key)
self._test_import_keypair(fin... |
RobinQuetin/CAIRIS-web | cairis/cairis/WeaknessTreatmentDialog.py | Python | apache-2.0 | 3,242 | 0.024985 | # 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... | indWindowById(armid.WEAKNESSTREATMENT_COMBOREQGOAL_ID)
assetC | trl = self.FindWindowById(armid.WEAKNESSTREATMENT_COMBOASSET_ID)
effCtrl = self.FindWindowById(armid.WEAKNESSTREATMENT_COMBOEFFECTIVENESS_ID)
ratCtrl = self.FindWindowById(armid.WEAKNESSTREATMENT_TEXTRATIONALE_ID)
self.theRequirementName = reqCtrl.GetValue()
self.theAssetName = assetCtrl.GetValue()
... |
siosio/intellij-community | python/testData/quickFixes/PyAddImportQuickFixTest/combinedElementOrdering/first/second/__init__.py | Python | apache-2.0 | 20 | 0.05 | f | rom bar import | path |
andymckay/django | django/core/management/base.py | Python | bsd-3-clause | 13,731 | 0.001311 | """
Base classes for writing management commands (named commands which can
be executed through ``django-admin.py`` or ``manage.py``).
"""
import os
import sys
from optparse import make_option, OptionParser
import traceback
import django
from django.core.exceptions import ImproperlyConfigured
from django.core.managem... | nd.
"""
pass
def handle_default_options(options):
"""
Include any default options that all commands should accept here
so that ManagementUtility can handle them before searching for
user commands.
"""
if options.settings:
| os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
if options.pythonpath:
sys.path.insert(0, options.pythonpath)
class BaseCommand(object):
"""
The base class from which all management commands ultimately
derive.
Use this class if you want access to all of the mechanisms whic... |
raphaelrpl/portal | backend/appengine/routes/profiles/new.py | Python | mit | 968 | 0.002066 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from config.template_middleware import TemplateResponse
from gaebusiness.business import CommandExecutionException
from gaepermission.decorator import login_required
from tekton import router
from gaecookie.decorator import no_csrf
from pr... | ter.to_path(save)}, 'profiles/profile_form.html')
@login_required
def save(**profile_properties):
cmd = profile_facade.save_profile_cmd(**profile_properties)
try:
cmd()
except CommandExecutionException:
context = {'errors': cmd.errors,
' | profile': profile_properties}
return TemplateResponse(context, 'profiles/profile_form.html')
return RedirectResponse(router.to_path(profiles))
|
aoakeson/home-assistant | homeassistant/components/sensor/systemmonitor.py | Python | mit | 5,755 | 0.000174 | """
Support for monitoring the local system..
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.systemmonitor/
"""
import logging
import homeassistant.util.dt as dt_util
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.helpers.... | psutil.virtual_memory().available) /
1024**2, 1)
elif self.type == 'memory_free':
self._state = round(psutil.virtual_memory().available / 1024**2, 1)
elif self.type == 'swap_use_percent':
self._state = psutil.swap_memo... | elf.type == 'swap_use':
self._state = round(psutil.swap_memory().used / 1024**3, 1)
elif self.type == 'swap_free':
self._state = round(psutil.swap_memory().free / 1024**3, 1)
elif self.type == 'processor_use':
self._state = round(psutil.cpu_percent(interval=None))
... |
lowitty/selenium | com/ericsson/xn/commons/base_clint_for_selenium.py | Python | mit | 2,301 | 0.005215 | #! /usr/bin/python
# -*- coding: utf-8 -*-
# from datetime import datetime
from multiprocessing.managers import BaseManager
BaseManager.register('platform_info')
def platform_info(ip, port, passwd):
mgr = start_session(ip, port, passwd)
return mgr.platform_info()._getvalue()
BaseManager.register('server_ti... | auth_info=None, nbi_raw='/opt/LINBI/TestTool_CMCC_N13A/bin/raw_catch.log', t_port=None):
mgr = start_session(ip, port, passwd)
return mgr.send_trap_nbi(ne_type, alarm, host, auth_info, nbi_raw, t_port)._getvalue()
BaseManager.register('')
def get_nodeid_by_nename(ip, port, password, ne_name):
mgr = sta... | start_session(ip, port, password)
return mgr.is_alarm_id_unic(id)._getvalue()
BaseManager.register('is_notification_id_unic')
def is_notification_id_unic(ip, port, password, id):
mgr = start_session(ip, port, password)
return mgr.is_notification_id_unic(id)._getvalue()
def start_session(ip, port, pas... |
emvecchi/mss | src/utils/crowdflower/create_csv.py | Python | apache-2.0 | 1,241 | 0.033038 | import sys, glob, os
"""
This program creates a csv file where each row contains an
image and one of its associated tag <"image_path, tag">.
An image has to be in 'jpg' format, a lab | el in 'txt' format.
Usage:
@param1: dataset directory
@param2: url base where images and labels have to be located
@param3: output directory
"""
def write_csv(dataset_path, url_path, out_path):
info = {}
for file_path in glob.glob(os.path.join(dataset_path, 'labels/*')):
file = open(file_path, 'r')... | :
label = info[image_name]
else:
label = []
for tag in file:
label.append(tag)
info[image_name] = label
data = []
for image in info:
for tag in info[image]:
image_file_name = url_path + 'images/' + image
data.append((str(image_file_name), str(tag)))
csv_file = open(out_path, 'w'... |
polysquare/polysquare-travis-container | container-setup.py | Python | mit | 1,494 | 0 | # /container-setup.py
#
# Initial setup script specific to polysquare-travis-container. Creates
# a cache dir in the container and sets the
# _POLYSQUARE_TRAVIS_CONTAINER_TEST_CACHE_DIR environment variable
# to point to it.
#
# See /LICENCE.md for Copyright information
"""Initial setup script specific to polysquare-ci... | cache_dir_key = "_POLYSQUARE_TRAVIS_CONTAINER_TEST_CACHE_DIR"
shell.overwrite_environment_variable(cache_dir_key, cache_dir)
cont.fetch_and_import("setup/pyth | on/setup.py").run(cont, util, shell, argv)
config_python = "setup/project/configure_python.py"
py_ver = util.language_version("python3")
py_cont = cont.fetch_and_import(config_python).get(cont,
util,
... |
marcoceppi/juju-bundlelib | jujubundlelib/changeset.py | Python | lgpl-3.0 | 9,892 | 0.000101 | # Copyright 2015 Canonical Ltd.
# Licensed under the AGPLv3, see LICENCE file for details.
from __future__ import unicode_literals
import copy
import itertools
import models
import utils
class ChangeSet(object):
"""Hold the state for parser handlers.
Also expose methods to send and receive changes (usuall... | def __init__(self, bundle):
self.bundle = bundle
self._changeset = []
self._counter = itertools.count()
def send(self, change):
"""Store a change | in this change set."""
self._changeset.append(change)
def recv(self):
"""Return all the collected changes.
Changes are stored using self.send().
"""
changeset = self._changeset
self._changeset = []
return changeset
def next_action(self):
"""Retu... |
anqxyr/pyscp | pyscp/snapshot.py | Python | mit | 11,400 | 0 | #!/usr/bin/env python3
"""
Snapshot access classes.
This module contains the classes that facilitate information extraction
and communication with the sqlite Snapshots.
"""
###############################################################################
# Module Imports
###############################################... | ost(
p.id, p.title, p.content, p.user.name,
str(p.time), p._data['parent'])
for p i | n query]
class Wiki(core.Wiki):
"""Snapshot of a Wikidot website."""
Page = Page
Thread = Thread
# Tautology = Tautology
###########################################################################
# Special Methods
#########################################################################... |
jaywink/shoop | shoop_tests/admin/test_qs.py | Python | agpl-3.0 | 691 | 0.001447 | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 lice | nse found in the
# LICENSE file in the root directory of this source tree.
from shoop.admin.utils.urls import manipulate_query_string
def test_qs_manipulation():
url = "http://example.com/"
assert manipulate_query_string(url) == url # Noop works
hello_url = manipulate_query_string(url, q="hello", w="well... | uery_string(hello_url, q=None) # Removal works
assert "w=wello" in unhello_url
|
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractWataboutMe.py | Python | bsd-3-clause | 597 | 0.030151 | def extractWataboutMe(item): |
'''
Parser for 'watabout.me'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('Ben-To', | 'Ben-To', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl... |
Tianyi94/EC601Project_Somatic-Parkour-Game-based-on-OpenCV | Old Code/ControlPart/FaceDetection+BackgroundReduction.py | Python | mit | 723 | 0.045643 | import numpy as np
import cv2
from matplotlib import pyplot as plt
face_ | cascade = cv2.CascadeClassifier('/home/tianyiz/user/601project/c/haarcascade_frontalface_alt.xml')
cap = cv2.VideoCapture(0)
fgbg = cv2.createBackgroundSubtractorMOG2()
while 1:
ret, img = cap.read()
gray = cv2.cvtColor(img, | cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
#Background reduce
fgmask = fgbg.apply(img)
cv2.imshow('Reduce',fgmask)
for (x,y,w,h) in faces:
print(x,y,w,h)
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
cv2.imsh... |
davidhalter/depl | test/deploy/test_fab.py | Python | mit | 709 | 0 | import pytest
from ..helpers import config_file, main_run
@config_file('''
deploy:
- fab: |
run('touch depl_fab')
sudo("rm depl_fab")
''')
def test_no_error(tmpdir):
main_run(['depl', 'deploy', 'localhost'])
@config_file('''
deploy:
- fab: |
sudo("rm... | with warn_only():
result = sudo("rm depl_fab")
assert result.failed
''')
def test_raise_error_but_quiet(tmpdir):
main_run(['depl', 'deploy', | 'localhost'])
|
madvas/gae-angular-material-starter | main/task.py | Python | mit | 3,654 | 0.004926 | # coding: utf-8
"""
Module for created app engine deferred tasks. Mostly sending emails
"""
import logging
import flask
from google.appengine.api import mail #pylint: disable=import-error
from google.appengine.ext import deferred #pylint: disable=import-er | ror
import config
import util
def send_mail_notification(subject, body, receiver=None, **kwargs):
"""Function for sending email via GAE's mail and deferred module
Args:
subject (string): Email subject
body (string): | Email body
receiver (string, optional): Email receiver, if omitted admin will send email himself
**kwargs: Arbitrary keyword arguments.
"""
if not config.CONFIG_DB.feedback_email:
return
brand_name = config.CONFIG_DB.brand_name
sender = '%s <%s>' % (brand_name, config.CONFIG_... |
wavefrontHQ/python-client | wavefront_api_client/models/integration_dashboard.py | Python | apache-2.0 | 7,471 | 0.000134 | # coding: utf-8
"""
Wavefront REST API Documentation
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the W... | vefront.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from wavefront_api_client.configuration import Configuration
class IntegrationDashboard(object):
"""NOTE: This class is auto generated by the swagger code generator program.
... | y is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'dashboard_min_obj': 'DashboardMin',
'dashboard_obj': 'Dashboard',
... |
compas-dev/compas | src/compas_ghpython/artists/artist.py | Python | mit | 300 | 0 | from __future__ import print_function
from __fu | ture__ import absolute_import
from __future__ import division
from compas.artists import Artist
class GHArtist(Artist):
"""Base class for all GH artists.
"""
def __init__(self, **kwargs):
super(GHArtist, self).__init__( | **kwargs)
|
SuperDARNCanada/placeholderOS | experiments/testing_archive/test_beamforming_16_boxes.py | Python | gpl-3.0 | 7,055 | 0.009639 | #!/usr/bin/python
import os
import sys
sys.path.append(os.environ['BOREALISPATH'])
# write an experiment that creates a new control program.
from experiment_prototype.experiment_prototype import ExperimentPrototype
class OneBox(ExperimentPrototype):
def __init__(self):
cpid = 100000000
super(On... | 6, 5, 4, 3, 2, 1, 0],
# "scanboundflag": True, # there is a scan boundary
# "scanbound": 60000, # ms
# "clrfrqflag": True, # search for clear frequency before transmitting
# "clrfrqrange": [13100, 13200], # frequency range for clear frequency search, kHz
# ... | longer necessary
# # as they will be set by the frequency chosen from the range.
# "xcf": True, # cross-correlation processing
# "acfint": True, # interferometer acfs
# }, interfacing_dict={0: 'PULSE'})
# Other things you can change if you wish. You may want to dis... |
SeanXP/Nao-Robot | python/language/set_Chinese.py | Python | gpl-2.0 | 1,345 | 0.018311 | #! /usr/bin/env python
#-*- coding: utf-8 -*-
#################################################################
# Copyright (C) 2015 Sean Guo. All rights reserved.
#
# > File Name: < set_Chinese.py >
# > Author: < Sean Guo >
# > Mail: < iseanxp+code@gmail | .com >
# > Created Tim | e: < 2015/03/30 >
# > Last Changed:
# > Description:
#################################################################
from naoqi import ALProxy
robot_ip = "192.168.1.100"
robot_port = 9559 # default port : 9559
tts = ALProxy("ALTextToSpeech", robot_ip, robot_port)
#tts.setLanguage("English")
#tts.say("Hello, ... |
zouyapeng/horizon-newtouch | openstack_dashboard/dashboards/admin/instances/forms.py | Python | apache-2.0 | 3,554 | 0.000281 | # Copyright 2013 Kylin OS, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... | block_migration=block_migration,
disk_over_commit=disk_over_commit)
msg = _('The instance is preparing the live migration '
'to host "%s".') % data['host']
messages.success(request, msg)
return True
... | ost "%s".') % data['host']
redirect = reverse('horizon:admin:instances:index')
exceptions.handle(request, msg, redirect=redirect)
|
SteelToeOSS/Samples | pysteel/fs.py | Python | apache-2.0 | 296 | 0 | import os
import | shutil
import stat
def deltree(dirpath):
"""
:type dirpath: str
"""
if os.path.exists(dirpath):
def remove_readonly(func, path, _):
os.chmod(path, stat.S_IWRITE)
func(path) |
shutil.rmtree(dirpath, onerror=remove_readonly)
|
mvkirk/appengine-lumx-skeleton | app/server/main.py | Python | apache-2.0 | 766 | 0.002611 | import logging
| import os
import jinja2
import webapp2
from google.appengine.ext.webapp.util import run_wsgi_app
from server.service import Service
jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(os.path.dirname(__file__))),
variable_start_strin | g='[[',
variable_end_string=']]'
)
class MainHandler(webapp2.RequestHandler):
def get(self):
template = jinja_environment.get_template('/client/front/index.html')
self.response.out.write(template.render({}))
application = webapp2.WSGIApplication([
('/', MainHandler),
('/service.*', Se... |
little-dude/monolithe | tests/base/sdk/python/tdldk/v1_0/fetchers/galists_fetcher.py | Python | bsd-3-clause | 598 | 0.003344 | # -*- coding: | utf-8 -*-
#
# __code_header example
# put your license header here
# it will be added to all the generated files
#
from bambou import NURESTFetcher
class GAListsFetcher(NURESTFetcher):
""" Represents a GALists fetcher
Notes:
This fetcher enables to | fetch GAList objects.
See:
bambou.NURESTFetcher
"""
@classmethod
def managed_class(cls):
""" Return GAList class that is managed.
Returns:
.GAList: the managed class
"""
from .. import GAList
return GAList
|
John-Lin/SDN-hands-on | examples/simple_switch/simple_switch.py | Python | mit | 3,589 | 0 | from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet
class SimpleSwitch(app_ma... | actions)]
if buffer_id:
mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id,
priority=priority, match=match,
instructions=inst)
else:
mod = parser.OFPFlowMod(datapath=... | |
clsb/miles | doc/conf.py | Python | mit | 9,457 | 0.006027 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# miles documentation build configuration file, created by
# sphinx-quickstart on Sun Jul 17 | 17:10:29 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
... | If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -------------... |
capstone-rust/capstone-rs | capstone-sys/capstone/suite/synctools/asmwriter.py | Python | mit | 33,268 | 0.002345 | #!/usr/bin/python
# convert LLVM GenAsmWriter.inc for Capstone disassembler.
# by Nguyen Anh Quynh, 2019
import sys
if len(sys.argv) == 1:
print("Syntax: %s <GenAsmWriter.inc> <Output-GenAsmWriter.inc> <Output-GenRegisterName.inc> <arch>" %sys.argv[0])
sys.exit(1)
arch = sys.argv[4]
f = open(sys.argv[1])
li... | # extract param between text()
# MRI.getRegClass(AArch64::GPR32spRegClassID).contains(MI->getOperand(1).getReg( | )))
def extract_paren(line, text):
i = line.index(text)
return line[line.index('(', i)+1 : line.index(')', i)]
# extract text between <>
# printSVERegOp<'q'>
def extract_brackets(line):
if '<' in line:
return line[line.index('<')+1 : line.index('>')]
else:
return ''
# delete text betw... |
sthenc/nc_packer | tools/chime_scorer.py | Python | mit | 13,171 | 0.037279 | #!/usr/bin/python
import numpy as np
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('inset', choices=['test', 'val', 'train', 'all'])
parser.add_argument('recog', choices=['clean', 'reverb', 'noisy', 'retrain', 'all'])
phase_group = parser.add_mutually_exclusive_group(required = False)
pha... | ging.info("Copy netname: \n{}\n".format(tmp_output))
# feature generate phase
testfe | at = "output_test/"
valfeat = "output_val/"
trainfeat = "output_train/"
testfeatnorm = "output_norm_test/"
valfeatnorm = "output_norm_val/"
trainfeatnorm = "output_norm_train/"
testnc = "../../test_reverb_norm.nc"
valnc = "../../val_reverb_norm.nc"
trainnc = "../../train_reverb_norm.nc"
# for dubugging
#testnc... |
silly-wacky-3-town-toon/SOURCE-COD | toontown/estate/GardenDropGame.py | Python | apache-2.0 | 20,215 | 0.002721 | from panda3d.core import *
from panda3d.direct import *
from toontown.toonbase.ToonBaseGlobal import *
from direct.gui.DirectGui import *
from panda3d.core import *
from panda3d.direct import *
from direct.gui.DirectScrolledList import *
from direct.distributed.ClockDelta import *
from toontown.toontowngui import TTDia... | gotNeighbor = 1
elif se | lf.testGridfull(self.getValidGrid(cellX - 1, cellZ)):
gotNeighbor = 1
elif self.testGridfull(self.getValidGrid(cellX + 1, cellZ)):
gotNeighbor = 1
elif self.testGridfull(self.getValidGrid(cellX, cellZ + 1)):
gotNeighbor = 1
elif self.testGridfull(self.getValid... |
honeynet/beeswarm | beeswarm/drones/honeypot/tests/test_smtp.py | Python | gpl-3.0 | 7,214 | 0.003327 | # Copyright (C) 2012 Aniket Panse <[email protected]
#
# 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.
# This prog... | er': 'Test'},
'users': {'someguy': 'test'}}
cap = smtp.smtp(options, self.work_dir)
srv = StreamServer(('0.0.0.0', | 0), cap.handle_session)
srv.start()
smtp_ = smtplib.SMTP('127.0.0.1', srv.server_port, local_hostname='localhost', timeout=15)
arg = '\0%s\0%s' % ('test', 'test')
code, resp = smtp_.docmd('AUTH', 'PLAIN ' + base64.b64encode(arg))
self.assertEqual(code, 535)
srv.stop()
... |
djanderson/equery | pym/gentoolkit/eshowkw/keywords_header.py | Python | gpl-2.0 | 3,555 | 0.029817 | # vim:fileencoding=utf-8
# Copyright 2001-2010 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
__all__ = ['keywords_header']
from portage import settings as ports
from portage.output import colorize
from display_pretty import colorize_string
from display_pretty import align_string... | used as separators for further split so we wont loose spaces and coloring
return ['%'.join(align_string(x, align, length)) for x in additional]
def __prepareExtra(self, extra, align, length):
content = []
content.append(''.ljust(length, '-'))
content.extend(self.__formatAdditional(extra, align, length))
ret... | _prepareResult(self, keywords, additional, align, length):
"""Parse keywords and additional fields into one list with proper separators"""
content = []
content.append(''.ljust(length, '-'))
content.extend(self.__formatKeywords(keywords, align, length))
content.append(''.ljust(length, '-'))
content.extend(se... |
twitter/pants | src/python/pants/backend/python/tasks/setup_py.py | Python | apache-2.0 | 30,450 | 0.010213 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import inspect
import io
import itertools
import os
import shutil
import textwrap
from ab... | ator to aggregate
# un-exported non-3rdparty interior nodes as needed. It seems like the latter is preferable since
# it can be used with a BUILD graph validator requiring completely exported subgraphs to enforce the
# former as a matter of local repo policy.
class ExportedTargetDependencyCalculator(AbstractClass):
... | ernal targets that are also exported and "own" these internal transitive library deps.
In other words, exported targets generally can have reduced dependency sets and an
`ExportedTargetDependencyCalculator` can calculate these reduced dependency sets.
To use an `ExportedTargetDependencyCalculator` a subclass mus... |
jcu-eresearch/TDH-rich-data-capture | jcudc24provisioning/controllers/ca_schema_scripts.py | Python | bsd-3-clause | 11,701 | 0.005811 | """
alters the ColanderAlchemy generated schema to add additional display options including:
- Removing the top level title (ColanderAlchemy outputs a schema with a name at the top of every form).
- Removing items not on the specified page (based on attributes on schema nodes).
- Allowing form elements to be requir... | ema.children:
node.name = schema.name + ":" + node.name
if | isinstance(node.typ, colander.Sequence):
_prevent_duplicate_fields(node.children[0])
elif len(node.children) > 0:
node = _prevent_duplicate_fields(node)
return schema
@cache_region('long_term')
def _force_required(schema):
"""
Make fields required (ColanderAlchemy r... |
hunch/hunch-gift-app | django/conf/locale/lv/formats.py | Python | mit | 1,226 | 0.004898 | # -*- encoding: utf-8 -*-
# This file is distributed under the same license as the Django package.
#
DATE_FORMAT = r'Y. \g\a\d\a j. F'
TIME_FORMAT = 'H:i:s'
DATETIME_FORMAT = r'Y. \g\a\d\a j. F, H:i:s'
YEAR_MONTH_FORMAT = r'Y. \g. F'
MONTH_DAY_FORMAT = 'j. F'
SHORT_DATE_FORMAT = r'j.m.Y'
SHORT_DATETIME_FORMA... | INP | UT_FORMATS = (
'%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06'
)
TIME_INPUT_FORMATS = (
'%H:%M:%S', # '14:30:59'
'%H:%M', # '14:30'
'%H.%M.%S', # '14.30.59'
'%H.%M', # '14.30'
)
DATETIME_INPUT_FORMATS = (
'%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30... |
tobegit3hub/cinder_docker | cinder/tests/unit/api/contrib/test_services.py | Python | apache-2.0 | 24,584 | 0 | # Copyright 2012 IBM Corp.
# 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 app... |
from cinder import test
from cinder.tests.unit.api import fakes
fake_services_list = [
{'binary': 'cinder-scheduler',
'host': 'host1',
'availability_zone': 'cinder',
'id': 1,
'disabled': True,
'updated_at': datetime.datetime(2012, 10, 29, 13, 42, 2),
'created_at' | : datetime.datetime(2012, 9, 18, 2, 46, 27),
'disabled_reason': 'test1',
'modified_at': ''},
{'binary': 'cinder-volume',
'host': 'host1',
'availability_zone': 'cinder',
'id': 2,
'disabled': True,
'updated_at': datetime.datetime(2012, 10, 29, 13, 42, 5),
'created_at': datetime... |
plotly/plotly.py | packages/python/plotly/plotly/validators/layout/mapbox/layer/line/_dash.py | Python | mit | 421 | 0.002375 | import _plotly_utils.basevalidators
class DashValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(
self, plotly_name="dash", parent_name="layout.mapbox.layer.line" | , **kwargs
):
super(DashValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "plot" | ),
**kwargs
)
|
elbeardmorez/quodlibet | quodlibet/quodlibet/ext/events/inhibit.py | Python | gpl-2.0 | 2,526 | 0 | # -*- coding: utf-8 -*-
# Copyright 2011 Christoph Reiter <[email protected]>
#
# 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) an... | vel_xid())
flags = dbus.UInt32(InhibitFlags.IDLE)
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
self.__cookie = iface.Inhibit(
self.APPLICATION_ID, xid, s... | flags)
except dbus.DBusException:
pass
def plugin_on_paused(self):
if self.__cookie is None:
return
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)... |
KennethNielsen/SoCo | soco/cache.py | Python | mit | 7,367 | 0 | # -*- coding: utf-8 -*-
# pylint: disable=not-context-manager,useless-object-inheritance
# NOTE: The pylint not-content-manager warning is disabled pending the fix of
# a bug in pylint https://github.com/PyCQA/pylint/issues/782
# NOTE: useless-object-inheritance needed for Python 2.x compatability
"""This module con... | new_cls = TimedCache
else:
new_cls = NullCache
instance = super(Cache | , cls).__new__(new_cls)
instance.__init__(*args, **kwargs)
return instance
|
metabrainz/picard | picard/ui/filebrowser.py | Python | gpl-2.0 | 9,720 | 0.001955 | # -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2006-2008 Lukáš Lalinský
# Copyright (C) 2008 Hendrik van Antwerpen
# Copyright (C) 2008-2009, 2019-2022 Philipp Wolfer
# Copyright (C) 2011 Andrew Barnert
# Copyright (C) 2012-2013 Michael Wiencek
# Copyright (C) 2013 Wieland ... | index = self.indexAt(event.pos())
if index.isValid():
self.selectionModel().setCurrentIndex(index, QtCore.QItemSelectionModel.SelectionFlag.NoUpdate)
def focusInEvent(self, event):
self.focused = True
super().focusInEvent(event)
def | show_hidden(self, state):
config = get_config()
config.persist["show_hidden_files"] = state
self._set_model_filter()
def save_state(self):
indexes = self.selectedIndexes()
if indexes:
path = self.model().filePath(indexes[0])
config = get_config()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.