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 |
|---|---|---|---|---|---|---|---|---|
SalesforceFoundation/HEDAP | robot/EDA/resources/SystemSettingsPageObject.py | Python | bsd-3-clause | 5,956 | 0.009402 | from BaseObjects import BaseEDAPage
from EDA import eda_lex_locators
from cumulusci.robotframework.pageobjects import BasePage
from cumulusci.robotframework.pageobjects import pageobject
import time
@pageobject("System", "HEDA_Settings")
class SystemSettingsPage(BaseEDAPage, BasePage):
def _is_current_page(self)... | error= "Element is not di | splayed for the user")
actual_value = self.selenium.get_webelement(locator).text
if not str(expected_value).lower() == str(actual_value).lower() :
raise Exception (f"Dropdown value in {field} is {actual_value} but it should be {expected_value}")
|
seankelly/buildbot | master/buildbot/test/unit/test_plugins.py | Python | gpl-2.0 | 14,759 | 0 | # This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | rror, plugins.get, 'good')
def test_failure_on_dups(self):
self.assertRaises(PluginDBError, db.get_plugins, 'duplicates',
| load_now=True)
def test_get_info_on_a_known_plugin(self):
plugins = db.get_plugins('interface')
self.assertEqual(('non-existent', 'irrelevant'), plugins.info('good'))
def test_failure_on_unknown_plugin_info(self):
plugins = db.get_plugins('interface')
sel... |
oe-alliance/oe-alliance-enigma2 | lib/python/Screens/ChannelSelection.py | Python | gpl-2.0 | 87,895 | 0.029365 | # -*- coding: utf-8 -*-
from Tools.Profile import profile
from Screen import Screen
import Screens.InfoBar
import Components.ParentalControl
from Components.Button import Button
from Components.ServiceList import ServiceList
from Components.ActionMap import NumberActionMap, ActionMap, HelpableActionMap
from Components... | == -1:
if not csel.dopipzap:
append_when_current_valid(current, menu, (_("play as picture in picture"), self.showServiceInPiP), level = 0, key = "blue")
self.pipAvailable = True
else:
append_when_current_valid(current, menu, (_("play in mainwindow"), self.playMain), level = 0) |
else:
if 'FROM SATELLITES' in current_root.getPath():
append_when_current_valid(current, menu, (_("remove selected satellite"), self.removeSatelliteServices), level = 0)
if haveBouquets:
if not inBouquet and not "PROVIDERS" in current_sel_path:
append_when_current_valid(current, menu, ... |
uliss/quneiform | tests/py/cf.py | Python | gpl-3.0 | 12,883 | 0.006443 | #!@PYTHON_EXECUTABLE@
# -*- coding: utf-8 -*-
import os, sys
import zipfile
import platform
from subprocess import *
from xml.dom import minidom
import re
import glob
os.environ['CF_DATADIR'] = "@CMAKE_SOURCE_DIR@/datafiles"
os.environ['PATH'] = os.environ['PATH'] + ":@CMAKE_BINARY_DIR@"
# globals exe's and paths
CU... | self.HEADER = ''
self.OKBLUE = ''
self.OK = ''
self.WARNING = ''
self.FAIL = ''
self.END = ''
@staticmethod
def clear():
bcolor.HEADER = ''
bcolor.OKBLUE = ''
bcolor.OK = ''
bcolor.WARNING = ''
bcolor.FAIL = ''
bcolor.END ... | () == 'Windows':
bcolor.clear()
class Tester:
_imagedir = ''
_images = []
_version = None
_tests_passed = 0
_tests_failed = 0
_language = None
_output = None
_output_image_dir = None
_format = None
_line_breaks = False
_sample_ext = None
_args = []
_turn = 0
... |
aladdinwang/django-cms | cms/migrations/0049_auto__del_field_page_template.py | Python | bsd-3-clause | 15,791 | 0.008233 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaM | igration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Page.template'
db.delete_column(u'cms_page', 'template')
def backwards(self, orm):
# User chose to not deal with backwards NULL issues for 'Page.template'
rais... | Error("Cannot reverse this migration. 'Page.template' and its values cannot be restored.")
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField... |
enriquesanchezb/practica_utad_2016 | venv/lib/python2.7/site-packages/_pytest/main.py | Python | apache-2.0 | 26,215 | 0.002022 | """ core implementation of testing process: init, session, runtest loop. """
import imp
import os
import re
import sys
import _pytest
import _pytest._code
import py
import pytest
try:
from collections import MutableMapping as MappingMixin
except ImportError:
from UserDict import DictMixin as MappingMixin
from... | )
def keys(self):
return list(self)
def __repr__(self):
return "<NodeKeywords for node %s>" % (self.node, )
class Node(object):
""" base class for Collector and Item the test collection tree.
Collector subclasses have children, Items are terminal nodes."""
def __init__(self, nam... | scope of the parent node
self.name = name
#: the parent collector node.
self.parent = parent
#: the pytest config object
self.config = config or parent.config
#: the session this node is part of
self.session = session or parent.session
#: filesystem pa... |
clicheio/cliche | cliche/celery.py | Python | mit | 7,480 | 0 | """:mod:`cliche.celery` --- Celery_-backed task queue worker
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Sometimes web app should provide time-consuming features that cannot
immediately respond to user (and we define "immediately" as "shorter than
a second or two seconds" in here). Such things should... | database session.
:returns: a database session
:rtype: :class:`~.orm.Session`
"""
task = current_task._get_current_object()
request = task.request
if getattr(request, 'db_session', None) is None:
request.db_session = Session(bind=get_database_engine())
return request.db_session
... |
session = getattr(task.request, 'db_session', None)
if session is not None:
session.close()
def get_raven_client() -> Client:
"""Get a raven client.
:returns: a raven client
:rtype: :class:`raven.Client`
"""
config = current_app.conf
if 'SENTRY_DSN' in config:
if 'RA... |
pim89/youtube-dl | youtube_dl/extractor/dramafever.py | Python | unlicense | 7,450 | 0.002148 | # coding: utf-8
from __future__ import unicode_literals
import itertools
from .amp import AMPIE
from ..compat import (
compat_HTTPError,
compat_urlparse,
)
from ..utils import (
ExtractorError,
clean_html,
int_or_none,
sanitized_Request,
urlencode_postdata
)
class DramaFeverBaseIE(AMPIE)... | continue
entries.append(self.url_result(
compat_urlparse.urljoin(url, episode_u | rl),
'DramaFever', episode.get('guid')))
if page_num == episodes['num_pages']:
break
return self.playlist_result(entries, series_id, title, description)
|
jart/tensorflow | tensorflow/python/keras/engine/training_utils.py | Python | apache-2.0 | 32,266 | 0.006446 | # Copyright 2018 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... | NumPy arrays in graph mode
# placeholder ops should be used
# this i | s only ideal for eager mode
dataset = dataset_ops.Dataset.from_tensor_slices(data)
if batch_size is not None:
dataset = dataset.batch(batch_size)
if shuffle:
dataset = dataset.shuffle(buffer_size=10000)
dataset = dataset.repeat(epochs)
iterator = dataset.make_one_shot_iterator()
return iterator, s... |
drewrobb/marathon-python | marathon/models/deployment.py | Python | mit | 3,907 | 0.003071 | from .base import MarathonObject, MarathonResource
class MarathonDeployment(MarathonResource):
"""Marathon Application resource.
See: https://mesosphere.github.io/marathon/docs/rest-api.html#deployments
https://mesosphere.github.io/marathon/docs/generated/api.html#v2_deployments_get
:param lis... | def parse_deployment_step(self, step):
if step.__class__ == dict:
# This is what Marathon 1.0.0 returns: steps
return MarathonDeploymentStep().from_json(step)
elif step.__class__ == list:
# This is Marathon < 1.0.0 style, a list of actions
return [s if i... | ntAction().from_json(s) for s in step]
else:
return step
class MarathonDeploymentAction(MarathonObject):
"""Marathon Application resource.
See: https://mesosphere.github.io/marathon/docs/rest-api.html#deployments
:param str action: action
:param str app: app id
:param str app... |
wjo1212/aliyun-log-python-sdk | aliyun/log/cursor_time_response.py | Python | mit | 808 | 0.001238 | #!/usr/bin/env python
# encoding: utf-8
# Copyright (C) Alibaba Cloud Computing
# All rights reserved.
from .logresponse import LogResponse
class GetCursorTimeResponse(LogResponse):
""" The response of the get_cursor_time API from log.
:type header: dict
:param header: GetCursorTime | Response HTTP response header
:type resp: dict
:param resp: the HTTP response body
"""
def __init__(self, resp, header):
LogResponse.__init__(self, header, resp)
self.cursor_time = resp['cursor_time']
def get_cursor_time(self):
"""
:return:
"" | "
return self.cursor_time
def log_print(self):
print('GetCursorTimeResponse')
print('headers:', self.get_all_headers())
print('cursor_time:', self.cursor_time)
|
PyCon/pycon | pycon/sponsorship/admin.py | Python | bsd-3-clause | 6,184 | 0.002264 | from urllib import quote
from django import forms
from django.contrib import admin
from django.db import models
from django.utils.html import escape, format_html
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from pycon.sponsorship.models import SponsorLevel, Spo... |
u'<a href="mailto:{}">{}</a>',
quote(u','.join(sponsor.contact_emails)),
sponsor.contact_name
)
def applicant_field(self, sponsor):
name = sponsor.applicant.get_full_name()
email = sponsor.applicant.email
return mark_safe('<a href="mailto:%s">%s<... | description = _(u"Applicant")
def get_form(self, *args, **kwargs):
# @@@ kinda ugly but using choices= on NullBooleanField is broken
form = super(SponsorAdmin, self).get_form(*args, **kwargs)
form.base_fields["active"].widget.choices = [
(u"1", _(u"unreviewed")),
(u... |
alex/pyvcs | tests/andrew_tests.py | Python | bsd-3-clause | 1,801 | 0.004997 | #!/usr/bin/env python
from datetime import datetime
import unit | test
from pyvcs.backends import get_backend
from pyvcs.exceptions import FileDoesNotExist, FolderDoes | NotExist
class BzrTest(unittest.TestCase):
def setUp(self):
bzr = get_backend('bzr')
self.repo = bzr.Repository('/home/andrew/junk/django/')
def test_commits(self):
commit = self.repo.get_commit_by_id('6460')
self.assert_(commit.author.startswith('gwilson'))
self.assert... |
andmos/ansible | lib/ansible/playbook/role/metadata.py | Python | gpl-3.0 | 4,362 | 0.001834 | # (c) 2014 Michael DeHaan, <[email protected]>
#
# This file is part of Ansible
#
# Ansible 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 ve... | s is not a dictionary" % owner.get_name())
m = RoleMetadata(owner=owner).load_data(data, variable_manager=variable_manager, loader=loader)
return | m
def _load_dependencies(self, attr, ds):
'''
This is a helper loading function for the dependencies list,
which returns a list of RoleInclude objects
'''
roles = []
if ds:
if not isinstance(ds, list):
raise AnsibleParserError("Expected r... |
pratikmallya/heat | heat/engine/lifecycle_plugin.py | Python | apache-2.0 | 2,141 | 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
# ... | f get_ordinal(self):
"""Order class instances for pre and post operation execution.
The values returned by get_ordinal are used to create a partial order
for pre and post operation method invocations. The default ordinal
value of 100 may be overridden.
If class1inst.ordinal() < ... | lass2inst.
If class1inst.ordinal() > class2inst.ordinal(), then the method on
class1inst will be executed after the method on class2inst.
If class1inst.ordinal() == class2inst.ordinal(), then the order of
method invocation is indeterminate.
"""
return 100
|
openweave/openweave-core | src/test-apps/happy/tests/service/wdmNext/test_weave_wdm_next_service_mutual_subscribe_08.py | Python | apache-2.0 | 2,898 | 0.010697 | #!/usr/bin/env python3
#
# Copyright (c) 2016-2017 Nest Labs, 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/lic... | mport
from __future__ import print_function
import unittest
from weave_wdm_next_test_service_base import weave_wdm_next_test_service_base
class test_weave_wdm_next_service_mutual_subscribe_08(weave_wdm_next_test_service_base):
def test_weave_wdm_next_service_mutual_subscribe_08(self):
wdm_next_args = {}
... | ient_iterations'] = 10
wdm_next_args['client_clear_state_between_iterations'] = True
wdm_next_args['client_log_check'] = [('bound mutual subscription is going away', wdm_next_args['test_client_iterations']),
('Handler\[0\] \[(ALIVE|CONFM)\] AbortSubscription ... |
nixon/pretty | setup.py | Python | bsd-2-clause | 725 | 0 | from setuptoo | ls import find_packages
from distutils.core import setup
from pretty_times import VERSION
REQUIREMENTS = []
TEST_REQUIREMENTS = [
'cover | age',
'pep8',
'pyflakes',
'nose',
'nosexcover',
]
def do_setup():
setup(
name="pretty-times",
version=VERSION,
author="nixon",
description="pretty_times provides fixes for the py-pretty library.",
long_description=open('README.txt', 'r').read(),
url=... |
aldanor/SocketIO-Flask-Debug | app.py | Python | mit | 1,749 | 0.000572 | from gevent import monkey
from socketio.server import | SocketIOServer
from socketio import socketio_manage
from flask import Flask, request, render_template, Response
from werkzeug.serving import run_with_reloader
from socketio.namespace import BaseNamespace
from debu | gger import SocketIODebugger
monkey.patch_all()
class Namespace(BaseNamespace):
def __init__(self, *args, **kwargs):
print '\nNamespace.__init__(args=%s, kwargs=%s)' % (
repr(args), repr(kwargs))
super(Namespace, self).__init__(*args, **kwargs)
def recv_connect(self):
pr... |
kostya0shift/SyncToGit | synctogit/Config.py | Python | mit | 1,728 | 0.001157 | from __future__ import absolute_import
try:
import configparser
except:
import ConfigParser as configparser
class _NotSet(object):
pass
class ConfigException(Exception):
pass
class Config:
def __init__(self, conffile):
self.conffile = conffile
self.conf = configparser.ConfigP... | if not self.conf.has_section(section):
if isinstance(default, _NotSet):
raise ConfigException('Section %s is missing' % section)
else:
return default
if not self.conf.has_option(section, key):
if isinstance(default, _NotSet):
... | se:
v = getter(section, key)
return v
def get_int(self, section, key, default=_NotSet()):
v = self._get(section, key, self.conf.getint, default)
return int(v)
def get_string(self, section, key, default=_NotSet()):
v = self._get(section, key, self.conf.get, default)... |
denfromufa/clrmagic | clrmagic.py | Python | mit | 2,540 | 0.014567 |
import clr
def create_cs_function(name, code, dependencies = None):
clr.AddReference("clrmagic")
from MagicIPython import MagicCS
from System import String
from System.Collections.Generic import List
if dependencies is not None and len(dependencies) > 0 :
myarray = List[String]()
... | """
Defines command ``%%CS``.
"""
#if not sys.platform.startswith("win"):
# raise Exception("Works only on Windows.")
#from clrfunction import create_cs_function
if line is not None:
spl = line.strip().split(" ")
name = spl[0]
... | l) > 1 else ""
deps = deps.split(";")
if name == "-h":
print( "Usage: "
" %%CS function_name dependency1;dependency2"
" function code")
else :
try:
f = create_cs_function(name, cell, deps)
... |
praekelt/molo-gem | gem/admin.py | Python | bsd-2-clause | 3,379 | 0 | from collections import Counter
from django.contrib import admin
from django.contrib.auth.models import User
from gem.models import GemCommentReport, Invite
from gem.rules import ProfileDataRule, CommentCountRule
from molo.commenting.admin import MoloCommentAdmin, MoloCommentsModelAdmin
from molo.commenting.models i... | quest.user
if not form.instance.site:
form.instance.site = site
return super().form_valid(form)
create_view_class = InviteCreateView
modeladmin_register(InviteAdmin)
class UserProfileInlin | eModelAdmin(admin.StackedInline):
model = UserProfile
can_delete = False
class GemCommentReportModelAdmin(admin.StackedInline):
model = GemCommentReport
can_delete = True
max_num = 0
actions = None
readonly_fields = ["user", "reported_reason", ]
class FormsSegementUserPermissionHelper(Pe... |
benjamincongdon/adept | inventory.py | Python | mit | 6,093 | 0.005744 | from item import Item
import random
from floatingText import FloatingText,FloatingTextManager
from playerConsole import PlayerConsole
from serializable import Serializable
from eventRegistry import Event
from eventRegistry import EventRegistry
class Inventory(Serializable):
INV_SIZE_X = 10
INV_SIZE_Y = 3
... | {'item':item}
))
for x in range(Inventory.INV_SIZE_X):
if self.hotbar[x] != None and self.hotbar[x].name == item | .name:
self.hotbar[x].quantity += item.quantity
return
if self.hotbar[x] == None and isinstance(item, Item):
self.hotbar[x] = item
return
for x in range(Inventory.INV_SIZE_X):
for y in range(Inventory.INV_SIZE_Y):
... |
CompassionCH/compassion-modules | crm_compassion/models/event_compassion.py | Python | agpl-3.0 | 22,387 | 0 | ##############################################################################
#
# Copyright (C) 2014 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <[email protected]>
#
# The licence is in the file __manifest__.py
#
#####################... | event.balance = event.total_income / float(event.total_expense) |
else:
event.balance = 0.0
@api.multi
@api.depends("start_date")
def _compute_year(self):
for event in self.filtered("start_date"):
event.year = str(event.start_date.year)
@api.multi
def _compute_full_name(self):
for event in self:
... |
bluefish/kdi | src/python/kdi/splits.py | Python | gpl-2.0 | 4,429 | 0.01445 | #!/usr/bin/env python
#
# Copyright (C) 2008 Josh Taylor (Kosmix Corporation)
# Created 2008-06-15
#
# This file is part of KDI.
#
# KDI 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 th... | License, or any later version.
#
# KDI 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
# details.
#
# You should have received a copy of the GNU | General Public License along
# with this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
def iterSplitRanges(splitPoints, maxKey):
minT = 0.0
minKey = ''
for t,s in splitPoints:
yield (minT, t, minKey, s)
min... |
SWRG/semanticsdata | RDFTypeSummary.py | Python | gpl-3.0 | 1,493 | 0.013396 | # -*- coding: utf-8 -*-
"""
This class can be used to load an RDF-type summary graph.
:author: Spyridon Kazanas
:contact: [email protected]
"""
import networkx as nx
import cPickle,csv
from os import p | ath
class RDFTypeSummary():
# db info
db_graph = None
db_file = None
def __init__(self,inputfile=None):
if inputfile is not None:
self.loaddb(inputfile)
def loaddb(self,inputfile):
"""
Loads db_graph, shortest path data and labeli | ngs from save directory.
Sorts labelings.
:param dirpath: The directory containing data.
"""
inputfile = path.abspath(path.expanduser(inputfile))
print "Loading RDF-type summary graph: ",inputfile
print "(please wait)"
if path.isfile(inputfile):
sel... |
pFernbach/hpp-rbprm-corba | script/scenarios/sandbox/siggraph_asia/chair/bezier_traj.py | Python | lgpl-3.0 | 22,357 | 0.028984 | from gen_data_from_rbprm import *
from hpp.corbaserver.rbprm.tools.com_constraints import get_com_constraint
from hpp.gepetto import PathPla | yer
from hpp.corbaserver.rbprm.s | tate_alg import computeIntermediateState, isContactCreated
from numpy import matrix, asarray
from numpy.linalg import norm
from spline import bezier
def __curveToWps(curve):
return asarray(curve.waypoints().transpose()).tolist()
def __Bezier(wps, init_acc = [0.,0.,0.], end_acc = [0.,0.,0.], init_vel = [0.,0.,... |
ioos/catalog-harvesting | catalog_harvesting/__init__.py | Python | mit | 762 | 0 | #!/usr/bin/env python
'''
catalog_harvesting/__init__.py
'''
import logging
import os
__version__ = '1.2.0'
| LOGGER = None
def get_logger():
'''
Returns an initialized logger
'''
global LOGGER
if LOGGER is None:
LOGGER = logging.getLogger(__name__)
return LOGGER
def get_r | edis_connection():
redis_url = os.environ.get('REDIS_URL', 'redis://localhost:6379/0')
protocol, address = redis_url.split('://')
if protocol != 'redis':
raise ValueError('REDIS_URL must be protocol redis')
connection_str, path = address.split('/')
if ':' in connection_str:
host, por... |
duplocloud/duploiotagent | samples/basicShadow/basicShadowUpdater.py | Python | apache-2.0 | 5,041 | 0.004166 | '''
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache Licens | e, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF AN... | icense for the specific language governing
* permissions and limitations under the License.
*/
'''
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient
import logging
import time
import json
import argparse
# Shadow JSON schema:
#
# Name: Bot
# {
# "state": {
# "desired":{
# "property":<INT VALUE>
# }
#... |
lightbase/LBApp | lbapp/config/routing.py | Python | gpl-2.0 | 743 | 0.001346 |
def make_routes(config):
from lbapp.config.routes.base import make_base_routes
from lbapp.config.routes.user import make_user_routes
# ** STATIC **
config.add_static_view('static', 'static', cache_max_age=3600)
config.add_static_view('templates', 'templates', cache_max_age=3600)
# ** HOME **
... | # ** BASE **
make_base_routes(config)
# ** USER **
make_user_routes(config)
| config.add_route('delete_tmp_storage', 'base/{id}/tmp-storage/{storage}')
config.add_route('tmp_storage', 'base/{id}/tmp-storage')
# ** ERROR **
config.add_route('error-404', 'error-404')
config.add_route('error-500', 'error-500')
|
593141477/pyA13_swiftboard | source/A13_SPI.py | Python | mit | 6,079 | 0.01168 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# A13_SPI.py
#
# Copyright 2013 Stefan Mavrodiev <[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 ... | GPIO.output(SCK, LOW)
else:
GPIO.output(SCK, HIGH)
byte >>= 1
def ReadByte():
byte = 0
for i in range(8):
time.sleep(0.000001)
| if pol == 0:
GPIO.output(SCK, HIGH)
else:
GPIO.output(SCK, LOW)
if pha == 0:
if GPIO.input(MISO) == 1:
if pol == 0:
byte |= 1
else:
byte |= 0
... |
JoelBender/bacpypes | py27/bacpypes/service/object.py | Python | mit | 15,660 | 0.007088 | #!/usr/bin/env python
from ..debugging import bacpypes_debugging, ModuleLogger
from ..capability import Capability
from ..basetypes import ErrorType, PropertyIdentifier
from ..primitivedata import Atomic, Null, Unsigned
from ..constructeddata import Any, Array, ArrayOf, List
from ..apdu import \
SimpleAckPDU, Re... | ePropertyServices._debug(" - wildcard device identifier")
objId = self.localDevice.objectIdentifier
# get the object
obj = self.get_object_id(objId)
if _debug: ReadWritePropertyServices._debug(" - object: %r", obj)
if | not obj:
raise ExecutionError(errorClass='object', errorCode='unknownObject')
try:
# get the datatype
datatype = obj.get_datatype(apdu.propertyIdentifier)
if _debug: ReadWritePropertyServices._debug(" - datatype: %r", datatype)
# get the value
... |
pshchelo/heat | heat/engine/resources/openstack/ceilometer/alarm.py | Python | apache-2.0 | 14,721 | 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
# ... | ck, properties):
kwargs = {}
for k, v in iter(properties.items()):
if k in [ALARM_ACTIONS, OK_ACTIONS,
INSUFFICIENT_DATA_ACTIONS] and v is not None:
kwargs[k] = []
for act in v:
# if the action is a resource name
| # we ask the destination resource for an alarm url.
# the template writer should really do this in the
# template if possible with:
# {Fn::GetAtt: ['MyAction', 'AlarmUrl']}
if act in stack:
url = stack[act].FnGetAtt('AlarmUrl')
... |
ONEcampaign/humanitarian-data-service | resources/data/raw/example/transform_scripts/parse_acled_all_africa.py | Python | mit | 1,542 | 0.003243 | import re
import pandas as pd
ACLED_FILE = 'ACLED-All-Africa-File_20170101-to-20170429.csv'
def clean_and_save():
encoding_key = 'iso-8859-1'
df = pd.read_csv(ACLED_FILE, encoding=encoding_key)
print df.head()
print df.columns
print df.describe()
cleaned_file = 'cleaned_{}'.format(ACLED_FILE)... | descript, country = results[0]
if bool(_digits.search(country)):
# here it's probably a year, not a country
# try to get last word of first string as proxy for region
country = descript.split()[-1]
return country.strip()
df['ex... | format(ACLED_FILE)
df.to_csv(derived_file, encoding='utf-8', index=False)
return df, derived_file
def run():
print 'Transforming ACLED data...'
cleaned_df, cleaned_file = clean_and_save()
derived_df, derived_file = derive_cols(cleaned_file)
print 'Done!'
run()
|
dana-i2cat/felix | ofam/src/src/foam/sfa/methods/Start.py | Python | apache-2.0 | 402 | 0.014925 | from foa | m.sfa.util.xrn import urn_to_hrn
from foam.sfa.trust.credential import Credential
from foam.sfa.trust.auth import Auth
class Start:
def __init__(self, xrn, creds, **kwargs):
hrn, type = urn_to_hrn(xrn)
valid_creds = Auth().checkCredentials(creds, 'startslice', hrn)
origin_hrn = Credent... | |
sairon/motoscrape | motoscrape/settings.py | Python | unlicense | 3,018 | 0.009609 | # -*- coding: utf-8 -*-
# Scrapy settings for motoscrape project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/lat... | {
# 'motoscr | ape.middlewares.MyCustomSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'motoscrape.middlewares.MyCustomDownloaderMiddleware': 543,
#}
# Enable or disable extensions
# See http://scra... |
jkeen/tracking_number_data | utils/gen_s10_countries.py | Python | mit | 4,361 | 0.000917 | #!/usr/bin/env python
"""Update the file s10_country_code.json with
the latest list of member countries
requirements:
requests
beautifulsoup
grequests
"""
import requests
import bs4
from os.path import join
import json
import grequests
from requests.adapters import HTTPAdapter
from requests.packages.urllib... | urier_url"
}
countrydct = {}
for attr in attr_map:
if attr == 'operator':
value, child = _get_value(attr, soup)
if value is None: # try to get ministry
value, child = _get_value("ministry", soup)
| countrydct['courier'] = child.next_element.text \
if value is not None else None
countrydct['courier_url2'] = value
else:
value, child = _get_value(attr, soup)
countrydct[attr_map[attr]] = value
if countrydct['courier_url'] is None:
cou... |
mhbu50/erpnext | erpnext/templates/pages/material_request_info.py | Python | gpl-3.0 | 1,743 | 0.021801 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
import frappe
from frappe import _
from frappe.utils import flt
def get_context(context):
context.no_cache = 1
context.show_sidebar = True
context.doc = frappe.get_doc(frappe.form_dict.d... | "Standard"
context.doc.items = get_more_items_info(context.doc.items, context.doc.name)
def get_more_items_info(items, material_request):
for item in items:
item.customer_provided = frappe.get_value('I | tem', item.item_code, 'is_customer_provided_item')
item.work_orders = frappe.db.sql("""
select
wo.name, wo.status, wo_item.consumed_qty
from
`tabWork Order Item` wo_item, `tabWork Order` wo
where
wo_item.item_code=%s
and wo_item.consumed_qty=0
and wo_item.parent=wo.name
and wo.status ... |
bartosz-kozak/Sample-script | python/seq_len.py | Python | mit | 544 | 0.014733 | #!usr/bin/python2.7
# coding: | utf-8
# date: 16-wrzesień-2016
# autor: B.Kozak
# Simple script giving length of sequences from fasta file
import Bio
from Bio import SeqIO
import sys
import os.path
filename = sys.argv[-1]
outname = filename.split('.')
outname1 = '.'.join([outname[0], 'txt'])
FastaFile = open(filename, 'rU')
f = open(outname1, '... | '
|
Fillll/reddit2telegram | reddit2telegram/channels/~inactive/r_technology/app.py | Python | mit | 143 | 0.006993 | #encoding | :utf-8
subreddit = 'technology'
t_channel = '@r_technology'
def send_post(submission, r2t):
| return r2t.send_simple(submission)
|
dorey/pyxform | pyxform/tests_v1/test_translations.py | Python | bsd-2-clause | 1,244 | 0.000804 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from pyxform_test_case import PyxformTestCase
class DoubleColonTranslations(PyxformTestCase):
def test_langs(self):
self.assertPyxformXform(
name='translations',
id_string='transl',
md="""
| survey | | | ... | """<label ref="jr:itext('/translations/n1:label')"/>""",
| ],
model__contains=[
'<bind nodeset="/translations/n1" readonly="true()" type="string"/>',
],
)
|
oppia/oppia-ml | core/classifiers/classifier_utils_test.py | Python | apache-2.0 | 9,247 | 0.001081 | # coding: utf-8
#
# Copyright 2017 The Oppia 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 requi... | u'intercept', u'classes', u'kernel_params', u'probA',
u'probB']
self.assertListEqual(sorted(expected_keys), sorted(data.keys()))
# Make s | ure that all of the values are of serializable type.
self.assertEqual(type(data[u'n_support']), list)
self.assertEqual(type(data[u'support_vectors']), list)
self.assertEqual(type(data[u'dual_coef']), list)
self.assertEqual(type(data[u'intercept']), list)
self.assertEqual(type(dat... |
antoinecarme/pyaf | tests/model_control/detailed/transf_RelativeDifference/model_control_one_enabled_RelativeDifference_ConstantTrend_BestCycle_AR.py | Python | bsd-3-clause | 164 | 0.04878 | import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['RelativeDifference'] , ['ConstantTrend' | ] , ['BestCycle'] , ['AR | '] ); |
adblockplus/abpbot | beanbot-client.py | Python | gpl-2.0 | 843 | 0.020166 | #!/usr/bin/python
import sys, re
from socket import *
serve_addr = ('localhost', 47701)
if __name__ == '__main__':
IRC_BOLD = '\x02'
IRC_ULINE = '\x1f'
IRC_NORMAL = '\x0f'
IRC_RED = '\x034'
IRC_LIME = '\x039'
IRC_BLUE = '\x0312'
repo, branch, author, rev, description = sys | .argv[1:6]
match = re.search(r'^\s*(.*?)\s*<.*>\s*$', author)
if match:
author = match.group(1)
data = (
"%(IRC_RED)s%(repo)s"
"%(IRC_NORMAL)s[%(branch)s] "
"%(IRC_NORMAL)s%(IRC_BOLD)s%(author)s "
"%(IRC_NORMAL)s%(IRC_ULINE)s%(rev)s%(IRC_NORMAL)s "
"%(description)s" % | locals()
)
if len(data) > 400:
data = data[:400] + "..."
sock = socket(AF_INET, SOCK_DGRAM)
sock.sendto(data, serve_addr)
sock.sendto("https://hg.adblockplus.org/%(repo)s/rev/%(rev)s" % locals(), serve_addr)
sock.close()
|
Connexions/cnx-epub | cnxepub/formatters.py | Python | agpl-3.0 | 33,743 | 0 | # -*- coding: ut | f-8 -*-
# ###
# Copyright (c) 2016, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
fr | om __future__ import unicode_literals
import hashlib
import json
import logging
import sys
from io import BytesIO
import re
import jinja2
import lxml.html
from lxml import etree
from copy import deepcopy
import requests
from .models import (
model_to_tree, content_to_etree, etree_to_content,
flatten_to_docum... |
mattbrowley/PSim | simplex.py | Python | mit | 11,438 | 0.003759 | #!/usr/bin/env python
#
# -*- Mode: python -*-
#
# $Id: Simplex.py,v 1.2 2004/05/31 14:01:06 vivake Exp $
#
# Copyright (c) 2002-2004 Vivake Gupta (vivakeATlab49.com). All rights reserved.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as... | l
# static parameters to the objective function (Filip Dominec)
""" Simplex - a regression method for arbitrary nonlinear function minimization
Simplex minimizes an arbitrary nonlinear function of N variables by the
Nedler-Mead Simplex method as described in:
Nedler, J.A. and Mead, R. "A Simplex Me... | inimized.
It converges to a local minimum which may or may not be the global minimum
depending on the initial guess used as a starting point.
"""
import math
import copy
import csv
import time
#from numpy import ndarray as nd
class Simplex:
def __init__(self, testfunc, guess, increments, kR = -1, kE = 2, kC = 0... |
collective/cyn.in | src/ubify.coretypes/ubify/coretypes/content/spacesfolder.py | Python | gpl-3.0 | 2,590 | 0.016216 | ###############################################################################
#cyn.in is an open source Collaborative Knowledge Management Appliance that
#enables teams to seamlessly work together on files, documents and content in
#a secure central environment.
#
#cyn.in v2 an open source appliance is distrib... |
class SpacesFolder(BaseClass):
__doc__ = BaseClass.__doc__ + "(customizable version)"
# portal_type = BaseClass.portal_type
# archetype_name = BaseClass.archetype_name
schema = schema
_at_rename_after_creation = True
# enable FTP/WebDAV and friends
PUT = BaseC | lass.PUT
registerATCT(SpacesFolder, PROJECTNAME)
|
zelongc/cloud-project | connect_db.py | Python | mit | 783 | 0.014049 | #!/usr/bin/python
from couchdb import Server
import datetime
# server = Server() # connects to the local_server
# >>> remote_server = Server('http://example.com:5984/')
# >>> secure_remote_server = Server('https://username:[email protected]:5984/')
class db_server(object):
def __init__(self,username,login):
... | %[email protected]:5984' % (username, login))
self.db = self.secure_server["new_tweet"]
def insert(self,data):
try:
doc_id,doc_rev=self.db.save(data)
except Exception as e:
with open('dabatase_log','a') as f:
f.write("["+datetime.datetime.now().__str__... | e((data['_id']+'\n'))
|
UCNA/main | Scripts/plotters/LarmorClipping.py | Python | gpl-3.0 | 8,636 | 0.074456 | #!/sw/bin/python2.7
import sys
sys.path.append("..")
from ucnacore.PyxUtils import *
from math import *
from ucnacore.LinFitter import *
#from UCNAUtils import *
from bisect import bisect
from calib.FieldMapGen import *
def clip_function(y,rho,h,R):
sqd = sqrt(rho**2-y**2)
if sqd==0:
sqd = 1e-10
return h*rho**2... | point
vz,nu = larmor_step(p,pt2_per_B,fmap(z))
theta += nu*dt
z += vz*dt
return lpath
def plot_larmor_trajectory():
fmap = fieldMap()
fmap.addFlat(-1.0,0.01,1.0)
fmap.addFlat(0.015,1.0,0.6)
#fmap.addFlat(-1.0,0.01,0.6)
#fmap.addFlat(0.08,1.0,1.0)
fT = fmap(0)
theta = 1.4
KE = 511.
#rot = r... | -pi/2+0.2,500)
tm = 1e-9
doFinal = True
plarmor = larmorPath(fmap,500,495**2/fmap(0),0,0.02,5e-13,3*pi/4)
plarmor.apply(rot)
#plarmor.sty = [style.linewidth.thick,rgb.red]
plarmor.sty = [style.linewidth.thick]
plarmor.endsty = [deco.earrow()]
plarmor.finish()
x0,y0 = plarmor.p.at(plarmor.p.begin())
fieldl... |
dbaty/soho | tests/test_builder.py | Python | bsd-3-clause | 4,834 | 0.000414 | from contextlib import contextmanager
from filecmp import dircmp
from tempfile import mkdtemp
from shutil import rmtree
from unittest import TestCase
@contextmanager
def temp_folder():
tmp_dir = mkdtemp()
try:
yield tmp_dir
finally:
rmtree(tmp_dir)
class DummyLogger(object):
def info(... | _dir, 'sitemap.xml')
if os.path.exists(sitemap):
self._fix_lastmod_in_sitemap(out_dir)
def test_builder(self):
from .base import make_options
options = make_options(config_file=self.config_file)
with temp_folder() as out_dir:
builder = self._make_builder(opti... | self.expected_dir)
class TestSite1(BuilderFunctionalTest, TestCase):
test_site = 'site1'
# inherits 'test_builder()' from BuilderFunctionalTest
def test_builder_dry_run(self):
import os
from .base import make_options
options = make_options(config_file=self.config_file, do_nothin... |
madpilot78/ntopng | tools/http_authenticator.py | Python | gpl-3.0 | 2,414 | 0.002071 | #!/usr/bin/env python3
#
# https://gist.githubusercontent.com/Integralist/ce5ebb37390ab0ae56c9e6e80128fdc2/raw/2e62bcc38aed7873f07e06865f0f4c06ec9129ee/Python3%2520HTTP%2520Server.py
#
# Sample HTTP authenticator service which work with ntopng "http" authentication.
# The "HTTP server" URL should be set to "http://loca... | questHandler, HTTPServer
HOST_NAME = 'localhost'
PORT_NUMBER = 3001
USERS_DB = {
"testuser": {"password": "avoid-plaintext", "admin": False},
"testadmin | ": {"password": "avoid-plaintext-admin", "admin": True},
}
class MyHandler(BaseHTTPRequestHandler):
def do_POST(self):
if self.path == "/login":
self.handle_login()
else:
self.respond({'status': 500})
def handle_http(self, status_code, path, data={}):
self.send_... |
lpirl/autosuspend | autosuspend.pre/200-ensure-low-loadavg.py | Python | gpl-3.0 | 507 | 0.005917 | #!/usr/bin/env python3
# Exits with exit code 0 (i.e., allows sleep) if all load averages
# (1, 5, 15 minutes) are below ``MAX_IDLE_LOAD``.
from os import getloadavg
MAX_IDLE_ | LOAD = .09
def check_load(time_span, load):
| if load > MAX_IDLE_LOAD:
print(
" Won't sleep because %i minute load average" % time_span,
"of %.2f is above threshold of %.2f." % (load, MAX_IDLE_LOAD)
)
exit(1)
loads = getloadavg()
check_load(1, loads[0])
check_load(5, loads[1])
check_load(15, loads[2])
|
kstaniek/ciscoconfparse | ciscoconfparse/__init__.py | Python | gpl-3.0 | 29 | 0 | from ciscoconf | parse import *
| |
matthewoconnor/maps | map/admin.py | Python | mit | 975 | 0.007179 | from django.contrib import admin, messages
from .tasks import import_areas_from_kml_file
from .models import Area, AreaMap, DataMap, AreaBin
class AreaAdmin(admin.ModelAdmin):
list_display = ("id", "name", "area_type")
class AreaMapAd | min(admin.ModelAdmin):
list_display = ("id", "name", "data_source", "dataset_identifier", "created_time")
actions = ["generate_areas_from_kmlfile"]
def generate_areas_from_kmlfile(modeladmin, request, queryset):
for areamap in queryset:
import_areas_from_kml_file.apply_async(args=[areamap])
... | = ("id", "name", "area_map", "data_source", "dataset_identifier", "created_time")
class AreaBinAdmin(admin.ModelAdmin):
list_display = ("id", "data_map", "area", "value", "count")
admin.site.register(Area, AreaAdmin)
admin.site.register(AreaMap, AreaMapAdmin)
admin.site.register(DataMap, DataMapAdmin)
admin.si... |
Muyoo/gold_pred | feature_creator/news.py | Python | apache-2.0 | 3,497 | 0.004713 | #!/usr/bin/env python
#encoding=utf8
'''
Author: [email protected]
Date: 2015/12/04
Content:
生成新闻特征数据
输入:
1、无特征样本数据
2、topic_view的文件
3、文章分词过滤后的文件
输出:
1、特征样本数据
'''
import pdb
from collections import Counter
DATA_DIR = 'tmp_data/topic_train'
MAX_SCORE = 10.0
MIN_WORDS_COUNT = 3
T... | f generate(reader, output_fname, mongo_source):
''''''
print 'Feature: News'
writer = open(output_fname, 'w')
word_topic_dic, topic_num = load_topic_word()
topic_lst = sorted(set(word_topic_dic.values()))
date_word_dic = load_date_word()
title_str = 'label %s\n' % ' '.join(['news_%s' % t f... | 4)
label = int(data[1])
date = data[2]
features = init_features(topic_lst)
tmp_topic_set = scan_topics(date, date_word_dic, word_topic_dic)
if not tmp_topic_set:
raise Exception('Error date: \n%s' % date)
#if label == -1:
# pdb.set_trace()
... |
hedin/vyatta-conf-parser | vyattaconfparser/parser.py | Python | mit | 5,394 | 0 | # coding:utf-8
import re
import sys
if sys.version < '3':
def u(x):
return x.decode('utf-8')
else:
unicode = str
def u(x):
return x
# Matches section start `interfaces {`
rx_section = re.compile(r'^([\w\-]+) \{$', re.UNICODE)
# Matches named section `ethernet eth0 {`
rx_named_section ... | [\w\-\"\./@:=\+]+) \{$', re.UNICODE
)
# Matches simple key-value pair `duplex auto`
rx_value = re.compile(r'^([\w\-]+) "?([^"]+)?"?$', re.UNICODE)
# Matches single value (flag) `disable`
rx_flag = re.compile(r'^([\w\-]+)$', re.UNICODE)
# Matches comments
rx_comment = re.compile(r'^(\/\*).*(\*\/)', re.UNICODE)
| class ParserException(Exception):
pass
def update_tree(config, path, val, val_type=None):
t = config
for item in path:
if list(item.keys())[0] not in t:
try:
t[list(item.keys())[0]] = {}
except TypeError:
break
t = t.get(list(item.k... |
npuichigo/ttsflow | third_party/tensorflow/tensorflow/contrib/distributions/python/kernel_tests/sample_stats_test.py | Python | apache-2.0 | 9,019 | 0.005987 | # 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 applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing perm... | ort absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.distributions.python.ops import sample_stats
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
from tensorflow.python.platform import test
rng ... |
dhess/lobbyists | lobbyists/tests/test_import_issues.py | Python | gpl-3.0 | 17,052 | 0.001935 | # -*- coding: utf-8 -*-
#
# test_import_issues.py - Test issue importing.
# Copyright (C) 2008 by Drew Hess <[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 ... | fense Appropriations-Navy, Army & SOCOM R&D\nH.R.1585 & S.1547 FY08 Defense Authorizations-Navy, Army & SOCOM R& | D\nH.R.2638 & S.1644 FY08 DHS AppropriationsBill-CRP')
row = rows.pop()
self.failUnlessEqual(row['id'], 13)
self.failUnlessEqual(row['code'],
'DEFENSE')
self.failUnlessEqual(row['specific_issue'],
'DEFENSE AUTHORIZATION, DEFENSE ... |
rishig/zulip | zerver/tornado/application.py | Python | apache-2.0 | 1,268 | 0.003155 |
import atexit
import tornado.web
from django.conf import settings
from zerver.tornado import autoreload
from zerver.lib.queue import get_queue_client
from zerver.tornado.handlers import AsyncDjangoHandler
from zerver.tornado.socket import get_sockjs_router
def setup_tornado_rabbitmq() -> None: # nocoverage
# W... | t_queue_client()
atexit.register(lambda: queue_client.close())
autoreload.add_reload_hook(lambda: queue_client.close())
def create_tornado_application(port: int) -> tornado.web.Application:
urls = (
r"/notify_tornado",
r"/json/events",
r"/api/v1/events",
r"/api/v1/ev... | ternal",
)
# Application is an instance of Django's standard wsgi handler.
return tornado.web.Application(([(url, AsyncDjangoHandler) for url in urls] +
get_sockjs_router(port).urls),
debug=settings.DEBUG,
... |
satoken/centroid-rna-package | python/CentroidFold.py | Python | gpl-2.0 | 5,989 | 0.003506 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.7
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (2, 6, 0):
def swig_import_helper():
from os.path imp... | return
method = class_type.__swig_setmethods__.get(name, None)
if method:
return method(self, value)
if (not static):
if _newclass:
object.__setattr__(self, name, value)
else:
self.__dict__[name] = value
else:
raise AttributeError("You ... | r(self, class_type, name, value):
return _swig_setattr_nondynamic(self, class_type, name, value, 0)
def _swig_getattr_nondynamic(self, class_type, name, static=1):
if (name == "thisown"):
return self.this.own()
method = class_type.__swig_getmethods__.get(name, None)
if method:
return m... |
ckelly/pyomniar | pyomniar/parsers.py | Python | mit | 1,440 | 0.003472 |
from pyomniar.utils import import_simplejson
from pyomniar.error import OmniarError
class Parser(object):
def parse(self, method, payload):
"""
Parse the response payload and return the result.
Returns a tuple that contains the result data and the cursors
(or None if not present).... | , payload):
"""
Parse the error message from payload.
If unable to parse the message, throw an exception
and default error message will be used.
"""
raise NotImplementedError
class JSONParser(Parser):
payload_format = 'json'
def __init__(self):
... | son = self.json_lib.loads(payload)
except Exception, e:
raise OmniarError('Failed to parse JSON payload: %s' % e)
return json
def parse_error(self, payload):
error = self.json_lib.loads(payload)
if error.has_key('error-reason'):
return error['error-reason']
... |
arju88nair/projectCulminate | venv/lib/python3.5/site-packages/lazy_object_proxy/compat.py | Python | apache-2.0 | 196 | 0 | import sys
PY2 = sys.vers | ion_info[0] == 2
PY3 = sys.version_info[0] == 3
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
return meta("NewBase", bases, {} | )
|
maximmaxim345/Sheep-it-blender-plugin | splinter/request_handler/status_code.py | Python | gpl-3.0 | 732 | 0.001366 | # -*- coding: utf-8 -*-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
class StatusCode(object):
def __init__(self, status_code, reason):
| #: A message for the response (example: Success)
self.reason = reason
#: Code of the response (example: 200)
self.code = status_code
def __eq__(self, other):
return self.code == other
def __str__(self):
return "{} - {}".format(self.code, self.reason)
def is... | the response was succeed, otherwise, returns ``False``.
"""
return self.code < 400
|
mnunberg/yobot | py/gui/agent_connect_dlg.py | Python | gpl-3.0 | 2,632 | 0.004179 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'agent_connect_dlg.ui'
#
# Created: Tue Oct 12 14:22:17 2010
# by: PyQt4 UI code generator 4.7.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_Dialog(object):
def setupUi(self, Di... | Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("Dialog", "Agent", None, QtGui.QApplication.UnicodeUTF8))
self.disconnect_from_server.setText(QtGui.QApplication.translate("Dialog", "Disconnect Clients from server", None, QtGui.QApplication.Unicod... | )
Dialog = QtGui.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
|
peterayeni/django-kong-admin | setup.py | Python | bsd-3-clause | 1,630 | 0.001227 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import kong_admin
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
version = kong_admin.__version__
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
os.system('python setu... | em("git push --tags")
sys.exit()
readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')
setup(
name='django-kong-admin',
version=version,
description="""A reusable Django App to manage a Kong service (http://getkong.org)""",
long_description=readme + ... | b.com/vikingco/django-kong-admin',
packages=[
'kong_admin',
],
include_package_data=True,
install_requires=[
],
license="BSD",
zip_safe=False,
keywords='django-kong-admin',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Framework :: Django',
'In... |
zbigniewwojna/text-rcnn | core/preprocessor.py | Python | apache-2.0 | 77,352 | 0.003633 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | e.
# ==============================================================================
"""Preprocess images and bounding boxes for detection.
We perform two sets of operations in preprocessing stage:
(a) operations that are applied to both training and testing data,
(b) operations that are applied only to training data ... | t of inputs,
e.g. an image and bounding boxes,
performs an operation on them, and returns them.
Some examples are: randomly cropping the image, randomly mirroring the image,
randomly changing the brightness, contrast, hue and
randomly jittering the bounding boxes.
The preprocess f... |
googlei18n/glyphsLib | tests/builder/designspace_roundtrip_test.py | Python | apache-2.0 | 2,834 | 0.000353 | # coding=UTF-8
#
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this fi | le except in complianc | e 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 i... |
Yuvv/LearnTestDemoTempMini | py-django/DataBackup/ops/credentials.py | Python | mit | 3,202 | 0.000625 | #!/usr/bin/env python
# import keystoneclient.v2_0.client as ksclient
# import glanceclient.v2.client as glclient
# import novaclient.client as nvclient
# import neutronclient.v2_0.client as ntclient
# import cinderclient.v2.client as cdclient
# import swiftclient.client as sftclient
__author__ = 'Yuvv'
OS_PROJECT_D... | ft_credits():
cred = dict()
cred['user'] = OS_USERNAME
cred['key'] = OS_PASSWORD
cred['authurl'] = OS_AUTH_URL
return cred
'''
+----------------------------------+----------+--------------+
| ID | Name | Type |
+----------------------------------+---------... | df3ebe9deb745 | swift | object-store |
| 8e185002e3fe4028bda5c6cd910d31f6 | nova | compute |
| aaf1a49b4a1e463990880ddf9c8fb658 | glance | image |
| b3600985814247558a289c332ad62f09 | keystone | identity |
| bc4d28242d3a466ebce7663b28465a99 | neutron | network |
| cb799b0f7447401fb15821cf... |
andybab/Impala | tests/shell/test_shell_interactive.py | Python | apache-2.0 | 9,064 | 0.008164 | #!/usr/bin/env python
# encoding=utf-8
# Copyright 2014 Cloudera 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 app... | ltiline queries are p | reserved when they're read back from history.
Additionally, also test that comments are preserved.
"""
# regex for pexpect, a shell prompt is expected after each command..
prompt_regex = '.*%s:2100.*' % socket.getfqdn()
# readline gets its input from tty, so using stdin does not work.
child_proc... |
lahwran/distributed-crawler | crawler/central.py | Python | mit | 7,864 | 0.000127 | import json
import random
import urlparse
import re
import itertools
from collections import deque
from twisted.internet.protocol import Factory
from twisted.web.server import Site
from klein import Klein
from crawler import util
class Job(object):
def __init__(self, job_id):
self.queue = deque()
... | r url in urls:
print
print "adding url", repr(url), type(url)
print
if type(url) == | unicode:
print "Unicode string!"
url = url.encode("utf-8")
job.add_url(url)
self.coordinator._broadcast(job)
return json.dumps(job.id) + '\n'
def _job_status_info(self, job):
return {
"crawled_urls": {
"finished": job.... |
croxis/SpaceDrive | spacedrive/renderpipeline/samples/download_samples.py | Python | mit | 1,629 | 0.002455 | """
RenderPipeline
Copyright (c) 2014-2016 tobspr <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in | the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of t | he Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRE... |
mikel-egana-aranguren/SADI-Galaxy-Docker | galaxy-dist/lib/galaxy/webapps/galaxy/controllers/requests_admin.py | Python | gpl-3.0 | 47,292 | 0.021885 | from __future__ import absolute_import
from galaxy.web.base.controller import *
from galaxy.web.framework.helpers import time_ago, iff, grids
from galaxy.model.orm import *
from galaxy import model, util
from galaxy.web.form_builder import *
from .requests_common import RequestsGrid, invalid_id_redirect
from galaxy im... | action='view_request_type',
**kwd ) )
i | f operation == "delete":
return trans.response.send_redirect( web.url_for( controller='requests_common',
action='delete_request',
cntrller='requests_admin',
... |
ecell/ecell3 | ecell/frontend/model-editor/ecell/ui/model_editor/ClassEditorWindow.py | Python | lgpl-3.0 | 4,556 | 0.017779 | #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
# This file is part of the E-Cell System
#
# Copyright (C) 1996-2016 Keio University
# Copyright (C) 2008-2016 RIKEN
# Copyright (C) 2005-2009 The Molecular Sciences Institute
#
#:::::::::::::::::::::::::::::::::::::::... | rlist
self.theClassList = ClassList( self, self['ClassListFrame'] )
# add stepperpropertylist
self.theClassPropertyList = ClassEditor( self, self['ClassPropertyFrame'] )
# add signal handlers
# self.addHandlers({ })
self.theClassList.update()
classList = self.t... | if len(classList) == 0:
aClassList = []
else:
aClassList = [ classList[0] ]
self.selectStepper( aClassList )
def updateEntityList ( self ):
if not self.exists():
return
self.theClassList.update( )
self.updatePropertyList( )
d... |
malaterre/ITK | Modules/Core/GPUCommon/wrapping/test/itkGPUImageTest.py | Python | apache-2.0 | 5,250 | 0.005524 | #==========================================================================
#
# Copyright NumFOCUS
#
# 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/l... | ".format(dest.GetPixel(idx)))
kernel_manager.SetKernelArgWithImage(kernel_mult, 0, srcA.GetGPUDataManager());
kernel_manager.SetKernelArgWithImage(kernel_mult, 1, srcB.GetGPUDataManager());
kernel_manager.SetKernelArgWithImage(kernel_mult, | 2, dest.GetGPUDataManager());
kernel_manager.SetKernelArgWithUInt(kernel_mult, 3, number_of_elements);
kernel_manager.LaunchKernel2D(kernel_mult, width, height, 16, 16);
print("------------------")
print("After GPU kernel execution")
print("SrcA : {0}".format(srcA.GetPixel(idx)))
print("SrcB : {0}".format(srcB.GetPix... |
sketchfab/osgexport | blender-2.5/exporter/osg/osgobject.py | Python | gpl-2.0 | 48,200 | 0.002095 | # -*- python-indent: 4; coding: iso-8859-1; mode: python -*-
# Copyright (C) 2008 Cedric Pinson, Jeremy Moles
#
# 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, o... | ass()))
Object.serializeContent(self, output)
output.write(self.encode("$#Name %s\n" % json.dumps(self.key)))
output.write(self.encode("$#Value %s\n" % json.dumps(self.value)))
output.write(self.encode("$}\n"))
class DefaultUserDataContainer(Object):
def __init__(self, *args, **k... | ef append(self, value):
self.value.append(value)
def className(self):
return "DefaultUserDataContainer"
def serialize(self, output):
output.write(self.encode("$%s {\n" % self.getNameSpaceClass()))
Object.serializeContent(self, output)
self.serializeContent(output)
... |
ghchinoy/tensorflow | tensorflow/python/keras/wrappers/scikit_learn_test.py | Python | apache-2.0 | 5,719 | 0.010316 | # 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... | ras.models.Sequential()
model.add(keras.layers.Dense(INPUT_DIM, input_shape=(INPUT_DIM,)))
model.add(keras.layers.Activation('relu'))
model.add(keras.layers.Dense(hidden_dim))
model.add(keras.layers.Activ | ation('relu'))
model.add(keras.layers.Dense(NUM_CLASSES))
model.add(keras.layers.Activation('softmax'))
model.compile(
optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])
return model
def assert_classification_works(clf):
np.random.seed(42)
(x_train, y_train), (x_test, _) = testi... |
AadityaJ/CodeMonk | Searching/cm3.py | Python | mit | 388 | 0.085052 | t = int(raw_input())
while t>0:
t = t - 1
curma = 0
n = int(raw_input())
arr1 = map(int, raw_input().split())
arr2 = map(int, raw_input().split())
for i in xrange(n):
low, high, pos = 0 | , n - 1, -1
while low<=high:
mid = (low + high) / 2
if arr2[mid] >= arr1[i]:
pos = mid
low = mid + 1
else:
high = mid - 1
curma = max (curma | , pos - i)
prilnt curma |
b12io/orchestra | orchestra/migrations/0024_auto_20160325_1916.py | Python | apache-2.0 | 1,224 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.utils.timezone
from django.db import migrations
from django.db import models
class Migration(migrations.Migration):
dependencies = [
('orchestra', '0023_assignment_failed'),
]
operations = [
migrations.AddFiel... | name='created_at',
fi | eld=models.DateTimeField(default=django.utils.timezone.now),
),
migrations.AddField(
model_name='workflowversion',
name='created_at',
field=models.DateTimeField(default=django.utils.timezone.now),
),
]
|
VWApplications/VWCourses | forum/migrations/0001_initial.py | Python | mpl-2.0 | 2,693 | 0.004836 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-06 21:26
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import taggit.managers
class Migration(migrations.Migration):
initial = True
dependenci... | ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Criado em')),
('updated_at', models.DateTimeField(auto_now=True, verbose_name='Modificado em')),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='replies', to=settings.AUTH_US... | ing': ['-correct', 'created_at'],
},
),
migrations.CreateModel(
name='Topic',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100, verbose... |
spektom/incubator-airflow | airflow/contrib/hooks/slack_webhook_hook.py | Python | apache-2.0 | 1,156 | 0.00173 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | t
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governi... | use `airflow.providers.slack.hooks.slack_webhook`."""
import warnings
# pylint: disable=unused-import
from airflow.providers.slack.hooks.slack_webhook import SlackWebhookHook # noqa
warnings.warn(
"This module is deprecated. Please use `airflow.providers.slack.hooks.slack_webhook`.",
DeprecationWarning, st... |
amitsela/incubator-beam | sdks/python/apache_beam/utils/path_test.py | Python | apache-2.0 | 2,494 | 0.004411 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | path.join.side_effect = _gen_fake_join('/')
self.assertEqual('/tmp/path/to/file', path.join('/tmp/path', 'to', 'file'))
self.assertEqual('/tmp/path/to/file', path.join('/tmp/path', 'to/file'))
@mock.patch('apache_beam.utils.path.os')
def test_windows_path(self, *unused_mocks):
# Test joining of Windows... | ual(r'C:\tmp\path\to\file',
path.join(r'C:\tmp\path', 'to', 'file'))
self.assertEqual(r'C:\tmp\path\to\file',
path.join(r'C:\tmp\path', r'to\file'))
if __name__ == '__main__':
unittest.main()
|
mc10/project-euler | problem_34.py | Python | mit | 561 | 0.003565 | '''
Problem 34
@author: Kevin Ji
'''
FACTORIALS = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
def factorial(number):
return FACTORIALS[number]
def is_curious_num(number):
temp_num = number
curious_sum = 0
while temp_num > 0:
curious_sum += factorial(temp_num % | 10)
temp_num //= 10
return number == curious_sum
# Tests
#print(is_curious_num(145)) # True
#print(is_curious_num(100)) # False
cur_sum = 0
for num in range(3, 1000000 | ):
if is_curious_num(num):
cur_sum += num
print(cur_sum)
|
mick-d/nipype_source | nipype/interfaces/freesurfer/base.py | Python | bsd-3-clause | 4,569 | 0.000219 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""The freesurfer module provides basic functions for interfacing with
freesurfer tools.
Currently these tools are supported:
* Dicom2Nifti: using mri_convert
* Resample: using mri_convert
Exam... | CommandLineInputSpec, isdefined)
cl | ass Info(object):
""" Freesurfer subject directory and version information.
Examples
--------
>>> from nipype.interfaces.freesurfer import Info
>>> Info.version() # doctest: +SKIP
>>> Info.subjectsdir() # doctest: +SKIP
"""
@staticmethod
def version():
"""Check for free... |
jh23453/privacyidea | doc/installation/system/pimanage/conf.py | Python | agpl-3.0 | 9,178 | 0.006102 | # -*- coding: utf-8 -*-
#
# pi-manage documentation build configuration file, created by
# sphinx-quickstart on Sun Oct 11 19:10:09 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
#... | ify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the proje | ct.
project = u'pi-manage'
copyright = u'2015, privacyIDEA'
author = u'privacyIDEA'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '2.8'
# The full version... |
khushboo9293/mailman | src/mailman/rest/tests/test_api.py | Python | gpl-3.0 | 2,194 | 0.000456 | # Copyright (C) 2015 by the Free Software Foundation, Inc.
#
# This file is part of GNU Mailman.
#
# GNU Mailman 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 opt... | pi(url)
self.assertEqual(json['mailman_version'], system.mailman_version)
self.assertEqual(json['python_version'], system.python_version)
self.assertEqual(json['api_version'], '3.1')
self.assertEqual(json['self_link'], new)
def test_api_30(self):
# API version 3.0 is still s... | ['mailman_version'], system.mailman_version)
self.assertEqual(json['python_version'], system.python_version)
self.assertEqual(json['api_version'], '3.0')
self.assertEqual(json['self_link'], new)
def test_bad_api(self):
# There is no API version earlier than 3.0.
with self.as... |
szigyi/DAT210x | Module4/assignment5.py | Python | mit | 2,886 | 0.010742 | import math
import pandas as pd
import numpy as np
from scipy import misc
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
import matplotlib.pyplot as plt
# Look pretty...
# matplotlib.style.use('ggplot')
plt.style.use('ggplot')
def Plot2D(T, title, x, y):
# This method picks a bunch of random samples (im... | #pic = pic[::2, ::2]
pic | = pic.values.reshape(-1, 3)
samples.append(pic)
#
# Optional: Resample the image down by a factor of two if you
# have a slower computer. You can also convert the image from
# 0-255 to 0.0-1.0 if you'd like, but that will have no
# effect on the algorithm's results.
#
df = pd.DataFrame.from_records(samples)
prin... |
globocom/database-as-a-service | dbaas/maintenance/async_jobs/remove_instance_database.py | Python | bsd-3-clause | 874 | 0 | from mainte | nance.async_jobs import BaseJob
from maintenance.models import RemoveInstanceDatabase
__all__ = ('RemoveInstanceDatabase',)
class RemoveInstanceDatabaseJob(BaseJob):
step_manger_class = RemoveInstanceDatabase
get_steps_method = 'remove_readonly_i | nstance_steps'
success_msg = 'Instance removed with success'
error_msg = 'Could not remove instance'
def __init__(self, request, database, task, instance, since_step=None,
step_manager=None, scheduled_task=None,
auto_rollback=False, auto_cleanup=False):
super(Remov... |
romanz/python-trezor | trezorlib/tests/device_tests/test_cancel.py | Python | lgpl-3.0 | 2,032 | 0 | # This file is part of the Trezor project.
#
# Copyright (C) 2012-2018 SatoshiLabs and contributors
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.
#
# This library is distrib... | ncel_message_via_cancel(client, message):
resp = client.call_raw(message)
assert isinstance(resp, m.ButtonRequest)
client.transport.write(m.ButtonAck())
clie | nt.transport.write(m.Cancel())
resp = client.transport.read()
assert isinstance(resp, m.Failure)
assert resp.code == m.FailureType.ActionCancelled
@setup_client()
@pytest.mark.parametrize(
"message",
[
m.Ping(message="hello", button_protection=True),
m.GetAddress(
add... |
fhdk/eordre-app.pyqt | util/worker.py | Python | agpl-3.0 | 8,857 | 0.002939 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright: Frede Hundewadt <echo "ZmhAdWV4LmRrCg==" | base64 -d>
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
#
# code from https://stackoverflow.com/a/41605909
#
"""Worker module"""
import csv
from PyQt5.QtCore import QObject, pyqtS... | emit(self.__thread_id)
@pyqtSlot(name="import_order_line | s_csv")
def import_orderlines_csv(self, orderlines, filename, header):
"""
Import lines using csv file
:param orderlines: OrderLine() class
:param filename: filename to read
:param header: bool if first line is header
:return:
"""
filename.encode("utf8... |
RentennaDev/partial | partial/request.py | Python | mit | 325 | 0.009231 | from werkzeug.contrib.securecookie import SecureCookie
from werkzeug.utils import cached_property
from werkzeug.wrappers import BaseRequest
from part | ial import scanner
class Request(BaseRequest):
@ | cached_property
def session(self):
return SecureCookie.load_cookie(self, secret_key=scanner.CONFIG['SECRET']) |
farooqsheikhpk/Aspose.BarCode-for-Cloud | Examples/Python/generating-saving/cloud-storage/generate-barcode-and-save-asposecloudstorage.py | Python | mit | 1,910 | 0.013613 | import asposebarcodecloud
from asposebarcodecloud.BarcodeApi import BarcodeApi
from asposebarcodecloud.BarcodeApi import ApiException
import asposestoragecloud
from asposestoragecloud.StorageApi import StorageApi
from asposestoragecloud.StorageApi import ResponseMessage
import ConfigParser
config = Config... | rser.ConfigParser()
config.readfp(open(r'../../data/config.properties'))
apiKey = config.get('AppConfig', 'api_key')
appSid = config.get('AppConfig', 'app_sid')
out_folder = config.get('AppC | onfig', 'out_folder')
data_folder = "../../data/" #resouece data folder
#ExStart:1
#Instantiate Aspose.Storage API SDK
storage_apiClient = asposestoragecloud.ApiClient.ApiClient(apiKey, appSid, True)
storageApi = StorageApi(storage_apiClient)
#Instantiate Aspose.Barcode API SDK
api_client = asposebarcodeclou... |
Norin-Radd/plugin.video.boilerroom | resources/lib/youtubewrapper.py | Python | gpl-2.0 | 9,753 | 0.042346 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Author: Norin (copied it)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later versio... | _page)))
video_ids = []
if returnedVideos:
for video in returnedVideos:
videoid = video["contentDetails"]["videoId"]
video_ids.append(videoid)
video_ids = ','.join(video_ids)
url_api = 'https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id='+video_ids+'&key='+youtube_api_key
raw = ... | sp["items"]
for video in returnedVideos:
title = video["snippet"]["title"]
plot = video["snippet"]["description"]
aired = video["snippet"]["publishedAt"]
thumb = video["snippet"]["thumbnails"]["high"]["url"]
videoid = video["id"]
#process duration
duration_string = video["contentDetails"]["dur... |
pablorecio/djangae | djangae/db/backends/appengine/base.py | Python | bsd-3-clause | 17,365 | 0.002361 | #STANDARD LIB
import datetime
import decimal
import warnings
#LIBRARIES
from django.conf import settings
from django.db.backends import (
BaseDatabaseOperations,
BaseDatabaseClient,
BaseDatabaseIntrospection,
BaseDatabaseWrapper,
BaseDatabaseFeatures,
BaseDatabaseValidation
)
try:
from dja... | except (TypeError, ValueError):
pass
value = get_datastore_key(model, value)
else:
value = get_datastore_key(model, value)
return value
de | f prep_lookup_decimal(self, model, value, field):
return self.value_to_db_decimal(value, field.max_digits, field.decimal_places)
def prep_lookup_date(self, model, value, field):
if isinstance(value, datetime.datetime):
return value
return self.value_to_db_date(value)
def p... |
lukasmerten/GitPlayground | UsefulPythonScripts/Ferrie2007_Innen.py | Python | mit | 3,648 | 0.052906 | import numpy as np
import matplotlib.pyplot as plt
import pylab
import scipy.integrate as integrate
x= -500
y= -500
z = 10
# Konstanten fuer CMZ
xc =-50 # Position Mitte in allg Koordinaten
yc = 50
TettaC = 70
#Konstanten fuer DISK
alpha = 13.5
beta = 20.
TettaD = 48.5
# Abmessungen in CMZ Koordinaten
XMAX=250
... | taD))
zT = z*(cos(alpha)*sin(beta)*sin(TettaD) -sin(alpha)*sin(TettaD))
return -xT+yT+zT
def DISK_Z_Trafo(x,y,z):
xT = x*sin(beta)
yT = y*sin(alpha)*cos(beta)
zT = z*cos(al | pha)*cos(beta)
return xT+yT+zT
#Mollekularer Wasserstoff im CMZ,
def n_H2_CMZ(x0,y0,z0): # Eingabe in Urspruenglichen koordinaten
x = CMZ_X_Trafo(x0,y0)
y = CMZ_Y_Trafo(x0,y0)
XY_Help = ((np.sqrt(x**2+(2.5*y)**2)-XC)/LC)**4
return 150*np.exp(-XY_Help)*np.exp(-(z0/HC)**2)
#Atomarer Wasserstoff im CMZ
def n_H... |
goller/pynsq | tests/test_writer.py | Python | mit | 892 | 0 | from __future__ import absolute_import
import nsq
import unittest
class WriterUnitTest(unittest.TestCase):
def setUp(self):
super(WriterUnitTest, self).setUp()
def test_constructor(self):
name = 'test'
reconnect_interval = 10.0
writer = nsq.Writer(nsqd_tcp_addresses=['127.0.... | name=name)
self.assertEqual(writer.name, name)
self.assertEqual(0, len(writer.conn_kwargs))
self.assertEqual(writer.reconnect_interval, re | connect_interval)
def test_bad_writer_arguments(self):
bad_options = dict(foo=10)
self.assertRaises(
AssertionError,
nsq.Writer,
nsqd_tcp_addresses=['127.0.0.1:4150'],
reconnect_interval=15.0,
name='test', **bad_options)
|
mrmuxl/keops | keops/modules/comments/apps.py | Python | agpl-3.0 | 403 | 0.002481 |
from django.utils.translation import ugettext_lazy as _
app_info = {
'name': 'comments',
'author': 'Katrid',
'website': 'http://katrid.com',
'short_description': 'Enterprise Social Network',
'description': _('Comments, Discussions, Mailing List, News, Document Followers'),
' | dependencies': ['keops.module | s.contact'],
'category': _('Communication'),
'version': '0.2',
}
|
neillc/zookeepr | zkpylons/controllers/product_category.py | Python | gpl-2.0 | 5,696 | 0.002633 | import logging
from pylons import request, response, session, tmpl_context as c
from zkpylons.lib.helpers import redirect_to
from pylons.decorators import validate
from pylons.decorators.rest import dispatch_on
from formencode import validators, htmlfill, ForEach, Invalid
from formencode.variabledecode import NestedV... | meta.Session.commit()
h.flash("Category created")
redirect_to(action='view', id=c.product_category.id)
def view(self, id):
c.product_category = ProductCategory.find_by_id(id)
return render('/product_category/view.mako')
def stats(self, id):
c.can_edit = True
... | ndex(self):
c.can_edit = True
c.product_category_collection = ProductCategory.find_all()
return render('/product_category/list.mako')
@dispatch_on(POST="_edit")
def edit(self, id):
c.product_category = ProductCategory.find_by_id(id)
defaults = h.object_to_defaults(c.pro... |
NikNitro/Python-iBeacon-Scan | sympy/printing/printer.py | Python | gpl-3.0 | 9,328 | 0.000536 | """Printing subsystem driver
SymPy's printing system works the following way: Any expression can be
passed to a designated Printer who then is responsible to return an
adequate representation of that expression.
The basic concept is the following:
1. Let the object print itself if it knows how.
2. Take the best f... | expr):
"""Returns printer's representation for expr (as a string)"""
return self._str(self._print(expr))
def _print(self, expr, *args, **kwargs):
"""Internal dispatcher
Tries the following concepts to print an expression:
1. Let the object print itself if it knows how.... | ck use the emptyPrinter method for the printer.
"""
self._print_level += 1
try:
# If the printer defines a name for a printing method
# (Printer.printme |
kAlmAcetA/zookeeper_monitor | zookeeper_monitor/zk/__init__.py | Python | mit | 668 | 0.002994 | # -*- coding:utf-8 -*-
"""
Module provides zookeeper abstraction
"""
from .host import Host
from .cluster import Cluster
from .exceptions import HostBaseError, HostConnec | tionTimeout, HostSetTimeoutTypeError
from .exceptions import HostSetTimeoutValueError, HostInvalidInfo, ZkBaseError
from .exceptions import ClusterHostAddError, ClusterHostDuplicateError, ClusterHostCreateError
__all__ = [
'Host',
'Cluster',
'ZkBaseError',
'HostBaseError',
'HostConnectionTimeout',... | ostSetTimeoutTypeError',
'HostSetTimeoutValueError',
'HostInvalidInfo',
'ClusterHostAddError',
'ClusterHostDuplicateError',
'ClusterHostCreateError'
]
|
kanishkamisra/pokedex | scraper.py | Python | mit | 1,483 | 0.035738 | import requests
import lxml.html as lh
import json
url = 'http://pokemondb.net/pokedex/all'
page = requests.get(url)
doc = lh.fromstring(page.content)
#Store data from the table into a list
elements = doc.xpath('//tr')
col = []
i=0
# Store headers as tuples with each header being associated with a list
for e in ele... | (word):
list = [x for x in word]
for i in range(1, len(list)):
if list[i].isupper():
list[i] = ' ' + list[i]
new_list = ''.join(list).split(' ')
if len(new_list) > 1:
new_list.insert(1,'(')
new_list.append(')')
return ' '.join(new_list)
def breaks(word):
list = [x for x in word]
for i in range(1, len(l... | t[i] = ' ' + list[i]
new_list = ''.join(list).split(' ')
return new_list
for data in data_list:
data['Name'] = brackets(data['Name'])
data['Type'] = breaks(data['Type'])
# Dump to json
with open('pokemondata.json', 'wb') as jsonfile:
json.dump(data_list, jsonfile)
print 'Data saved to json!'
|
adamlincoln/pokersim | src/pokersim/__init__.py | Python | gpl-3.0 | 1,480 | 0.006081 | import argparse
from pokersim.Table import Table
from pokersim.Player import Player
from pokersim.Recorder import Recorder
rec = Recorder()
parser = argparse.ArgumentParser(description='Set up a poker game')
#parser.add_argument('-n', '--numplayers', type=int, nargs='?', default=10, help='Number of players')
parser... | s'])
table = Table()
for i in xrange(numplayers):
player = Player(int(args['players'][i][0]), args['players'][i][1])
player.sit(table, i)
for i in xrange(args['numhands']):
| table.deal()
print 'After', args['numhands'], 'hands:'
for player in table.players.values():
print 'Player', player.position, 'has', player.chips, 'chips'
print 'The Table has', table.box, 'chips'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.