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 |
|---|---|---|---|---|---|---|---|---|
richardkiss/pycoinnet | tests/peer/helper.py | Python | mit | 4,885 | 0.004094 | import asyncio
import hashlib
import logging
from pycoinnet.peer.BitcoinPeerProtocol import BitcoinPeerProtocol
from pycoinnet.helpers.standards import initial_handshake, version_data_for_peer
from pycoinnet.PeerAddress import PeerAddress
from pycoin import ecdsa
from pycoin.block import Block
from pycoin.encoding im... | col_factory=protocol_factory, port=port)
| except Exception as OSError:
port += 1
return abstract_server, port, future_peer
server, port, future_peer = asyncio.get_event_loop().run_until_complete(asyncio.Task(run_listener()))
@asyncio.coroutine
def run_connector(port):
def protocol_factory():
re... |
YongseopKim/crosswalk-test-suite | webapi/tct-csp-w3c-tests/csp-py/csp_default-src_cross-origin_font_blocked-manual.py | Python | bsd-3-clause | 2,607 | 0.002685 | def main(request, response):
_URL = request.url
_CSSURL = _URL[:_URL.index('/csp')+1] +"csp/support/w3c/CanvasTest.ttf"
response.headers.set("Content-Security-Policy", "default-src http://www.tizen.com 'unsafe-inline'")
response.headers.set("X-Content-Security-Policy", "default-src http://www.tizen.com ... | , "default-src http://www.tizen.com 'unsafe-inline'")
return """<!DOCTYPE html>
<!--
Copyright (c) 2013 Intel Corporation.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided | that the following conditions are met:
* Redistributions of works must retain the original copyright notice, this list
of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the original copyright notice,
this list of conditions and the following disclaimer in the documentatio... |
xqms/catkin_tools | catkin_tools/verbs/catkin_build/cli.py | Python | apache-2.0 | 9,623 | 0.003118 | # Copyright 2014 Open Source Robotics Foundation, 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... | om catkin_tools.context import Context
from catkin_tools.terminal_color import set_color
from catkin_tools.metadata import get_metadata
from catkin_tools.metadata import update_metadata
from catkin_tools.resultspace import load_resultspace_environment
from .color import clr
from .common import get_build_type
from... | solated_workspace
from .build import determine_packages_to_be_built
from .build import topological_order_packages
from .build import verify_start_with_option
def prepare_arguments(parser):
parser.description = "Build one or more packages in a catkin workspace.\
This invokes `CMake`, `make`, and optionally `m... |
graphicore/fontbakery | Lib/fontbakery/profiles/notofonts.py | Python | apache-2.0 | 6,244 | 0.008808 | import os
from fontbakery.profiles.universal import UNIVERSAL_PROFILE_CHECKS
from fontbakery.checkrunner import Section, WARN, PASS #, INFO, ERROR, SKIP, FAIL
from fontbakery.callable import check #, disable
from fontbakery.message import Message
from fontbakery.fonts_profile import profile_factory
from fontbakery.con... | WindowsEncodingID,
UnicodeEncodingID,
MacintoshEncodingID)
from .googlefonts_conditions import * # pylint: disable=wildcard-import,unused-wildcard-import
profile_imports = ('fontbakery.profiles.univer | sal',) # Maybe this should be .googlefonts instead...
profile = profile_factory(default_section=Section("Noto Fonts"))
CMAP_TABLE_CHECKS = [
'com.google.fonts/check/cmap/unexpected_subtables',
]
OS2_TABLE_CHECKS = [
'com.google.fonts/check/unicode_range_bits',
]
# Maybe this should be GOOGLEFONTS_PROFILE_CHE... |
ahwmrklas/warpWarp | gamepane.py | Python | gpl-3.0 | 2,141 | 0.004671 | # display Game information to create a game on a server
#
import tkinter as TK
import client
from cmds import warpWarCmds
class gamePane(TK.Frame):
# PURPOSE:
# RETURNS:
def __init__(self, master, owner, **kwargs):
TK.LabelFrame.__init__(self, master, text="Game Options", **kwargs)
self.... | self.gameName.config(state="disabled")
else:
self.createBtn.config(state="disabled")
self.gameName.config(stat | e="disabled")
|
eduNEXT/edx-platform | cms/djangoapps/contentstore/tests/test_i18n.py | Python | agpl-3.0 | 10,725 | 0.002432 | """
Tests for validate Internationalization and Module i18n service.
"""
import gettext
from unittest import mock, skip
from django.utils import translation
from django.utils.translation import get_language
from xmodule.modulestore.django import ModuleI18nService
from xmodule.modulestore.tests.django_utils import TE... | ettext has been put back into place
self.assertEqual(i18n_service.ugettext(self.test_language), 'dummy language')
@mock.patch('django.utils.translation.ugettext', mock.Mock(return_value='XYZ-TEST-LANGUAGE'))
@mock.patch('dj | ango.utils.translation.gettext', mock.Mock(return_value='XYZ-TEST-LANGUAGE'))
def test_django_translator_in_use_with_empty_block(self):
"""
Test: Django default translator should in use if we have an empty block
"""
i18n_service = ModuleI18nService(None)
self.assertEqual(i18n... |
petterreinholdtsen/cinelerra-hv | thirdparty/OpenCV-2.3.1/samples/python/dft.py | Python | gpl-2.0 | 3,966 | 0.024458 | #!/usr/bin/python
import cv2.cv as cv
import sys
import urllib2
# Rearrange the quadrants of Fourier image so that the origin is at
# the image center
# src & dst arrays of equal size & type
def cvShiftDFT(src_arr, dst_arr ):
size = cv.GetSize(src_arr)
dst_size = cv.GetSize(dst_arr)
if dst_size != size:
... | arr):
if( not cv.CV_ARE_TYPES_EQ( q1, d1 )):
cv. | Error( cv.CV_StsUnmatchedFormats, "cv.ShiftDFT", "Source and Destination arrays must have the same format", __FILE__, __LINE__ )
cv.Copy(q3, d1)
cv.Copy(q4, d2)
cv.Copy(q1, d3)
cv.Copy(q2, d4)
else:
cv.Copy(q3, tmp)
cv.Copy(q1, q3)
cv.Copy(tm... |
prasadtalasila/IRCLogParser | lib/analysis/network.py | Python | gpl-3.0 | 39,848 | 0.008507 | import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
import re
import networkx as nx
from networkx.algorithms.components.connected import connected_components
from datetime import date
import lib.util as util
import csv
import numpy as np
import lib.config as config
from it... | S):
if(len(conversation[index]) == 3 and conversation[index][0] >= config.THRESHOLD_MESSAGE_NUMBER_GRAPH):
if len(conversation[index][1]) >= config.MINIMUM_NICK_LENGTH and len(conversation[index][2]) >= | config.MINIMUM_NICK_LENGTH:
message_graph.add_edge(util.get_nick_representative(nicks, nick_same_list, conversation[index][1]), util.get_nick_representative(nicks, nick_same_list, conversation[index][2]), weight=conversation[index][0])
return message_graph
for day_content_all_channels... |
kernsuite-debian/obit | python/ZernikeUtil.py | Python | gpl-2.0 | 4,098 | 0.006833 | """
Python utility package for Zernike polynomials
This utility package supplies Zernike terms and derivatives.
"""
# Python utility package for Zernike polynomials
from __future__ import absolute_import
import Obit
from six.moves import range
# $Id$
#------------------------------------------------------------------... | e on unit circle
y = Y coordinate on unit circle
"""
################################################################
# Error check
if n<1 or n>36:
raise RuntimeError("unsupported Zernike order:"+str(n))
out = [] # initi | alize output
for i in range(0,n):
val = Obit.Zernike(i, x, y);
out.append(val)
return out
# end PZernike
def PZernikeGradX(n, x, y):
""" Determine Zernike gradient in x coefficients for position (x,y)
returns array of n efficients (by order)
n = highest order number (1-r... |
BlindHunter/django | django/http/response.py | Python | bsd-3-clause | 17,980 | 0.001057 | from __future__ import unicode_literals
import datetime
import json
import re
import sys
import time
from email.header import Header
from django.conf import settings
from django.core import signals, signing
from django.core.exceptions import DisallowedRedirect
from django.core.serializers.json import DjangoJSONEncode... | ent_type
@property
def reason_phrase(self):
if self._reason_phrase is not None:
retu | rn self._reason_phrase
# Leave self._reason_phrase unset in order to use the default
# reason phrase for status code.
return responses.get(self.status_code, 'Unknown Status Code')
@reason_phrase.setter
def reason_phrase(self, value):
self._reason_phrase = value
@property
... |
takeshineshiro/nova | nova/tests/functional/v3/test_image_size.py | Python | apache-2.0 | 2,115 | 0 | # Copyright 2012 Nebula, Inc.
# Copyright 2013 IBM Corp.
#
# 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... | ck.compute.contrib.image_size.Image_size')
return f
def test_show(self):
# Get api sample of one single image details request.
image_id = fake.get_valid_image_id()
| response = self._do_get('images/%s' % image_id)
subs = self._get_regexes()
subs['image_id'] = image_id
self._verify_response('image-get-resp', subs, response, 200)
def test_detail(self):
# Get api sample of all images details request.
response = self._do_get('images/detail... |
luci/luci-py | appengine/swarming/swarming_bot/swarmingserver_bot_fake.py | Python | apache-2.0 | 4,446 | 0.011696 | # Copyright 2014 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import base64
import copy
import json
import os
import sys
import threading
BOT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert... | sk_update(self, task_id, data):
with self._loc | k:
self._tasks.setdefault(task_id, []).append(data)
must_stop = self.must_stop
self.has_updated_task.set()
return must_stop
def _add_task_error(self, task_id, data):
# Used by the handler.
with self._lock:
self._task_errors.setdefault(task_id, []).append(data)
|
sxjscience/tvm | python/tvm/relay/testing/resnet_3d.py | Python | apache-2.0 | 10,942 | 0.000731 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | n0")
body = relay.nn.relu(data=body)
# body = relay.nn.max_pool3d(data=body, pool_size=(3, 3), strides=(2, 2), padding=(1, 1),
# layout=data_layout)
for i in range(num_stages):
body = residual_unit(
body,
| filter_list[i + 1],
(1 if i == 0 else 2, 1 if i == 0 else 2, 1 if i == 0 else 2),
False,
name="stage%d_unit%d" % (i + 1, 1),
bottle_neck=bottle_neck,
data_layout=data_layout,
kernel_layout=kernel_layout,
)
for j in range(u... |
plajjan/vrnetlab | sros/docker/launch.py | Python | mit | 15,040 | 0.005053 | #!/usr/bin/env python3
import datetime
import logging
import math
import os
import re
import signal
import sys
import vrnetlab
def handle_SIGCHLD(signal, frame):
os.waitpid(-1, os.WNOHANG)
def handle_SIGTERM(signal, frame):
sys.exit(0)
signal.signal(signal.SIGINT, handle_SIGTERM)
signal.signal(signal.SIGTE... | ([0-9]{2 | })", license)
if m:
self.fake_start_date = "%s%02d" % (m.group(1), int(m.group(2))+1)
except:
raise ValueError("Unable to parse license file")
self.logger.info("License file found for UUID %s with start date %s" % (self.uuid, self.fake_start_date))
class SROS_in... |
zeldin/libsigrokdecode | decoders/spiflash/lists.py | Python | gpl-3.0 | 3,593 | 0.003896 | ##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2015 Uwe Hermann <[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 Li... | enses/>.
##
from collections import OrderedDict
# OrderedDict which maps command IDs to their names and descriptions.
# Please keep this sorted by command ID.
# Don't forget to update 'Ann' in pd.py if you add/remove items here.
cmds = OrderedDict([
(0x01, ('WRSR', 'Wr | ite status register')),
(0x02, ('PP', 'Page program')),
(0x03, ('READ', 'Read data')),
(0x04, ('WRDI', 'Write disable')),
(0x05, ('RDSR', 'Read status register')),
(0x06, ('WREN', 'Write enable')),
(0x0b, ('FAST/READ', 'Fast read data')),
(0x20, ('SE', 'Sector erase')),
(0x2b, ('RDSCUR',... |
loafdog/loaf-src | prog-probs/eight-queens/EightQueens.py | Python | apache-2.0 | 5,123 | 0.013859 | import pdb
from copy import deepcopy
class Board:
board=None
def __init__(self, input_board=None, size=3):
if not input_board:
self.board = [[0]*size for i in range(size)]
else:
self.board = deepcopy(input_board.board)
def size(self):
if not self.board: ret... | nt "ur: col=%d row=%d item=%s" %(col,row,item)
if item[col] == 0: item[col]=1
| col+=1
except IndexError as e:
break
return True
#############################################################################
def findSolution(solutions, board, r, c):
#print "enter %d %d lvl=%s"%(r,c,lvl)
#board.printBoard()
# found a solution
if board.size()... |
SavinaRoja/challenges | Rosalind/Heredity/IPRB.py | Python | unlicense | 3,585 | 0.003347 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Mendel's First Law
Usage:
IPRB.py <input>
IPRB.py (--help | --version)
Options:
-h --help show this help message and exit
-v --version show version and exit
"""
problem_description = """Mendel's First Law
Problem
Probability is the mathematical stud... | k_m_n(inp_file):
with open(inp_file, 'r') as inp:
k, m, n = inp.readline().strip().split(' ')
return float(k), float(m), float(n)
#TODO: Write elegant, general solution to "marbles-in-jar problem"
def calculate(k, m, n):
first_pop = k + m + n
second_pop = first_pop - 1
kk = k / first_pop *... | n / first_pop * (k) / second_pop
mm = m / first_pop * (m - 1) / second_pop
mn = m / first_pop * (n) / second_pop + n / first_pop * (m) / second_pop
nn = n / first_pop * (n - 1) / second_pop
return kk, km, kn, mm, mn, nn
def main():
k, m, n = get_k_m_n(arguments['<input>'])
#k is homozygous do... |
ordinary-developer/lin_education | books/techno/python/programming_python_4_ed_m_lutz/code/chapter_2/08_the_loaded_modules_table/main.py | Python | mit | 183 | 0 | if __name__ == '__main__':
import sys
print(sys.modules)
print(list(sys.modu | les.keys()))
print(sys)
print(sys.m | odules['sys'])
print(sys.builtin_module_names)
|
openpgh/askpgh | askbot/views/users.py | Python | gpl-3.0 | 47,077 | 0.005119 | """
:synopsis: user-centric views for askbot
This module includes all views that are specific to a given user - his or her profile,
and other views showing profile-related information.
Also this module includes the view listing all forum users.
"""
import calendar
import collections
import functools
import datetime
i... | evel_for_user(
request.user
)
except models.Group.DoesNotExist:
raise Http404
i | f group_slug == slugify(group.name):
#filter users by full group memberships
#todo: refactor as Group.get_full_members()
full_level = models.GroupMembership.FULL
memberships = models.GroupMembership.objects.filter(
... |
mohamedhagag/community-addons | openeducat_erp/res_company/__init__.py | Python | agpl-3.0 | 1,091 | 0 | # -*- coding: utf-8 -*-
###############################################################################
#
# Tech-Receptives Solutions Pvt. Ltd.
# Copyright (C) 2009-TODAY Tech-Receptives(<http://www.techreceptives.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the... | ter version.
#
# This program is distr | ibuted 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# ... |
prakharjain09/qds-sdk-py | qds_sdk/account.py | Python | apache-2.0 | 2,789 | 0.000717 | """
The Accounts module contains the base definition for a Qubole account object
"""
from qds_sdk.resource import SingletonResource
from qds_sdk.qubole import Qubole
import argparse
class AccountCmdLine:
@staticmethod
def parsers():
argparser = argparse.ArgumentParser(
prog="qds.py account... | rgument(
"--storage-access-key", dest="acc_key", required=True,
| help="AWS Access Key ID for storage")
create.add_argument(
"--storage-secret-key", dest="secret", required=True,
help="AWS Secret Access Key for storage")
create.add_argument(
"--compute-access-key", dest="compute_access_key", required=True,
help="A... |
Ejhfast/meta | test/test_optimize.py | Python | mit | 606 | 0.014851 | from context import Meta
meta = Meta()
merge_two_dicts = meta.load("http://www.meta-lang.org/snippets/56ee471dc0cb8f7470fbb500")
flatten_list = | meta.load("http://www.meta-lang.org/snippets/56ee45b9c0cb8f7470fbb185")
unordered = meta.load("http://www.meta-lang.org/snippets/56ee4583c0cb8f7470fbb0c5")
dict1 = {x:i for x,i in enumerate(range(0,200))}
dict2 = {x:i for x,i in enumerate(range(0,200))}
# or pass OPT=True python ...
# merge_two_dicts(dict1,dict2)
# ... | ge_two_dicts.optimize2())
# print(flatten_list.optimize2())
print(unordered.optimize2())
|
CSCI1200Course/csci1200OnlineCourse | tests/functional/unit_description.py | Python | apache-2.0 | 2,008 | 0 | # Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | n(assessment.desc | ription, response)
self.assertIn(link.description, response)
|
sahiljain/catapult | third_party/mapreduce/mapreduce/api/map_job/sample_input_reader.py | Python | bsd-3-clause | 3,468 | 0.008074 | #!/usr/bin/env python
"""Sample Input Reader for map job."""
import random
import string
import time
from mapreduce import context
from mapreduce import errors
from mapreduce import operation
from mapreduce.api import map_job
# pylint: disable=invalid-name
# Counter name for number of bytes read.
COUNTER_IO_READ_BYT... | _MSEC = "io-read-msec"
class SampleInputReader(map_job.Inp | utReader):
"""A sample InputReader that generates random strings as output.
Primary usage is to as an example InputReader that can be use for test
purposes.
"""
# Total number of entries this reader should generate.
COUNT = "count"
# Length of the generated strings.
STRING_LENGTH = "string_length"
#... |
kidchenko/playground | python-para-zumbis/Lista 3/Desafios/exercicio1.py | Python | mit | 398 | 0.01005 | resultado = 0
contador = 0
numero = int(input('Digite um numero: '))
while resultado < numero:
resultado = (contador -2) * (contador -1) * contador
if resultado == numero:
print('O numero %d e triangular. %d x %d x %d = %d' % (numero, (contador -2), (contador - 1), contador, numero))
... |
else:
print('O numero %d nao e | triangular')
|
ClearCorp/odoo-clearcorp | sale_order_terms_and_conds/__openerp__.py | Python | agpl-3.0 | 776 | 0 | # -*- coding: utf-8 -*-
# © 2016 ClearCorp
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': 'Sale Order Terms & Conditions',
'version': '1.0',
'category': 'sales',
'sequence': 20,
'summary': '',
'description': """
Add Terms & Conditions t | o the sale order
========================================
""",
'author': 'ClearCorp',
'website': 'http://clearcorp.co.cr',
| 'complexity': 'normal',
'images': [],
'depends': [
'base',
'sale'
],
'data': [
'security/ir.model.access.csv',
'views/sale_order_terms_and_conds_view.xml'
],
'test': [],
'demo': [],
'installable': True,
'auto_install': False,
'application': False... |
steveniemitz/slack-rtm-bot | bot/handlers/dice.py | Python | mit | 559 | 0.012522 | from collections import Counter
import random
from handlers.base import MessageHandler
from util import parse_int
class DiceHandler(MessageHandler):
TRIGGERS = ['dice', 'roll']
HELP = 'roll the given number of dice; default 1'
def handle_message(self, event, query):
times = parse_int(query, default=1)
... | unter = Counter(dice_gen)
return ', '.join('%s: %s' % (k, counter[k]) for k in xra | nge(1, 7))
else:
return ', '.join(map(str, dice_gen))
|
zeitkunst/FluidNexus | FluidNexus/ui/FluidNexusNewMessageUI.py | Python | gpl-3.0 | 8,024 | 0.004736 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'FluidNexus/ui/FluidNexusNewMessage.ui'
#
# Created: Sun Nov 13 17:16:28 2011
# by: PyQt4 UI code generator 4.8.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QStr... | FluidNexusNewMessage.setWindowTitle(QtGui.QApplication.translate("FluidNexusNewMessage", "New Message", None, QtGui.QApplication.UnicodeUTF8))
self.titl | eLabel.setText(QtGui.QApplication.translate("FluidNexusNewMessage", "&Title:", None, QtGui.QApplication.UnicodeUTF8))
self.messageLabel.setText(QtGui.QApplication.translate("FluidNexusNewMessage", "&Message:", None, QtGui.QApplication.UnicodeUTF8))
self.attachmentLabel.setText(QtGui.QApplication.transla... |
Execut3/CTF | IRAN Cert/2016/3- Harder/Steg/80pt- SLSB/Resources/LSBDecrypter.py | Python | gpl-2.0 | 2,084 | 0.003839 | __author__ = 'omrih'
import binascii
# Consts
HEADER_SIZE = 54 # Header size of BMP
DELIMITER = "$" # Separator between number of characters and text
# User Configurations
StegImageFile = "lsb1.bmp"
class LSB | Decrypter:
def __init__(self):
self.fh = open(StegImageFile, 'rb')
self.number_of_chars_in_text = 0
self.original_text = ''
def read_header(self):
# Reading Header - text is not encoded in it
for i in range(0, HEADER_SIZE):
byte = self.fh.read(1)
# Takes... | new_byte = ''
# get lsb of next 8 bytes
for bit in range(0, 8):
byte = self.fh.read(1)
# Taking only the LSB
new_byte += str(ord(byte) & 0x01)
# Converting binary value to ASCII
n = int(new_byte, 2)
desteg_char = binascii.unhexlify('%x' ... |
qwang2505/ssdb-source-comments | api/python/SSDB.py | Python | bsd-3-clause | 10,178 | 0.050501 | # encoding=utf-8
# Generated by cpy
# 2015-04-15 20:07:01.541685
import os, sys
from sys import stdin, stdout
import socket
class SSDB_Response(object):
pass
def __init__(this, code='', data_or_message=None):
pass
this.code = code
this.data = None
this.message = None
if code=='ok':
pass
this.data ... | pass
k = resp[i]
if resp[(i + 1)]=='1':
pass
v = True
else:
pass
v = False
data[k] = v
pass
i += 2
return SSDB_Response('ok', data)
else:
pass
return SSDB_Response(resp[0], resp[1 : ])
break
if False or ((cmd) == 'mu... | esp[0]=='ok':
pass
if len(resp) % 2==1:
pass
data = {}
i = 1
while i<len(resp):
pass
k = resp[i]
v = resp[(i + 1)]
data[k] = v
pass
i += 2
return SSDB_Response('ok', data)
else:
pass
return SSDB_Response('server_error',... |
rpadilha/rvpsite | rvpsite/blog/apps.py | Python | agpl-3.0 | 133 | 0.007519 | from django.apps import AppConfig
cl | ass BlogConfig(AppConfig):
name = 'rvpsite.blog'
verbose_ | name = 'GERENCIAMENTO DO BLOG' |
TraMZzz/travelize | config/settings/production.py | Python | mit | 6,774 | 0.000443 | # -*- coding: utf-8 -*-
"""
Production Configurations
- Use djangosecure
- Use Amazon's S3 for storing static files and uploaded media
- Use mailgun to send emails
- Use Redis on Heroku
"""
from __future__ import absolute_import, unicode_literals
from boto.s3.connection import OrdinaryCallingFormat
from django.util... | les.
# MEDIA_URL = 'https://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME
# Static Assets
# ------------------------
STATICFILES_STORAGE | = 'whitenoise.django.GzipManifestStaticFilesStorage'
# EMAIL
# ------------------------------------------------------------------------------
DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL',
default='baby-w <[email protected]>')
EMAIL_HOST = env("DJANGO_EMAIL_HOST", default='smtp.send... |
yuewko/neutron | neutron/plugins/ml2/drivers/helpers.py | Python | apache-2.0 | 6,136 | 0.000163 | # Copyright (c) 2014 Thales Services SAS
# 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 r... | eDriver(BaseTypeDriver):
"""SegmentTypeDriver for segment allocation.
Provide methods helping to perform segment allocation fully or partially
specified.
"""
def __init__(self, model):
| super(SegmentTypeDriver, self).__init__()
self.model = model
self.primary_keys = set(dict(model.__table__.columns))
self.primary_keys.remove("allocated")
def allocate_fully_specified_segment(self, session, **raw_segment):
"""Allocate segment fully specified by raw_segment.
... |
SohKai/ChronoLogger | web/flask/lib/python2.7/site-packages/flaskext/babel.py | Python | mit | 18,730 | 0.00016 | # -*- coding: utf-8 -*-
"""
flaskext.babel
~~~~~~~~~~~~~~
Implements i18n/l10n support for Flask applications based on Babel.
:copyright: (c) 2010 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import os
# this is a workaround for a snow... | if app is not None:
self.init_app(app)
def init_app(self, app):
"""Set up this instance for use with *app*, if no app was passed to
the constructor.
"""
self.app = app
app.babel_instance = self
if not hasattr(app, 'extensions'):
app.extensio... | app.config.setdefault('BABEL_DEFAULT_LOCALE', self._default_locale)
app.config.setdefault('BABEL_DEFAULT_TIMEZONE', self._default_timezone)
if self._date_formats is None:
self._date_formats = self.default_date_formats.copy()
#: a mapping of Babel datetime format strings that c... |
warner/magic-wormhole | misc/dump-stats.py | Python | mit | 421 | 0.002375 | from __future__ import print_function
import time, json
# Run this as | 'watch python misc/dump-stats.py' against a 'wormhole-server
# start --stats-file=stats.json'
with open("stats.json") as f:
data_s = f.read()
now = time.time()
data = json.loads(data_s)
if now < data["valid_until"]:
valid = "valid"
else:
| valid = "EXPIRED"
age = now - data["created"]
print("age: %d (%s)" % (age, valid))
print(data_s)
|
ingokegel/intellij-community | python/testData/quickFixes/PyTypeHintsQuickFixTest/parenthesesAndCustomTarget_after.py | Python | apache-2.0 | 142 | 0.021127 | from | typing import Generic, TypeVar
T = TypeVar("T")
class A(G | eneric[T]):
def __init__(self, v):
pass
v2 = None # type: A[int] |
hsarmiento/people_finder_chile | app/jp_mobile_carriers.py | Python | apache-2.0 | 7,659 | 0.001958 | #!/usr/bin/python2.7
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | iers-provided
message board services and redirects to the results page. If th | e query is a
non-mobile phone number, shows a 171 suggestion.
Args:
handler: a request handler for this request.
query: a query string to the Person Finder query page.
Returns:
True if the query string is a phone number and has been properly
handled, and False otherwise.
... |
rkokkelk/Gulliver | deluge/core/filtermanager.py | Python | gpl-3.0 | 9,642 | 0.001452 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2008 Martijn Voncken <[email protected]>
#
# This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# the additional special exception to link portions of this program with the OpenSSL library.
# See LICENSE for more details.
#
import... | ield in tree_keys)
self.pr | ev_filter_tree_keys = tree_keys
items = copy.deepcopy(self.filter_tree_items)
for torrent_id in list(torrent_ids):
status = self.core.create_torrent_status(torrent_id, torrent_keys, plugin_keys) # status={key:value}
for field in tree_keys:
value = status[field]
... |
kinnevo/kic_alone | daily/apps.py | Python | mit | 126 | 0 | from __future__ impor | t unicode_literals
from django.apps import AppConfig
class | DailyConfig(AppConfig):
name = 'daily'
|
technologiescollege/Blockly-rduino-communication | scripts_XP/Lib/test/test_property.py | Python | gpl-3.0 | 7,809 | 0.002945 | # Test case for property
# more tests are in test_descr
import sys
import unittest
from test.support import run_unittest
class PropertyBase(Exception):
pass
class PropertyGet(PropertyBase):
pass
class PropertySet(PropertyBase):
pass
class PropertyDel(PropertyBase):
pass
class BaseClass(object):
... | ertEqual(base.__class__.spam.__doc__, "spam spam spam")
self.assertEqual(sub.__class__.spam.__doc__, "spam spam spam")
@unittest.skipIf(sys.flags.optimize >= 2,
"Docstrings are omitted with -O2 and above")
def tes | t_property_getter_doc_override(self):
newgettersub = PropertySubNewGetter()
self.assertEqual(newgettersub.spam, 5)
self.assertEqual(newgettersub.__class__.spam.__doc__, "new docstring")
newgetter = PropertyNewGetter()
self.assertEqual(newgetter.spam, 8)
self.assertEqual(n... |
tensorflow/lingvo | lingvo/core/attention.py | Python | apache-2.0 | 143,702 | 0.0054 | # Lint as: python3
# 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 ... | Should
be of shape | (batch_size, input_sequence_length), and should all be in the
range [0, 1].
previous_attention: The attention distribution from the previous output
timestep. Should be of shape (batch_size, input_sequence_length). For
the first output timestep, preevious_attention[n] should be [1, 0, 0, ...,
... |
NuttamonW/Archaeological | ElectricalConductivity/resources_rc.py | Python | gpl-3.0 | 6,837 | 0.000731 | # -*- coding: utf-8 -*-
# Resource object code
#
# Created by: The Resource Compiler for PyQt4 (Qt v4.8.7)
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore
qt_resource_data = "\
\x00\x00\x05\x5d\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\
\x00\x00\x17\x00... | 6\xb6\xd3\x6d\x55\x9f\xf6\x02\x6f\x0c\
\xf8\x03\x80\xb2\x07\x1e\x90\x78\x42\x1a\x0c\xc4\xf6\xb2\xed\x01\
\xb4\x49\x53\x41\x15\xd5\x24\xa4\x3d\x74\xda\x40\x68\x93\xf6\x82\
\xaa\x70\xae\xaf\x53\xbb\x5d\xc6\xb8\x91\xaf\x7f\x39\xe7\x77\x3e\
\xef\xd1\x35\x40\xc7\x57\x9a\xe3\x98\x49\x19\x60\xde\xf2\x5d\x35\
\x9f\x91\x8f\x9f\... | e\x02\x2e\xc6\x85\x47\xd6\xc3\x5f\x21\xc1\
\xde\x37\x07\xda\xeb\xff\x73\x75\x56\xa9\xa7\x03\x24\x9e\x42\x6c\
\x57\x3d\x7d\x1e\xf1\x69\x80\x94\xa9\x3b\xae\x0f\x20\xde\x46\xf9\
\xf0\x29\xdf\x41\xdc\xf1\x3c\xe2\x1d\x2e\x26\x88\x58\x61\x78\x96\
\xe3\x2c\xc3\x33\x1c\x1f\x0f\x38\x53\xea\x28\x62\x96\x8b\xa4\xd7\
\xb5\x2a\xe2\... |
castlecms/castle.cms | castle/cms/linkintegrity.py | Python | gpl-2.0 | 3,563 | 0 | from castle.cms.interfaces import IReferenceNamedImage
from plone.app.uuid.utils import uuidToObject
from persistent.mapping import PersistentMapping
from persistent.dict import PersistentDict
from lxml.html import fromstring
from lxml.html import tostring
from plone import api
from plone.app.blocks.layoutbehavior impo... | er(obj)
objid = intids.getId(obj)
except NotYet:
# if we get a NotYet error, the object is not
# attached yet and we will need to get links
# at | a later time when the object has an intid
pass
return objid
def get_content_links(obj):
refs = set()
if ILayoutAware.providedBy(obj):
behavior_data = ILayoutAware(obj)
# get data from tile data
annotations = IAnnotations(obj)
for key in annotations.keys():
... |
sachinpro/sachinpro.github.io | tensorflow/python/framework/tensor_util.py | Python | apache-2.0 | 23,028 | 0.007817 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | np.complex64: SlowAppendComplex64A | rrayToTensorProto,
np.complex128: SlowAppendComplex128ArrayToTensorProto,
np.object: SlowAppendObjectArrayToTensorProto,
np.bool: SlowAppendBoolArrayToTensorProto,
dtypes.qint8.as_numpy_dtype: SlowAppendQIntArrayToTensorProto,
dtypes.quint8.as_numpy_dtype: SlowAppendQIntArrayToTensorProto,... |
rendermotion/RMPY | rig/rigProp.py | Python | lgpl-3.0 | 2,842 | 0.003167 | from RMPY.rig import rigSingleJoint
from RMPY.rig import rigBase
import pymel.core as pm
class RigPropModel(rigBase.BaseModel):
def __init__(self):
super(RigPropModel, self).__init__()
self.single_joints = []
class RigProp(rigBase.RigBase):
def __init__(self, *args, **kwargs):
kwargs... | r index in range(depth):
single_joint.create_point_base(each_point, size=size + size_step*index, **kwargs)
if index >= 1:
single_joint.reset_controls[-1].setParent(single_joint.controls[-2])
if offset_visibility:
single_join... | ty:
single_joint.controls[0].addAttr('offset_visibility', at='bool', k=True)
if align == 'world':
self.custom_world_align(single_joint.reset_controls[-1])
self.joints.extend(single_joint.joints)
self.controls.extend(single_joint.contro... |
SRabbelier/Melange | thirdparty/google_appengine/google/appengine/datastore/datastore_stub_util.py | Python | apache-2.0 | 28,255 | 0.008176 | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | ct
import th | reading
from google.appengine.api import datastore_types
from google.appengine.api.datastore_errors import BadRequestError
from google.appengine.datastore import datastore_index
from google.appengine.datastore import datastore_pb
from google.appengine.runtime import apiproxy_errors
from google.appengine.datastore impo... |
hermelin/hermelin-universal | hermelin/config.py | Python | lgpl-3.0 | 1,488 | 0.007412 | # -*- codin | g: UTF-8 -*-
import os
import pickle
import json
import gtk
import sys
import glob
import shutil
import glib
PROGRAM_NAME = 'hermelin'
EXT_DIR_NAME = 'ext'
THEME_DIR_NAME = 'theme'
CONF_DIR = os.path.join(glib.get_user_config_dir(), PROGRAM_NAME)
DB_DIR = os.path.join(CONF_DIR, 'db')
CACHE_DIR | = os.path.join(glib.get_user_cache_dir(), PROGRAM_NAME)
AVATAR_CACHE_DIR = os.path.join(CACHE_DIR, 'avatar')
DATA_DIRS = []
DATA_BASE_DIRS = [
'/usr/local/share'
, '/usr/share'
, glib.get_user_data_dir()
]
DATA_DIRS += [os.path.join(d, PROGRAM_NAME) for d in DATA_BASE_DIRS]
DATA_DIRS.append(os.path... |
nrwahl2/ansible | lib/ansible/modules/identity/ipa/ipa_hostgroup.py | Python | gpl-3.0 | 8,304 | 0.00277 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Ansible Project
# 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',
... | l', name=name)
def hostgroup_add_member(self, name, item):
return self._post_json(method='hostgroup_add_member', name=name, item=item)
def | hostgroup_add_host(self, name, item):
return self.hostgroup_add_member(name=name, item={'host': item})
def hostgroup_add_hostgroup(self, name, item):
return self.hostgroup_add_member(name=name, item={'hostgroup': item})
def hostgroup_remove_member(self, name, item):
return self._post_j... |
googleads/google-ads-python | google/ads/googleads/v9/services/services/change_status_service/transports/__init__.py | Python | apache-2.0 | 1,057 | 0 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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
#
# Unle | ss required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "A | S IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from collections import OrderedDict
from typing import Dict, Type
from .base import ChangeStatusServiceTransport
from .grpc im... |
jaraco/irc | irc/client.py | Python | mit | 41,993 | 0.000214 | # -*- coding: utf-8 -*-
"""
Internet Relay Chat (IRC) protocol client library.
This library is intended to encapsulate the IRC protocol in Python.
It provides an event-driven IRC client framework. It has
a fairly thorough support for the basic IRC protocol, CTCP, and DCC chat.
To best understand how to make an IRC ... | This function can be called to reconnect a closed connection.
Returns the ServerConnection object.
"""
log.debug(
"connect(server=%r, port=%r, nickname=%r, ...)", server, port, nickname
| )
if self.connected:
self.disconnect("Changing servers")
self.buffer = self.buffer_class()
self.handlers = {}
self.real_server_name = ""
self.real_nickname = nickname
self.server = server
self.port = port
self.server_address = (server, p... |
kvesteri/validators | tests/i18n/test_es.py | Python | mit | 2,127 | 0 | # -*- coding: utf-8 -*-
import pytest
from validators import ValidationFai | lure
from validators.i18n.es import es_cif, es_doi, es_nie, es_nif
@pytest.mark.parametrize(('value',), [
| ('B25162520',),
('U4839822F',),
('B96817697',),
('P7067074J',),
('Q7899705C',),
('C75098681',),
('G76061860',),
('C71345375',),
('G20558169',),
('U5021960I',),
])
def test_returns_true_on_valid_cif(value):
assert es_cif(value)
@pytest.mark.parametrize(('value',), [
('1234... |
aurelieladier/openturns | python/test/t_OptimalLHSExperiment_ishigami.py | Python | lgpl-3.0 | 3,061 | 0.005554 | from __future__ import print_function
import openturns as ot
from math import sin, pi
#import matplotlib
#matplotlib.use('Agg')
#import matplotlib.pylab as plt
# Definition of the Ishigami function
dimension = 3
a = 7.0
b = 0.1
input_variables = ['xi1', 'xi2', 'xi3', 'a', 'b']
formula = ['sin(xi1) + a * (sin(xi2)) ^ 2... | un()
c | haos_result = algo_pc.getResult()
print('Surrogate model computed')
# Validation
lhs_validation = ot.LHSExperiment(distribution_ishigami, 100)
input_validation = lhs_validation.generate()
output_validation = ishigami_model(input_validation)
# Chaos model evaluation
output_metamodel_sample = chaos_result.getMetaModel()... |
lucacasagrande/qgis2web | writerRegistry.py | Python | gpl-2.0 | 6,598 | 0.000303 | # -*- coding: utf-8 -*-
# Copyright (C) 2017 Nyall Dawson ([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 l... | :param default_value: default value for parameter
"""
project = QgsProject.instance()
key_string = self.sanitiseKey(parameter)
value = default_value
if isinstance(default_value, bool):
if project.readBoolEntry(
"qgis2web", key_string)[1]:
... | key_string)[0]
elif isinstance(default_value, int):
if project.readNumEntry(
"qgis2web", key_string)[1]:
value = project.readNumEntry("qgis2web",
key_string)[0]
else:
if (isinstance(pro... |
PFCM/slack-ml | data/test_tools.py | Python | mit | 974 | 0.00308 | """Tests for functions provided by tools.py"""
from contextlib import contextmanager
import time
import tools
import models
from google.appengine.ext import ndb
from google.appengine.ext import testbed
@contextmanager
def ndb_context():
tb_obj = testbed.Testbed()
tb_obj.activate()
tb_obj.init_datastore_v... | _msg(get_msg())
assert len(models.Messag | e.query().fetch(10)) == 1
|
tkelman/utf8rewind | tools/converter/libs/blobsplitter.py | Python | mit | 2,226 | 0.048518 | class BlobPage:
def __init__(self, splitter, pageIndex):
self.splitter = splitter
self.pageIndex = pageIndex
self.startIndex = 0
self.endIndex = 0
def start(self):
self.line = ""
self.read = 0
self.written = 0
self.firstLine = True
self.atEnd = False
self.blobPage = self.splitte... | blob_search[(end_index + 4):]
total_offset += page_read
page_current.endIndex = total_offset
page_curren | t = BlobPage(self, len(self.pages))
page_current.startIndex = total_offset
self.pages.append(page_current)
blob_page = blob_page[(page_read * 4):]
blob_size -= page_read |
kidchang/compassv2-api | compass/actions/health_check/check_tftp.py | Python | apache-2.0 | 3,363 | 0 | # Copyright 2014 Huawei Technologies Co. Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file ex | cept 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, ei... | her express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Health Check module for TFTP service."""
import os
import socket
import xmlrpclib
from compass.actions.health_check import base
from compass.actions.health_check import utils as health_che... |
allcaps/django-scaffold | scaffold/management/commands/build.py | Python | mit | 8,615 | 0.001625 | # -*- coding: utf-8 -*-
import logging
import os
from django.conf import settings
from django.core.management import BaseCommand
from django.apps import apps
from django.core.management import CommandError
from django.template.defaultfilters import slugify
from django.template.loader import get_template
from django.db... | se.html',
'scaffold/templatetags/__init__.py',
'scaffold/templatetags/APP_NAME_tags.py',
'scaffold/urls.py.html',
'scaffold | /views.py.html',
]
class MultiFileGenerator(BaseGenerator):
"""MultiFileGenerator splits the context into a context for each model. It generates multiple files per model."""
template_names = [
'scaffold/templates/APP_NAME/MODEL_NAME_base.html',
'scaffold/templates/APP_NAME/MODEL_NAME_confi... |
hatukanezumi/pytextseg | setup.py | Python | gpl-2.0 | 7,432 | 0.011975 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
setup.py - Setup script for pytextseg Python package
Copyright (C) 2012 by Hatuka*nezumi - IKEDA Soji.
This file is part of the pytextseg package. This program is free
software; you can redistribute it and/or modify it under the terms of
either the GNU General Public... | tup, Extension
from distutils.command.build_clib import build_clib
###############################################################################
# CONSTANTS
###############################################################################
SOMBOK_VERSION = '2.2'
UNICODE_VERSION = '6.1.0' # default for bundled ... | #################################################################
try:
from subprocess import getstatusoutput
except ImportError:
from commands import getstatusoutput
def pkg_config(*packages, **kwds):
flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'}
pkgs = ' '.join(["'%s'" %... |
MohanL/apriori-Fpgrowth | apriori.py | Python | mit | 5,171 | 0.015858 | """
Description : Python implementation of Apriori Algorithm
Usage $python main.py -f [filename] -s [minSupport] -c [minConfidence]
Note to readers : my data structure is a list contains sets contains lists inside the sets
The reason I choose to implement in this way is because I can use the union method of the sets
... | s in originalList:
for e in s:
Cone.append(e)
return sorted(Cone)
def pruneForSizeOne(objectList):
"""this function take in a candidate itemset and filter by support """
""" K is the result frequent itemset for its size"""
kDict = dict()
kList = list()
a = Counter(ob... | globMinSup):
kDict.update({e:a[e]})
c = set([e])
kList.append(c)
return kList
def getSizePlueOneItemSet(Klist):
""" my way of this doing is super lazy, I just union it and check for size
and I put the result itemset into the list
at the end of the function,... |
lepture/Vealous | vealous/markdown/extensions/toc.py | Python | bsd-3-clause | 4,907 | 0.006929 | """
Table of Contents Extension for Python-Markdown
* * *
(c) 2008 [Jack Miller](http://codezen.org)
Dependencies:
* [Markdown 2.0+](http://www.freewisdom.org/projects/python-markdown/)
"""
import markdown
from markdown import etree
import re
class TocTreeprocessor(markdown.treeprocessors.Treeprocessor):
# Iter... | port unicodedata
value = unicodedata.normalize('NFK | D', value).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
return re.sub('[-\s]+','-',value)
def extendMarkdown(self, md, md_globals):
tocext = TocTreeprocessor(md)
tocext.config = self.config
md.treeprocessors.add("toc", tocext, "_be... |
snickl/buildroot-iu | utils/checkpackagelib/lib_mk.py | Python | gpl-2.0 | 9,279 | 0.004095 | # See utils/checkpackagelib/readme.txt before editing this file.
# There are already dependency checks during the build, so below check
# functions don't need to check for things already checked by exploring the
# menu options using "make menuconfig" and by running "make" with appropriate
# packages enabled.
import re... | OTFS",
"XTENSA_CORE_NAME"]))
PACKAGE_NAME = re.compile("/([^/]+)\.mk")
VARIABLE = re.compile("^([A-Z0-9_]+_[A-Z0-9_]+)\s*(\+|)=")
def before(self):
package = self.PACKAGE_NAME.search(self.filename).group(1)
package = package.replace("-", "_").upp | er()
# linux tools do not use LINUX_TOOL_ prefix for variables
package = package.replace("LINUX_TOOL_", "")
# linux extensions do not use LINUX_EXT_ prefix for variables
package = package.replace("LINUX_EXT_", "")
self.package = package
self.REGEX = re.compile("^(HOST_|RO... |
JakeCowton/titanic | src/ga_for_rfc.py | Python | mit | 5,521 | 0.000181 | import numpy as np
from sklearn.ensemble import RandomForestClassifier
from deap import creator, base, tools, algorithms
from utils import get_training_data, get_evaluation_data,\
get_testing_data, normalise_data
from evaluation import EvaluationMetrics
from nn_manager import create_nn, call_nn
import... | "Cabin"
], axis=1)
inputs_to_drop = []
for i in range(len(individual)):
if individual[i] == 0:
inputs_to_drop.append(self.get_feature_name(i))
inputs = inputs.drop(inputs_to_drop, axis=1)
inputs | = normalise_data(inputs).values
return inputs
def calculate(self):
pop = self.toolbox.population(n=300)
hof = tools.HallOfFame(1)
stats = tools.Statistics(lambda ind: ind.fitness.values)
stats.register("avg", np.mean)
stats.register("std", np.std)
stats.reg... |
diedthreetimes/VCrash | pybindgen-0.15.0.795/.waf-1.5.9-0c853694b62ef4240caa9158a9f2573d/wafadmin/Tools/cxx.py | Python | gpl-2.0 | 2,783 | 0.049946 | #! /usr/bin/env python
# encoding: utf-8
import sys
if sys.hexversion < 0x020400f0: from sets import Set as set
import TaskGen,Task,Utils
from Logs import debug
import ccroot
from TaskGen import feature,before,extension,after
g_cxx_flag_vars=['CXXDEPS','FRAMEWORK','FRAMEWORKPATH','STATICLIB','LIB','LIBPATH','LINKFLAGS'... | r,color='GREEN',ext_out='.o',ext_i | n='.cxx',shell=False)
cls.scan=ccroot.scan
cls.vars.append('CXXDEPS')
link_str='${LINK_CXX} ${CXXLNK_SRC_F}${SRC} ${CXXLNK_TGT_F}${TGT[0].abspath(env)} ${LINKFLAGS}'
cls=Task.simple_task_type('cxx_link',link_str,color='YELLOW',ext_in='.o',ext_out='.bin',shell=False)
cls.maxjobs=1
cls.install=Utils.nada
feature('cxx')(... |
bond-anton/Space | demo/07_lines_demo.py | Python | apache-2.0 | 471 | 0.002123 | from mayavi import mlab
from BDSpace.Coordinates import Cartesian
from BDSpace.Curve.Parametric import Line
import BDSpaceVis as Visual
coordinate_system = Car | tesian()
fig = mlab.figure('CS demo', bgcolor=(0, 0, 0))
line = Line(name='Line', coordinate_system=coordinate_system, a=1, b=2, c=0, start=0, stop=1)
line_visua | l = Visual.CurveView(fig, line, color=(1, 0, 0), thickness=None)
line_visual.draw()
line_visual.set_thickness(line_visual.thickness / 2)
mlab.show()
|
Hirras/inf1340_2015_asst1 | exercise1.py | Python | mit | 2,119 | 0.003775 | #!/usr/bin/env python
""" Assignment 1, Exercise 1, INF1340, Fall, 2015. Grade to gpa conversion
This module prints the amount of money that Lakshmi has remaining
after the stock transactions
"""
__author__ = 'Hirra and Tyler'
# function to calculate net gain/loss of purchase
def calc_pur_cost(pur_num_shares, pur_... | st * (pur_comm_pct / 100) # divide input percentage by 100 to make an accurate calculation
total_pur_cost = net_pur_cost + pur_comm_cost
return total_pur_cost
# function to calculate net gain/loss of sale
def calc_sale_cost(sale_num_shares, sale_share_cost, sale_comm_pct):
net_sale_cost = sale_num_shares ... | - sale_comm_cost
return total_sale_cost
# function to take inputs and calculate total gain/loss
def calc_total_cost():
pur_num_shares = float(raw_input("Number of shares purchased: "))
pur_share_cost = float(raw_input("Purchase price per share: "))
pur_comm_pct = float(raw_input("Purchase commission pe... |
kasioumis/invenio | invenio/utils/date.py | Python | gpl-2.0 | 22,706 | 0.000528 | # -*- coding: utf-8 -*-
#
# Some functions about dates
#
# This file is part of Invenio.
# Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 CERN.
#
# Invenio 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 ... | urn babel_format_datetime(dt, output_format).encode('utf8')
else:
raise ValueError
except:
return _("N/A").encode('utf8')
def convert_datestruct_to_datetext(datestruct):
"""Convert: (2005, 11, 16, 15, 11, 44, 2, 320, 0) => '2005-11-16 15:11:57'
"""
try:
... | atestruct(datecvs):
"""Convert CVS $Date$ and $Id$ formats into datestruct. Useful for later
conversion of Last updated timestamps in the page footers.
Example: '$Date$' => (2006, 09, 20, 19, 27, 11, 0, 0)
"""
try:
if datecvs.startswith("$Id"):
date_time = ' '.join(datecvs.split... |
authomatic/authomatic | authomatic/providers/oauth2.py | Python | mit | 59,333 | 0.000135 | # -*- coding: utf-8 -*-
"""
|oauth2| Providers
-------------------
Providers which implement the |oauth2|_ protocol.
.. autosummary::
OAuth2
Amazon
Behance
Bitly
Cosm
DeviantART
Eventbrite
Facebook
Foursquare
GitHub
Google
LinkedIn
PayPal
Reddit
Viadeo
... | params['grant_type'] = 'refresh_token'
else:
raise OAuth2Error(
'Credentials with valid refresh_token, consumer_key, '
'consumer_secret are required to creat | e OAuth 2.0 '
'refresh token request elements!')
elif request_type == cls.PROTECTED_RESOURCE_REQUEST_TYPE:
# Protected resource request.
# Add Authorization header. See:
# http://tools.ietf.org/html/rfc6749#section-7.1
if credentials.token_ty... |
xoseperez/rentalito | server/libs/Filters.py | Python | gpl-3.0 | 4,698 | 0.006177 | #! /usr/bin/python
# -*- coding: utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
# Xbee to MQTT gateway
# Copyright (C) 2012 by Xose Pérez
#
# 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... | ms():
if str(value) == str(from_v | alue):
return to_value
return to_value
FilterFactory.register(EnumFilter)
class StepFilter(Filter):
"""
Step filter
"""
name = 'step'
required = []
def process(self, value):
for threshold, to_value in self.parameters.iteritems():
if float(value) <= th... |
CSD-Public/stonix | src/stonix_resources/solaris.py | Python | gpl-2.0 | 7,231 | 0.006361 | ###############################################################################
# #
# Copyright 2019. Triad National Security, LLC. All rights reserved. #
# This program was produced under U.S. Government contract 89233218CNA000001 #
... | e : Name of the package to be installed, must be
recognizable to the underlying package manager.
| :param package:
:returns: bool :
@author
'''
try:
# retval = call(self.install + package,stdout=None,shell=True)
# if retval == 0:
self.ch.executeCommand(self.install + package)
if self.ch.getReturnCode() == 0:
self.deta... |
ferasha/curfil | scripts/hyperopt/hyperopt_search.py | Python | mit | 2,103 | 0.012363 | #!/usr/bin/env python
from __future__ import print_function
import sys
import math
import hyperopt
from hyperopt import fmin, tpe, hp
from hyperopt.mongoexp import MongoTrials
def get_space():
space = (hp.quniform('numTrees', 1, 10, 1),
hp.quniform('samplesPerImage', 10, 7500, 1),
hp.... | 0.0, 0.6),
)
return space
def get_exp(mongodb_url, database, exp_key):
trials = MongoTrials('mongo://%s/%s/jobs' % (mongodb_url, database), exp_key=exp_key)
space = | get_space()
return trials, space
def show(mongodb_url, db, exp_key):
print ("Get trials, space...")
trials, space = get_exp(mongodb_url, db, exp_key)
print ("Get bandit...")
bandit = hyperopt.Bandit(expr=space, do_checks=False)
print ("Plotting...")
# from IPython.core.debugger... |
durandj/ghost-chat | ghost_chat/ui/urls.py | Python | mit | 192 | 0.026042 | from django.conf | .urls import patterns, | url
from . import views as ui_views
# pylint: disable=invalid-name
urlpatterns = patterns('',
url(r'^$', ui_views.UIView.as_view(), name = 'ui'),
)
|
kymbert/behave | behave/formatter/css.py | Python | bsd-2-clause | 5,025 | 0.000796 | # -*- coding: utf-8 -*-
"""
CSS themes to include in the HTML formatter.
"""
class BasicTheme(object):
stylesheet_text = """
body {
font-size:0;
color:#fff;
margin:0;
padding:0
}
.behave,td,th {
font:400 11px "Lucida Grande",Helvetica,sans-serif;
background:#fff;
color:#000
}
.behave... | m:1px solid #0ff;
background:#e0ffff;
color:#011;
margin-left:10px
}
.behave #summary,td #summary,th #summary {
| margin:0;
padding:5px 10px;
text-align:right;
top:0;
right:0;
float:right
}
.behave #summary p,td #summary p,th #summary p {
margin:0 0 0 2px
}
.behave #summary #totals,td #summary #totals,th #summary #totals {
font-size:1.2em
}
"""
|
google-research/google-research | fairness_teaching/in_progress/rl_a2c/model.py | Python | apache-2.0 | 7,045 | 0.01462 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
| #
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for | the specific language governing permissions and
# limitations under the License.
import os
import numpy as np
import tensorflow as tf
# pylint: skip-file
def get_weight(shape, stddev, reg, name):
wd = 5e-4
init = tf.random_normal_initializer(stddev=stddev)
if reg:
regu = tf.contrib.layers.l2_regularizer(wd)... |
taniwha-qf/io_object_mu | export_mu/empty.py | Python | gpl-2.0 | 2,799 | 0.002501 | # vim:ts=4:et
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This prog... | se
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# <pep8 compliant>
from ..utils import strip_nnn
from . import attachnode
from . import export
def is_group_root(obj, objects):
... | :
objects = {}
def collect(col):
for o in col.objects:
objects[o.name] = o
for c in col.children:
collect(c)
collect(collection)
return objects
def export_collection(obj, muobj, mu):
saved_exported_objects = set(export.exported_objects)
group = obj.instan... |
Rinoahu/fastclust | scripts/orth2phy.py | Python | gpl-3.0 | 4,324 | 0.004163 | #!usr/bin/env python
import sys
from Bio import SeqIO
from collections import Counter
import os
# do the core gene find
# python this_script.py -i foo.pep.fsa -g foo.ortholog [-r taxon]
def manual_print():
print('This script is used to find orthologs in other species by given a reference, then extract sequences o... | asta')
_o.close()
#raise SystemExit()
# use the muscle to aln
for i in range(orths_N):
# break
os.system(
'muscle -in ./alns_tmp/%d.fsa -out ./alns_tmp/%d.fsa.aln -fasta -quiet' % (i, i))
#os.system('/home/zhans/tools/tree_tools/trimal/source/trimal -in ./alns_tmp/%d.fsa.aln -out ./alns_tmp/%d.... | #seqs = SeqIO.parse('./alns_tmp/%d.fsa.aln.trim' % i, 'fasta')
seqs = SeqIO.parse('./alns_tmp/%d.fsa.aln' % i, 'fasta')
for j in seqs:
taxon = j.id.split('|', 2)[0]
try:
tree[taxon].append(str(j.seq))
except:
tree[taxon] = [str(j.seq)]
# print 'tree is', tre... |
reybalgs/PyRecipe-4-U | gui/shopping_list.py | Python | gpl-3.0 | 3,704 | 0.00135 | ##############################################################################
#
# shopping_list.py
#
# Python module that contains code necessary for the creation of the dialog
# that handles the application's "Generate Shopping List" functionality.
#
###################################################################... |
self.mainLayout.addWidget(self.ingredientsList)
# Refresh the list
self.initialize_list()
# Exit button
self.mainLayout.addWidget(self.exitButton)
def __init__(self, parent, recipe):
"""
Initialization function. Mostly just calls an init ui functi... | alog, self).__init__(parent)
# Put the given recipe in this dialog's own copy
self.recipe = recipe
self.init_ui()
self.init_signals()
|
jorisvandenbossche/DS-python-data-analysis | notebooks/_solutions/case4_air_quality_processing8.py | Python | bsd-3-clause | 118 | 0.008475 | # Drop the origal date and hou | r columns
data_stacke | d = data_stacked.drop(['date', 'hour'], axis=1)
data_stacked.head() |
alexgorban/models | official/nlp/bert/input_pipeline.py | Python | apache-2.0 | 8,437 | 0.008534 | # Copyright 2019 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... | ibuted under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRAN | TIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""BERT model input pipelines."""
from __future__ import absolute_import
fro... |
Justin-Tan/hep-analysis | spark2tfrecords/spark2tfrecords.py | Python | gpl-3.0 | 6,562 | 0.006705 | #!/usr/bin/env python3
"""
Justin Tan 2017
Reads parquet file, conducts preprocessing, outputs to TfRecords
spark-submit --name spark2tf --jars /home/jtan/gpu/jtan/spark/ecosystem/spark/spark-tensorflow-connector/target/spark-tensorflow-connector-1.0-SNAPSHOT.jar,/home/jtan/gpu/jtan/spark/ecosystem/spark/spark-tensorf... | n corr_pairs]
[print(feature) for feature in list(set(top001_right)) if feature in list(set(top001_left))]
to_remove = [feature for feature in list(set(top001_right)) if feature not in top001_left]
return to_remove
def unpack_vectorCol(df, trainCols, specialCols, col2unpack='scaledFeatures'):
from py... | :
def to_array_(v):
return v.toArray().tolist()
return udf(to_array_, ArrayType(DoubleType()))(col)
unpacked_df = (df.withColumn("sf", to_array(col(col2unpack)))
.select([col("sf")[i].alias(trainCols[i]) for i in range(len(trainCols))]+specialCols))
return unpa... |
noahhsmith/starid | starid/util.py | Python | mit | 987 | 0.012158 | import numpy as np
import matplotlib.pyplot as plt
import libstarid
ls = libstarid.libstarid()
def test_sky(pathsky):
read_ | sky(pathsky)
imgdict = ls.image_generator(3)
plt.matshow(-1 * imgdict['pixels'], cmap='Greys', interpolation='nearest')
plt.show()
def read_sky(pathsky):
ls.read_sky(pathsky)
def write_sky(pathsky, pathcat):
ls.write_sky(pathsky, pathcat)
def read_starpairs(paths | tarpairs):
ls.read_starpairs(pathstarpairs)
def write_starpairs(pathstarpairs):
ls.write_starpairs(pathstarpairs)
def startriangles(starndx=3):
read_sky('../data/sky')
read_starpairs('../data/pairs')
imgdict = ls.image_generator(starndx)
id = ls.startriangles(imgdict['pixels'])
print(id)
... |
schleichdi2/OPENNFR-6.3-CORE | bitbake/lib/bb/fetch2/__init__.py | Python | gpl-2.0 | 67,666 | 0.002941 | """
BitBake 'Fetch' implementations
Classes for obtaining upstream sources for the
BitBake build tools.
"""
# Copyright (C) 2003, 2004 Chris Larson
# Copyright (C) 2012 Intel Corporation
#
# SPDX-License-Identifier: GPL-2.0-only
#
# Based on functions from the base bb module, Copyright 2003 Holger Schurig
import o... | t bb.event
__version__ = "2"
_checksum_cache = bb.checksum.FileChecksumCache()
logger = logging.getLogger("BitB | ake.Fetcher")
class BBFetchException(Exception):
"""Class all fetch exceptions inherit from"""
def __init__(self, message):
self.msg = message
Exception.__init__(self, message)
def __str__(self):
return self.msg
class UntrustedUrl(BBFetchException):
"""Exception raised when en... |
aelkikhia/pyduel_engine | pyduel_engine/model/position.py | Python | apache-2.0 | 3,110 | 0 |
from math import fabs
"""Kept these functions outside the class, since they are static
for the search and movement functions for board. The downside is it creates
an object for search purposes, which seems relatively heavy. I'll
optimize later if necessary
"""
def shift_up(pos):
"""returns new position... | def __eq__(self, pos):
return self._x == pos.x and self._y == pos.y
def __ne__(self, pos):
return self._x != pos.x or self._y != pos.y
def __hash__(self):
return hash(('x', self._x, 'y', self._y))
def __repr__(self):
return '({0},{1})'.format(self._x, self._y)
def __s... | @property
def x(self):
return self._x
@property
def y(self):
return self._y
# ############################### Discovery ###############################
def is_diagonal(self, pos):
"""Verify if points are diagonal"""
return fabs(self.x - pos.x) == fabs(self.y - p... |
cytex124/celsius-cloud-backend | src/celsius/celery.py | Python | mit | 623 | 0 | from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
# | set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celcius.settings')
app = Celery('celsius')
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related ... | tered Django app configs.
app.autodiscover_tasks()
|
GEMPACKsoftware/HARPY | harpy/__init__.py | Python | gpl-3.0 | 144 | 0.006944 | from .header_array import HeaderArr | ayObj
from .har_file import HarFileObj
from .har_file_io import HarFileIO
from .sl4 import SL4
na | me = "harpy" |
dgnorth/drift-base | driftbase/tests/players/test_players.py | Python | mit | 6,842 | 0.001462 | import datetime
from six.moves import http_client
from mock import patch
import unittest
from drift.systesthelper import uuid_string, big_number
from driftbase.utils.test_utils import BaseCloudkitTest
class PlayersTest(BaseCloudkitTest):
"""
Tests for the /players endpoints
"""
def test_pl... | js = r.json()
urls = ["player_url", "gamestates_url", "journal_url", "user_url",
"messagequeue_url", "messages_url",
"summary_url", "countertotals_url", "counter_url", "tickets_url"]
# make sure the urls in the list are in the response and | non-empty
for url in urls:
self.assertIn(url, js)
self.assertIsNotNone(js[url])
def test_players(self):
# Create three players for test
self.auth(username="Number one user")
p1 = self.player_id
self.assertGreater(p1, 0)
self.auth(u... |
ishay2b/tensorflow | tensorflow/contrib/boosted_trees/estimator_batch/model.py | Python | apache-2.0 | 4,592 | 0.006533 | # 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... | ts = predictions_dict["predictions"]
def _train_op_fn(loss):
"""Returns the op to optimize the loss."""
update_op = gbdt_model.train(loss, predictions_dict, labels)
with ops.control_dependencies(
[update_op]), (ops.colocate_with(global_step)):
update_op = state_ops.assign_add(gl... | p_fn,
logits=logits)
if num_trees:
if center_bias:
num_trees += 1
finalized_trees, attempted_trees = gbdt_model.get_number_of_trees_tensor()
model_fn_ops.training_hooks.append(
trainer_hooks.StopAfterNTrees(num_trees, attempted_trees,
finalized_tre... |
wjsl/jaredcumulo | test/system/auto/simple/mapreduce.py | Python | apache-2.0 | 6,108 | 0.014571 | # 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 use ... | log.debug("\n\n!!!FINISHED!!!\n\n")
if(handle.returncode==0):
self.checkResults()
else:
self.fail("Test did not finish")
def isAccumuloRunning(self):
output = subprocess.Popen(["jps","-m"],stderr=subprocess.PIPE, stdout=subprocess.PIPE).comm... | ,tablename,cfcq):
input = "table %s\nscan\n" % tablename
out,err,code = self.rootShell(self.masterHost(),input)
#print out
restr1 = "[0-9].*\[\] (.*)"
restr2 = "[0-9] %s \[\] (.*)"%(cfcq)
val_list = re.findall(restr2,out)
return val_list
def checkRe... |
evan176/rl | rl/utils.py | Python | mit | 496 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import tensorflow as tf
def summarize_variable(var, | name):
with tf.name_scope("summaries_{}".format(name)):
mean = tf.reduce_mean(var)
tf.summary.scalar("mean", mean)
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
tf.summary.scalar("stddev", stddev)
tf.summary.scalar("max", tf.reduce_ | max(var))
tf.summary.scalar("min", tf.reduce_min(var))
tf.summary.histogram("histogram", var)
|
systemsoverload/codeeval | easy/26_file_size/solution.py | Python | mit | 56 | 0.017857 | import os
import sys
print os.sta | t(sys.argv[1]). | st_size |
madscatt/zazzie | src_2.7/sassie/analyze/altens/altens.py | Python | gpl-3.0 | 4,413 | 0.005892 | '''
SASSIE: Copyright (C) 2011-2016 Joseph E. Curtis, Ph.D.
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.... | list file starts from 1
'''
mvars.use_monte_carlo_flag = variables['use_monte_carlo_flag'][0]
'''
method to MC run for error analysis
'''
if mvars.use_monte_carlo_flag:
mvars.number_of_monte_carlo_steps = variable | s['number_of_monte_carlo_steps'][0]
mvars.seed = variables['seed'][0]
# print "mvars.seed = ", mvars.seed
self.log.debug(vars(mvars))
return
def initialization(self):
'''
method to initialize input variables
'''
log = self.log
log.debu... |
DBrianKimmel/PyHouse | Project/src/Modules/Core/Drivers/_test/test_Null.py | Python | mit | 813 | 0 | """
@name: PyHouse/src/Modu | les/Drivers/_test/test_Null.py
@author: D. Brian Kimmel
@contact: [email protected]
@copyright: (c) 2015-2018 by D. Brian Kimmel
@license: MIT License
@note: Created on Jul 30, 2015
@Summary:
"""
__updated__ = '2018-02-12'
# Import system type stuff
from twisted.trial import unittest, reporter, run... | f):
self.m_test = runner.TestLoader()
def test_Null(self):
l_package = runner.TestLoader().loadPackage(I_test)
l_ret = reporter.Reporter()
l_package.run(l_ret)
l_ret.done()
#
print('\n====================\n*** test_Null ***\n{}\n'.format(l_ret))
# ## END DBK... |
M4rtinK/repho | platforms/maemo5.py | Python | gpl-3.0 | 17,636 | 0.012701 | """
Repho hildon UI (for Maemo 5@N900)
"""
import os
import gtk
import gobject
import hildon
import maemo5_autorotation
import info
from base_platform import BasePlatform
class Maemo5(BasePlatform):
def __init__(self, repho, GTK=True):
BasePlatform.__init__(self)
self.repho = repho
self.GTK = GTK
... | ', self._applyRotationCB)
return pb
def _applyRotationCB(self, pickerButton):
"""handle the selector callback and set the appropriate rotation"""
index = pickerButton.get_selector().get_active(0)
"""the indexes of the modes in the selector are the same as the numbers
used for switching modes"""
... | touch selector,
connect it with the history selector and connect the remove item callback"""
pb = self.getVerticalPickerButton("Erase an item from history")
selector = self._getHistorySelector()
pb.set_selector(selector)
pb.set_active(-1) # active item does not make sense in this case
selector.c... |
halitalptekin/sipptam | src/sipptam/validate/Schema.py | Python | isc | 4,705 | 0.003188 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
sipptam.conf.Schema
~~~~~~~~~~~~~~~~~~~
Contains a basic XML schema to parse the input configuration file.
:copyright: (c) 2013 by luismartingil.
:license: See LICENSE_FILE.
"""
import StringIO
schema = StringIO.StringIO('''\
<?xml version="1.0" enco... |
</xs:complexType>
<xs:simpleType name="numberListType">
<xs:restriction base="xs:string">
<xs:pattern value="([0-9]*)((;[0-9]+)*)?"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="execModeType">
<xs:restriction base="xs:string">
<xs:enumeration va... | simpleType>
<xs:simpleType name="IPType">
<xs:restriction base="xs:string">
<xs:pattern value="(([1-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([1-9]?[0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="anyOrIPType">
<xs:restr... |
NJU-HouseWang/Amazon_Index | Amazon_Index/urls.py | Python | gpl-2.0 | 215 | 0 | from django.conf.urls import patterns, include, url
from Amazon_Index.views import *
urlpatterns = patterns( |
'',
url(r'^$', index),
url(r'^category/$', ca | tegory),
url(r'^commodity/$', commodity),
)
|
fedelemantuano/thug | thug/ThugAPI/ThugOpts.py | Python | gpl-2.0 | 8,781 | 0.0041 | #!/usr/bin/env python
#
# ThugOpts.py
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; ... | [WARNING] Ignoring invalid threshold value (should be an integer)')
return
self._threshold = value
threshold = property(get_threshold, set_threshold)
def get_connect_timeout(self):
return self._connect_timeout
def set_connect_timeout(self, timeout):
try:
s... | nnect_timeout = seconds
connect_timeout = property(get_connect_timeout, set_connect_timeout)
def get_timeout(self):
return self._timeout
def set_timeout(self, timeout):
try:
seconds = int(timeout)
except ValueError:
log.warning('[WARNING] Ignoring invalid t... |
Metaswitch/calico-nova | nova/keymgr/single_key_mgr.py | Python | apache-2.0 | 2,552 | 0 | # Copyright (c) 2013 The Johns Hopkins University/Applied Physics Laboratory
# 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/... | gging
LOG = logging.getLogger(__name__)
class SingleKeyManager(mock_key_mgr.MockKeyManager):
"""This key manager implementation supports all | the methods specified by
the key manager interface. This implementation creates a single key in
response to all invocations of create_key. Side effects
(e.g., raising exceptions) for each method are handled as specified by
the key manager interface.
"""
def __init__(self):
LOG.warning(_... |
jismartin/RedesNegocios | scrapy/qdq/qdq/items.py | Python | gpl-3.0 | 282 | 0 | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class QdqItem(scrapy.Item):
# define the f | ields for your item here like:
# name = scrapy.F | ield()
pass
|
armando-migliaccio/neutron | neutron/services/loadbalancer/drivers/haproxy/agent_manager.py | Python | apache-2.0 | 9,680 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2013 New Dream Network, LLC (DreamHost)
#
# 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/li... | device_count = len(self.cache.devices)
self.agent_state['configurations']['devices'] = device_count
self.state_rpc.report_state(self.context,
self.agent_state)
self.agent_state.pop('start_flag', None)
except Exception:
... | G.exception("Failed reporting state!")
def initialize_service_hook(self, started_by):
self.sync_state()
@periodic_task.periodic_task
def periodic_resync(self, context):
if self.needs_resync:
self.needs_resync = False
self.sync_state()
@periodic_task.periodic_ta... |
rajarammallya/melange | melange/tests/unit/test_notifier.py | Python | apache-2.0 | 7,474 | 0.000134 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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/... | _message")
self.mock.StubOutWithMock(messaging, "Queue")
messaging.Queue("melange.notifier.INFO",
"notifier").AndReturn(self.mock_queue)
self.mock.ReplayAll()
self.notifier.info("test_event", "test_message")
def test_error(self):
... | .mock.StubOutWithMock(messaging, "Queue")
self._setup_queue_mock("error", "test_event", "test_message")
messaging.Queue("melange.notifier.ERROR",
"notifier").AndReturn(
self.mock_queue)
self.mock.ReplayAll()
self.notifier.e... |
corredD/upy | blender/v262/v263/blenderUI.py | Python | gpl-3.0 | 105,848 | 0.01505 |
"""
Copyright (C) <2010> Autin L. TSRI
This file git_upy/blender/v262/v263/blenderUI.py is part of upy.
upy 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 Licen... | _gui") :
return
self = getattr(bpy,"current_gui")
scn = bpy.context.scene
#layout event
for block in self._layout:
if type(block) is list :
for elem in block:
if elem["type"] in ["inputStr","pullMenu","checkbox",
"sliders","slidersInt",... | self.isChanged(elem["name"]):
#send event message to command?
# self._command([elem["id"],])
self._callElemAction(elem)
# return
else : #dictionary: multiple line / format dict?
if "0" in block:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.