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 |
|---|---|---|---|---|---|---|---|---|
valexandersaulys/prudential_insurance_kaggle | venv/lib/python2.7/site-packages/numpy/core/records.py | Python | gpl-2.0 | 29,422 | 0.001461 | """
Record Arrays
=============
Record arrays expose the fields of structured arrays as properties.
Most commonly, ndarrays contain elements of a single type, e.g. floats,
integers, bools etc. However, it is possible for elements to be combinations
of these using structured types, such as::
>>> a = np.array([(1, 2... | 'col3'), '|S5')])
`names` and/or `titles` can be empty lists. If | `titles` is an empty list,
titles will simply not appear. If `names` is empty, default field names
will be used.
>>> np.format_parser(['f8', 'i4', 'a5'], ['col1', 'col2', 'col3'],
... []).dtype
dtype([('col1', '<f8'), ('col2', '<i4'), ('col3', '|S5')])
>>> np.format_parser(['f... |
ehartsuyker/securedrop | securedrop/tests/functional/functional_test.py | Python | agpl-3.0 | 11,846 | 0.001266 | # -*- coding: utf-8 -*-
from __future__ import print_function
import logging
import os
import signal
import socket
import time
import traceback
from datetime import datetime
from multiprocessing import Process
from os.path import abspath
from os.path import dirname
from os.path import expanduser
from os.path import j... | TBB_PATH, tor_cfg=cm.USE_RUNNING_TOR, pref_dict=pref_dict, tbb_logfile_path=LOGFILE_PATH
)
logging.info("Created Tor Browser driver")
def _create_firefox_driver(self, profile=None):
logging.info("Creating Firefox driver" | )
if profile is None:
profile = webdriver.FirefoxProfile()
if self.accept_languages is not None:
profile.set_preference("intl.accept_languages", self.accept_languages)
profile.update_preferences()
self._firefox_driver = webdriver.Firefox(
... |
CG3002/Hardware-Bootloader-Timer | reg.py | Python | mit | 1,129 | 0.049601 | import time
import serial
ser = serial.Serial(port=29, baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_TWO, timeout=1)
ser.isOpen()
connected=False
cash_reg = []
my_dict = []
reg = ['@r3', '@r1', '@r | 2', '@r4']
flag = 1
start_rec = 0
wro | ng_id = 0
start_count = 0
barcode_flag = 0
def handle_data(data):
print(data)
print 'start transmission'
while 1 :
for item in reg:
try:
send_pkg = item+'/'
ser.write(send_pkg)
print 'sending '+ send_pkg
while flag :
start_count += 1
buffer = ser.read() #blocking call
print 'receive... |
CompSoc-NUIG/python_tutorials_2013 | guess.py | Python | unlicense | 774 | 0.003876 | #!/usr/bin/env python
import random
'''\
The computer will pick a number between 1 and | 100. (You can choose any high
number you want.) The purpose of the game is to guess the number the computer
picked in as few guesses as possible.
source:http://openbookproject.net/pybiblio/practice/\
'''
high_or_low = {True: "Too high. Try again:",
False: "Too low. Try again: "}
def main():
cho... | : "))
is_high = user_choice > choice
if user_choice == choice:
break
print(high_or_low[is_high])
print("You guessed {0} correctly".format(choice))
if __name__ == "__main__":
main()
|
kanishkarj/Rave | Qt_Designer_files/main_design.py | Python | gpl-3.0 | 20,258 | 0.002221 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'main.ui'
#
# Created by: PyQt4 UI code generator 4.12.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
... | ttingsWidget)
self.fullscreenButton.setMinimumSize(QtCore.QSize(30, 30))
self.fullscreenButton.setMaximumSize(QtCore.QSize(30, 30))
self. | fullscreenButton.setText(_fromUtf8(""))
self.fullscreenButton.setObjectName(_fromUtf8("fullscreenButton"))
self.horizontalLayout_6.addWidget(self.fullscreenButton)
self.playlistButton = QtGui.QPushButton(self.mediaSettingsWidget)
self.playlistButton.setMinimumSize(QtCore.QSize(30, 30))
... |
Nitrate/Nitrate | src/tcms/auth/migrations/0001_initial.py | Python | gpl-2.0 | 1,148 | 0.000871 | # -*- coding: utf-8 -*-
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="UserActiv | ateKey",
fields=[
(
"id",
models.AutoField(
verbose_n | ame="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
(
"activation_key",
models.CharField(max_length=40, null=True, blank=True),
... |
ArcherSys/ArcherSys | Lib/encodings/cp852.py | Python | mit | 105,146 | 0.01923 | <<<<<<< HEAD
<<<<<<< HEAD
""" Python Character Mapping Codec generated from 'VENDORS/MICSFT/PC/CP852.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,... | db, # OGONEK
0x00f3: 0x02c7, # CARON
0x00f4: 0x02d8, # | BREV |
yenliangl/bitcoin | test/functional/test_framework/blocktools.py | Python | mit | 9,688 | 0.003509 | #!/usr/bin/env python3
# Copyright (c) 2015-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Utilities for manipulating blocks and transactions."""
import struct
import time
import unittest
from... | FACTOR
# Genesis block time (regtest)
TIME_GENESIS_BLOCK = 1296688602
# Coinbase transaction outputs can only be spent after this number of new blocks (network rule)
COINBASE_MATURITY = 100
# Soft-fork activation heights
DERSIG_HEIGHT = 102 # BIP 66
CLTV_HEIGHT = 111 # BIP 65
CSV_ACTIVATION_HEIGHT = 432
# From BI... | f create_block(hashprev=None, coinbase=None, ntime=None, *, version=None, tmpl=None, txlist=None):
"""Create a block (with regtest difficulty)."""
block = CBlock()
if tmpl is None:
tmpl = {}
block.nVersion = version or tmpl.get('version') or VERSIONBITS_LAST_OLD_BLOCK_VERSION
block.nTime = n... |
SiderZhang/p2pns3 | src/emu/bindings/modulegen__gcc_LP64.py | Python | gpl-2.0 | 285,868 | 0.014741 | from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers
import pybindgen.settings
import warnings
class ErrorHandler(pybindgen.settings.ErrorHandler):
def handle_error(self, wrapper, exception, traceback_):
warnings.warn("exception %r in wrapper %s" % (exception, wrapper))
... | Ipv4Address'].implicitly_converts_to(root_module['ns3::Address'])
## ipv4-address.h (module 'network'): | ns3::Ipv4Mask [class]
module.add_class('Ipv4Mask', import_from_module='ns.network')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
module.add_class('Ipv6Address', import_from_module='ns.network')
## ipv6-address.h (module 'network'): ns3::Ipv6Address [class]
root_module['ns3::Ipv6Add... |
johankaito/fufuka | microblog/app/views.py | Python | apache-2.0 | 10,442 | 0.032561 | #from flask.templating import render_template
# Also installed redis
from app import app
from flask import Flask, request, url_for, Response, redirect
from extended_client import extended_client
import json
from jinja2 import Environment, PackageLoader
import logging
from time import sleep
#To access JMX Rest api
impo... | um/(second_counter+0.0)
#Method 2
# print "L: " + str(prevData[second_counter+1]) + " S: " + str(prevData[0])
# mean_rate = abs(prevData[second_counter+1] - prevData[0])/(second_counter+0.0)
#Method 3
# print " ArrLen: " + str(len(prevData))
# print " SC: " + str(second_counter)
# print " L: "... | ta[second_counter] - prevData[0])/(second_counter+0.0)
#print " MeanR " + str(mean_rate)
return mean_rate
else:
mean_rate = -1
return mean_rate
# Threaded method which calculates the offsets
def calculate_offsets():
#Get individual offsets of a consumer
for c in consumers:
global prev_consumer_inf... |
dcsan/ltel | resources/__init__.py | Python | mit | 197 | 0.005076 | d | ef load_resources(app):
# import all our Resources to get them registered
import home
import facebook
import fblogin
home.load_resources(app)
fblogin.load_resources(ap | p)
|
praekelt/django-form-designer | form_designer/models.py | Python | bsd-3-clause | 20,394 | 0.010052 | from django.db import models
from django.utils.translation import ugettext, ugettext_lazy as _
from django.forms import widgets
from django.core.mail import send_mail
from django.conf import settings
from form_designer import app_settings
import re
from form_designer.pickled_object_field import PickledObjectField
from ... | ext. Example: "admin@domain.com, {{ from_email }}" if you have a field named `from_email`.'), max_length=255 | , blank=True, null=True)
mail_from = TemplateCharField(_('Sender address'), max_length=255, help_text=('Your form fields are available as template context. Example: "{{ firstname }} {{ lastname }} <{{ from_email }}>" if you have fields named `first_name`, `last_name`, `from_email`.'), blank=True, null=True)
mai... |
asgeir/pydigilent | pydigilent/lowlevel/dwf.py | Python | mit | 82,320 | 0.01318 | import ctypes
import sys
if sys.platform.startswith("win"):
_dwf = ctypes.cdll.dwf
elif sys.platform.startswith("darwin"):
_dwf = ctypes.cdll.LoadLibrary("libdwf.dylib")
else:
_dwf = ctypes.cdll.LoadLibrary("libdwf.so")
class _types(object):
c_byte_p = ctypes.POINTER(ctypes.c_byte)
c_double_p = ctypes.POINTER(ct... | EExplorer = DEVID(1)
devidDiscovery = DEVID(2)
class DEVVER(ctypes.c_int):
pass
devverEExplorerC = DEVVER(2)
devverEExplorerE = DEVVER(4)
devverEExplorerF = DEVVER(5)
devverDiscoveryA = DEVVER(1)
devverDiscoveryB = DEVVER(2)
devverDiscoveryC = DEVVER(3)
class TRIGSRC(ctypes.c_byte):
pass
trigsrcNone = ... | RC(2)
trigsrcDetectorDigitalIn = TRIGSRC(3)
trigsrcAnalogIn = TRIGSRC(4)
trigsrcDigitalIn = TRIGSRC(5)
trigsrcDigitalOut = TRIGSRC(6)
trigsrcAnalogOut1 = TRIGSRC(7)
trigsrcAnalogOut2 = TRIGSRC(8)
trigsrcAnalogOut3 = TRIGSRC(9)
trigsrcAnalogOut4 = TRIGSRC(10)
trigsrcEx... |
dougmiller/theMetaCity | migrations/versions/551f78f9d8a5_fixed_the_id_and_reference_for_article_.py | Python | mit | 1,176 | 0.002551 | """Fixed the id and reference for article self referencing with foreign key
Revision ID: 551f78f9d8a5
Revises: 8e01032c9c5e
Create Date: 2018-11-17 19:13:52.491349
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '551f78f9d8a5'
down_revision = '8e01032c9c5e'
bra... | )
op.create_foreign_key(None, 'articles', 'articles', ['parent_id'], ['id'])
op.drop_column('articles', 'parent')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('articles', sa.Column('parent', sa.INTEGER(), autoincrement=... | 'foreignkey')
op.create_foreign_key('articles_parent_fkey', 'articles', 'articles', ['parent'], ['id'])
op.drop_column('articles', 'parent_id')
# ### end Alembic commands ###
|
paralab/Dendro4 | python_scripts_sc16/csv_mat.py | Python | gpl-2.0 | 1,046 | 0.048757 | # @author: Milinda Fernando
# School of Computing, University of Utah.
# generate all the slurm jobs for the sc16 poster, energy measurements,
import argparse
from subprocess import call
import os
if __nam | e__ == "__main__":
parser = argparse.ArgumentParser(prog='slurm_pbs')
parser.add_argument('-p','--prefix', help='file prefix that you need to merge')
parser.add_argument('-s','--suffix',help='suffix of the file')
parser.add_argument('-n','--n',help='number of flies that you need to merge')
args=parser.parse_args()... | ','0.000100','0.001000','0.010000','0.100000','0.200000','0.300000','0.400000','0.500000']
#sendCommMap_M_tol_0.010000_npes_4096_pts_100000_ps_4096mat.csv
for tol in tol_list:
inFName=args.prefix+tol+args.suffix+'_'+args.n+'mat'+'.csv'
outFName=args.prefix+tol+args.suffix+'_'+args.n+'mat_comma'+'.csv'
fin=open... |
tebriel/dd-agent | tests/core/test_service_discovery.py | Python | bsd-3-clause | 15,146 | 0.004093 | # stdlib
import copy
import mock
import unittest
# project
from utils.service_discovery.config_stores import get_config_store
from utils.service_discovery.consul_config_store import ConsulStore
from utils.service_discovery.etcd_config_store import EtcdStore
from utils.service_discovery.abstract_config_store import Abs... | )),
}
# raw templates coming straight from the config store
mock_tpls = {
# image_name: ('[check_name]', '[init_tpl]', '[instance_tpl]', expected_python_tpl_list)
'image_0': (
('["check_0"]', '[{}]', '[{"host": "%%host%%"}]'),
[('check_0', {}, {"host": "%%host%%"})])... | (
('["check_1"]', '[{}]', '[{"port": "%%port%%"}]'),
[('check_1', {}, {"port": "%%port%%"})]),
'image_2': (
('["check_2"]', '[{}]', '[{"host": "%%host%%", "port": "%%port%%"}]'),
[('check_2', {}, {"host": "%%host%%", "port": "%%port%%"})]),
'bad_image_0':... |
PersianWikipedia/pywikibot-core | tests/tk_tests.py | Python | mit | 1,761 | 0 | # -*- coding: utf-8 -*-
"""Tests for the Tk UI."""
#
# (C) Pywikibot team, 2008-2019
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, division, unicode_literals
import os
import pywikibot
from pywikibot.tools import PY2
from tests.aspects import unittest, TestCase, Default... | box.show_dialog()
except ImportError as e:
pywikibot.warning(e)
class TestTkinter(DefaultSiteTestCase):
"""Test Tkinter."""
net = True
def testTkinter(self):
"""Test Tkinter window."""
root = tkinter.Tk()
root.resizable(width=tkinter.FALSE, height=tkinter.... | myapp.bind('<Control-d>', myapp.debug)
v = myapp.edit(content, highlight=page.title())
assert v is None
def setUpModule(): # noqa: N802
"""Skip Travis tests if PYWIKIBOT_TEST_GUI variable is not set."""
if os.environ.get('PYWIKIBOT_TEST_GUI', '0') != '1':
raise unittest.SkipTest(... |
andykhov/got-my-pi-on-you | src/mail.py | Python | mit | 1,141 | 0.008764 | import os
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
class Email:
emailCount = 0;
def __init__(self, address, password):
self.address = address
self.password = password
email.emailCount += 1... | = subject
msg["From"] = self.address
msg["To"] = recipient
msg.attach(MIMEText(message))
imgfp = open(imgPath, "rb")
img = MIMEImage(imgfp.read())
imgfp.close()
msg.attach(img)
self.smtpconnect | ion.sendmail(self.address, recipient, msg.as_string())
def closeSMTP(self):
self.smtpconnection.close()
|
CARocha/estudiocafe | encuesta/migrations/0003_auto__chg_field_encuesta_altitud.py | Python | mit | 14,972 | 0.006946 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Encuesta.altitud'
db.alter_column(u'encuesta_encuesta', 'altitud', self.gf('django.db.mod... | 'fecha_nacimiento': ('django.db.models.fields.DateField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
u'encuesta.meses': {
'Meta': {'object_... | {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
u'encuesta.necesidadalimento': {
'Meta': {'object_name': 'NecesidadAlimento'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
... |
eunchong/build | scripts/slave/generate_profile_shim.py | Python | bsd-3-clause | 1,231 | 0.007311 | #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A simple trampoline to generate_profile.py in the src/ directory.
generate_profile.py generates a synthetic user profile.
"""
impo... | ld-dir', help='ignored')
parser.add_option('--target', help='Release or Debug')
parser.add_option('--profile-type-to-generate')
options, args = parser.parse_args()
output_dir = os.path.join(build_directory.GetBuildOutputDirectory(),
options.target,
'gener... | file'),
'-v',
'--browser=' + options.target.lower(),
'--profile-type-to-generate=' + options.profile_type_to_generate,
'--output-dir=' + output_dir,
'--output-format=buildbot',
] + args
return chromium_utils.RunCommand(cmd)
if '__main__' == __name__:
sys.exit(main())
|
pengzhangdev/slackbot | slackbot/plugins/component/database/BookshelfDatabase.py | Python | mit | 2,538 | 0.005516 | #! /usr/bin/env python
#
# whoosh_test.py ---
#
# Filename: whoosh_test.py
# Description:
# Author: Werther Zhang
# Maintainer:
# Created: Mon Oct 23 19:29:49 2017 (+0800)
#
# Change Log:
#
#
import os
from whoosh.index import create_in
from whoosh.index import exists_in
from whoosh.index import open_dir
from whoosh... | t results[0]
from whoosh.index import create_in
from whoosh.fields import *
from whoosh.qparser import QueryParser
class BookshelfDatabase(object):
"""BookshelfDatabase API"""
_DATABASE_DIR = '/mnt/mmc/database/bookshelf'
def __init__(self):
| ix = None
# title (filename or title in db)
# path (relative path in /mnt/mmc/mi)
# author (author of the file)
# content (basename of file ; title; author)
# fileid (hash of path)
# date (file update time in string)
#
# when index, check whether file upd... |
iemejia/incubator-beam | sdks/python/apache_beam/io/gcp/gcsio.py | Python | apache-2.0 | 23,315 | 0.005833 | #
# 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... | me_type (str): Mime type to set for write operations.
Returns:
GCS file object.
Raises:
ValueError: Invalid open file mode.
"""
if mode == 'r' or | mode == 'rb':
downloader = GcsDownloader(
self.client, filename, buffer_size=read_buffer_size)
return io.BufferedReader(
DownloaderStream(
downloader, read_buffer_size=read_buffer_size, mode=mode),
buffer_size=read_buffer_size)
elif mode == 'w' or mode == 'wb... |
phobson/bokeh | tests/test_bokehjs.py | Python | bsd-3-clause | 669 | 0.00299 | from __future_ | _ import print_function
import os
import pytest
from os.path import join
import sys
import unittest
import subprocess
if sys.platform == "win32":
GULP = "gulp.cmd"
else:
GULP = "gulp"
@pytest.mark.js
class TestBokehJS(unittest.TestCase):
def test_bokehjs(self):
os.chdir('bokehjs')
proc =... | mmunicate()
msg = out.decode('utf-8', errors='ignore')
print(msg)
if proc.returncode != 0:
assert False
if __name__ == "__main__":
unittest.main()
|
MichaelReiter/ProgrammingPractice | yield.py | Python | mit | 142 | 0.035211 | d | ef yield_function(n):
for i in range(n):
print "pre", i
yield i
print "post", i
for x in yield_function(10):
print x
| print |
cuescience/cuescience-shop | shop/tests/models/_NatSpecTemplate.py | Python | mit | 293 | 0.003413 | """ @Import | s """
from cuescience_shop.tests.support.support import ClientTestSupport
from django.test.testcases import TestCase
class _NatSpecTemplate(TestCase):
def setUp(self):
self.client_test_support = ClientTestSupport(self)
def test(self):
| """ @MethodBody """ |
YiqunPeng/Leetcode-pyq | solutions/117PopulatingNextRightPointersInEachNodeII.py | Python | gpl-3.0 | 1,205 | 0.005809 | # Definition for binary tree with next pointer.
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
def ... | t(parent, child):
parent = parent.next
while parent:
if parent.left:
child.next = parent.left
return
elif parent.right:
child.next = parent.right
return
else:
... | for node in q:
if node.left:
if node.right:
node.left.next = node.right
else:
find_next(node, node.left)
nxt.append(node.left)
if node.right:
find_next(... |
johnwlockwood/karl_data | karld/io.py | Python | apache-2.0 | 641 | 0 | from karld.loadump import dump_dicts_to_json_file
from karld.loadump import ensure_dir
from karld.loadump import ensure_file_path_dir
from karld.loadump import i_get_csv_data
from karld.loadump import is_ | file_csv
from karld.loadump import i_get_json_data
from karld.loadump import is_file_json
from karld.loadump import raw_line_reader
from karld.loadump import split_csv_file
from karld.loadump import split_file
from karld.loadump import split_file_output
from karld.loadump import split_file_output_csv
from karld.loa... | rom karld.loadump import write_as_json
|
huangkuan/hack | lib/gcloud/logging/test_sink.py | Python | apache-2.0 | 13,154 | 0.000076 | # Copyright 2016 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... | req = conn2._requested[0]
self.assertEqual(req['method'], 'POST')
self.assertEqual(req['path'], '/%s' % TARGET)
| self.assertEqual(req['data'], RESOURCE)
def test_exists_miss_w_bound_client(self):
FULL = 'projects/%s/sinks/%s' % (self.PROJECT, self.SINK_NAME)
conn = _Connection()
CLIENT = _Client(project=self.PROJECT, connection=conn)
sink = self._makeOne(self.SINK_NAME, self.FILTER, sel... |
atmark-techno/atmark-dist | user/python/Lib/test/test_unicodedata.py | Python | gpl-2.0 | 3,846 | 0.00468 | """ Test script for the unicodedata module.
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""#"
import sha
encoding = 'utf-8'
def test_methods():
h = sha.sha()
for i in range(65536):
char = unichr(i)
data = [
... | unicodedata.bidirectional(char),
u | nicodedata.decomposition(char),
str(unicodedata.mirrored(char)),
str(unicodedata.combining(char)),
]
h.update(''.join(data))
return h.hexdigest()
### Run tests
print 'Testing Unicode Database...'
print 'Methods:',
print test_methods()
# In case unicodedata is not avai... |
simplegeo/trialcoverage | setup.py | Python | gpl-2.0 | 2,609 | 0.005366 | #!/usr/bin/env python
# trialcoverage -- plugin to integrate Twisted trial with Ned Batchelder's coverage.py
#
# Author: Brian Warner
# Packaged by: Zooko Wilcox-O'Hearn
# Thanks to: Jonathan Lange
#
# See README.txt for licensing information.
import os, re, sys
try:
from ez_setup import use_setuptools
except Im... | ', 'README.txt' ]
# In case we are building for a .deb with stdeb's sdist_dsc command, we put the
# docs in "share/doc/python-$PKG".
doc_loc = "share/doc/" + PKG
data_files = [(doc_loc, data_fnames)]
setup(name=PKG,
version=verstr,
description="a plugin to integrate Twisted trial with Ned Batchelder's cov... | license='BSD', # see README.txt for details -- there are also alternative licences
packages=find_packages() + ['twisted'],
include_package_data=True,
setup_requires=setup_requires,
classifiers=trove_classifiers,
zip_safe=False, # I prefer unzipped for easier access.
install_require... |
ORMAPtools/MapProduction | Config File Templates/ORMAP_LayersConfig.py | Python | gpl-3.0 | 5,573 | 0.024224 | # ---------------------------------------------------------------------------
# OrmapLayersConfig.py
# Created by: Shad Campbell
# Date: 3/11/2011
# Updated by:
# Description: This is a configuration file to be customized by each county.
# Do not delete any of the items in this file. If they are not in use then... | = ''"
ANNO10_LAYER="Anno0010scale"
ANNO10_QD="\"MapNumber\" = '*MapNumber*' OR \"MapNumber\" is NULL OR \"MapNumber\" = ''"
ANNO20_LAYER="Anno0020scale"
ANNO20_QD="\"MapNumber\" = '*MapNumber*' OR \"MapNumber\" is NULL OR \"MapNumber\" = ''"
ANNO30_LAYER="Anno0030scale"
ANNO30_QD="\"MapNumber\" = '*MapNumb... |
ANNO50_LAYER="Anno0050scale"
ANNO50_QD="\"MapNumber\" = '*MapNumber*' OR \"MapNumber\" is NULL OR \"MapNumber\" = ''"
ANNO60_LAYER="Anno0060scale"
ANNO60_QD="\"MapNumber\" = '*MapNumber*' OR \"MapNumber\" is NULL OR \"MapNumber\" = ''"
ANNO100_LAYER="Anno0100scale"
ANNO100_QD="\"MapNumber\" = '*MapNumber*' O... |
r4mp/evolver_server | evolver_server/app.py | Python | agpl-3.0 | 486 | 0.012346 | import asynci | o
from server import Server
#def main(arguments):
def main():
loop = asyncio.get_event_loop()
server = Server()
asyncio.async(server.run_server())
try:
loop.run_forever()
except KeyboardInterrupt:
print('Received interrupt, closing')
| server.close()
finally:
loop.stop()
loop.close()
if __name__ == '__main__':
#arguments = docopt(__doc__, version='evolver_server 0.1')
#main(arguments)
main()
|
saurabh6790/test-med-app | patches/october_2013/p05_delete_gl_entries_for_cancelled_vouchers.py | Python | agpl-3.0 | 683 | 0.02489 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
def execute():
import webnotes
entries = webnotes.conn.sql("""select voucher_type, voucher_no
from `tabGL Entry` group by voucher_type, voucher_no""", as_dict=1)
for entry in entries:... | try:
cancelled_voucher = webnotes.conn.sql("""select name from `tab%s` where name = %s
and docstatus=2""" % (entry['voucher_type'], "%s"), entry['voucher_no'])
if cancelled_voucher:
webnotes.conn.sql("""delete from | `tabGL Entry` where voucher_type = %s and
voucher_no = %s""", (entry['voucher_type'], entry['voucher_no']))
except:
pass |
Kleptobismol/scikit-bio | skbio/tree/_exception.py | Python | bsd-3-clause | 814 | 0 | from __future__ import absolute_import, division, print_function
# -------------------- | --------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ------------------------------------------------------------------... | ror):
"""Missing length when expected"""
pass
class DuplicateNodeError(TreeError):
"""Duplicate nodes with identical names"""
pass
class MissingNodeError(TreeError):
"""Expecting a node"""
pass
class NoParentError(MissingNodeError):
"""Missing a parent"""
pass
|
vladan-m/ggrc-core | src/ggrc/utils.py | Python | apache-2.0 | 3,658 | 0.013395 | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: david@reciprocitylabs.com
# Maintained By: miha@reciprocitylabs.com
import datetime
import json
import sys
import time
from flask import current_ap... |
v.decode('utf8')
out_dict[k] = v
return out_dict
def merge_dict(destination, source, path=None):
"""merges source into destination"""
if path is None:
path = []
for key in source:
if key in destina | tion:
if isinstance(destination[key], dict) and isinstance(source[key], dict):
merge_dict(destination[key], source[key], path + [str(key)])
elif destination[key] == source[key]:
pass # same leaf value
else:
raise Exception('Conflict at %s' % '.'.join(path + [str(key)]))
el... |
ccordoba12/codenode | codenode/frontend/backend/rpc.py | Python | bsd-3-clause | 499 | 0.008016 |
import xmlrpclib
def listEngineTypes(address):
client = xmlrpclib.ServerProxy(address + '/admin/')
engine_types = client.listEngineTypes()
return engine_types
def allocateEngine(addr | ess, engine_type):
client = xmlrpclib.ServerProxy(str(address) + '/admin/')
access_id = client.allocateEngine(str(engine_type))
return access_id
def interruptInstance(address, instance_id):
client = xmlrpc | lib.ServerProxy(address + '/admin/')
client.interruptInstance(instance_id)
|
soscpd/bee | root/tests/zguide/examples/Python/pathosub.py | Python | mit | 636 | 0.004717 | #
# Pathological subs | criber
# Subscribes to one random topic and prints received messages
#
import sys
import time
from random import randint
import zmq
def main(url=None):
ctx = zmq.Context.instance()
subscriber = ctx.socket(zmq.SUB)
if url is None:
url = "tcp://localhost:5556"
subscriber.connect(url)
subs... | topic == subscription
print data
if __name__ == '__main__':
main(sys.argv[1] if len(sys.argv) > 1 else None)
|
darkspring2015/PyDatcomLab | PyDatcomLab/Core/datcomEventManager.py | Python | mit | 2,614 | 0.013364 | # -*- coding: utf-8 -*-
# 正处于设计开发阶段
from PyQt5 import QtCore
class datcomEvent(QtCore.QEvent):
"""
自定义的Datcom事件系统
"""
dtTypeID = QtCore.QEvent.registerEventType()
def __init__(self, type = dtTypeID):
"""
构造函数
"""
super(datcomEvent, self).__init__(type)... | 称[ 'NMACHLinkTable' ,'RuleNumToCount','RuleIndexToCombo',
self.controlVariables = {} #存储引起变换的变量的名称和值,某些规则可能是多触发的,因此使用dict类型 {'FLTCON/NMACH':'1'}
class datcomEventWarpper(QtCore.QObject):
"""
datcomModel中使用的,作为注册中心使用
"""
def __init__(self):
"""
注册中心的模型
... | (datcomEventWarpper, self).__init__()
#注册中心
#单个模板 {‘receiver':None,'eventLable':'','controlVariables’:[]}
self.registerCenter = []
def registerObject(self, receiver, eventLabel, controlVariables):
"""
向注册中心注册一个事件接收
@param receiver reference to the widget to r... |
dc3-plaso/plaso | tests/parsers/winreg_plugins/lfu.py | Python | apache-2.0 | 7,326 | 0.000956 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the Less Frequently Used (LFU) Windows Registry plugin."""
import unittest
from dfdatetime import filetime as dfdatetime_filetime
from dfwinreg import definitions as dfwinreg_definitions
from dfwinreg import fake as dfwinreg_fake
from plaso.formatters import win... | et=123)
registry_key.AddValue(registry_value)
value_data = u'2592000'.encode(u'utf_16_le')
registry_value = dfwinreg_fake.FakeWinRegistryValue(
u'CriticalSectionTimeout', data=value_data,
data_type=dfwinreg_definitions. | REG_SZ, offset=153)
registry_key.AddValue(registry_value)
value_data = u'\x00'.encode(u'utf_16_le')
registry_value = dfwinreg_fake.FakeWinRegistryValue(
u'ExcludeFromKnownDlls', data=value_data,
data_type=dfwinreg_definitions.REG_MULTI_SZ, offset=163)
registry_key.AddValue(registry_valu... |
WQuanfeng/django-summernote | django_summernote/__init__.py | Python | mit | 258 | 0 | ver | sion_info = (0, 6, 16)
__version__ = version = '.'.join(map(str, version_info))
__project__ = PROJECT = 'django-summernote'
| __author__ = AUTHOR = "Park Hyunwoo <ez.amiryo@gmail.com>"
default_app_config = 'django_summernote.apps.DjangoSummernoteConfig'
|
neozhangthe1/scraper | douban/photo/photo/misc/middlewares.py | Python | gpl-2.0 | 587 | 0.005111 | #encoding: utf-8
from random import choice
from .helper import gen_bids
class CustomCookieMiddleware(object):
def __init__(self):
self.bids = gen_bids()
def process_r | equest(self, request, sp | ider):
request.headers["Cookie"] = 'bid="%s"' % choice(self.bids)
class CustomUserAgentMiddleware(object):
def process_request(self, request, spider):
ug = "Baiduspider"
request.headers["User-Agent"] = ug
class CustomHeadersMiddleware(object):
def process_request(self, request, spide... |
sebrandon1/neutron | neutron/agent/l3/dvr_snat_ns.py | Python | apache-2.0 | 1,810 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... |
@namespaces.check_ns_existence
def delete(self):
ns_ip = ip_lib.IPWrapper(namespace=self.name)
for d in ns_ip.get_devices(exclud | e_loopback=True):
if d.name.startswith(SNAT_INT_DEV_PREFIX):
LOG.debug('Unplugging DVR device %s', d.name)
self.driver.unplug(d.name, namespace=self.name,
prefix=SNAT_INT_DEV_PREFIX)
# TODO(mrsmith): delete ext-gw-port
LOG.d... |
Balannen/LSMASOMM | atom3/Kernel/GraphGrammar/GraphGrammar.py | Python | gpl-3.0 | 1,680 | 0.021429 | # _ GraphGrammar.py __________________________________________________
# This class implements a graph gr | ammar, that is basically an ordered
# collecttion of GGrule's
# ____________________________________________________________________
from GGrule import *
class GraphGrammar:
def __init__(self, GGrules = None):
"Constructor, it receives GGrules, that is a list of GGrule elements"
self.GGrul... | No rewriting system assigned yet
while len(self.GGrules) < len(GGrules): # iterate until each rule is inserted
min = 30000 # set mininum number to a very high number
minRule = None # pointer to rule to be inserted
for rule in GGrules: # search for the minimum execution o... |
PW-Sat2/PWSat2OBC | integration_tests/emulator/beacon_parser/resistance_sensors.py | Python | agpl-3.0 | 4,701 | 0.003829 | RES = 1
TEMP = 0
OUT_OF_RANGE = -999
# Ni1000 relationship between resistances and temperatures [(temp0,resistance0), (temp1,resistance1), (tempN,resistanceN)]
ni1000_5000ppm_values = [(-80, 672.0), (-75, 692.0), (-70, 712.0), (-60, 751.8), (-50, 790.9), (-40, 830.8),
(-30, 871.7), (-20,... | res_to_temp(pt1000_values, pt1000_resistance)
# Public functions
def ni1000_6180ppm_res_to_temp(ni1000_resistance):
"""
This function converts an Ni1000 6180ppm sensor resistance to temperature
Parameters:
===========
ni1000_resistance: Ni1000 6180ppm resistance in Ohms
Return:
... | nce converted to temperature
"""
return res_to_temp(ni1000_6180ppm_values, ni1000_resistance)
# Private functions
def res_to_temp(values_list, resistance):
"""
This function converts a sensor resistance to temperature
Parameters:
===========
values_list: relationship between r... |
rickhurst/Django-non-rel-blog | blogengine/admin.py | Python | bsd-3-clause | 95 | 0 | from blogengine.models import Post
from d | jango.contrib import admin
admin.site.register | (Post)
|
takeicoin/takeicoin | share/qt/clean_mac_info_plist.py | Python | mit | 898 | 0.017817 | #!/usr/bin/env python
# Jonas Schnelli, 2013
# make sure the TakeiCoin-Qt.app contains the right plist (including the right version)
# fix made because of serval bugs in Qt mac dep | loyment (https://bugreports.qt-project.org/browse/QTBUG-21267)
from string import Template
from datetime import date
bitcoinDir = "./";
inFile = bitcoinDir+"/share/qt/Info.plist"
outFile = "TakeiCoin-Qt.app/Contents/Info.plist"
v | ersion = "unknown";
fileForGrabbingVersion = bitcoinDir+"bitcoin-qt.pro"
for line in open(fileForGrabbingVersion):
lineArr = line.replace(" ", "").split("=");
if lineArr[0].startswith("VERSION"):
version = lineArr[1].replace("\n", "");
fIn = open(inFile, "r")
fileContent = fIn.read()
s = Template(fileContent)
... |
gsnedders/Template-Python | t/string_test.py | Python | artistic-2.0 | 6,966 | 0.001005 | from template.test import TestCase, main
class StringTest(TestCase):
def testString(self):
self.Expect(DATA)
DATA = r"""
-- test --
[% USE String -%]
string: [[% String.text %]]
-- expect --
string: []
-- test --
[% USE String 'hello world' -%]
string: [[% String.text %]]
-- expect --
string: [hello world]
... | ' filters=['trim' 'uri'] -%]
[[% String %]]
-- expect --
[foo%20bar]
-- test --
[% USE String ' foo bar ' filter='trim, uri' -%]
[[% String %]]
-- expect --
[foo% | 20bar]
-- test --
[% USE String ' foo bar ' filters='trim, uri' -%]
[[% String %]]
-- expect --
[foo%20bar]
-- test --
[% USE String 'foo bar' filters={ replace=['bar', 'baz'],
trim='', uri='' } -%]
[[% String %]]
-- expect --
[foo%20baz]
-- test --
[% USE String 'foo bar' filters=[ 'replace', ['bar', 'ba... |
IPIDataLab/PPP_Loader | python/data_norm.py | Python | gpl-2.0 | 12,915 | 0.022145 | #!/usr/bin/python
import csv
import json
import datetime
import time
from utils import dateToISOString
#############################
#############################
# This file normalizes incoming
# data from the morph.io API
# to conform with the Mongo
# data model.
#############################
####################... | Alpha']]['ca | pital'],
'tcc_capital_loc': countries[entry['tccIso3Alpha']]['capital_loc'],
'tcc_continent': countries[entry['tccIso3Alpha']]['continent'],
'tcc_un_region': countries[entry['tccIso3Alpha']]['un_region'],
'tcc_un_bloc': countries[entry['tccIso3Alpha']]['un_bloc'],
'mission': 'all',
'total': 0,
... |
Strangemother/python-state-machine | scratch/machine_2/core/conditions.py | Python | mit | 3,066 | 0.005545 | '''
A condition
'''
from base import Base
from compares import const
class ComparisonMixin(object):
'''
Compare two values with a comparison utility
to denote if a change has validated.
'''
def compare(self, a, b, ctype=None):
'''
compare 'a' against 'b' for a comparison of `c | type`
by defauly ctype will compare for an exact match
'''
if ctype is None:
ctype = const.EXACT
# internal importer for core.compares.simple.
Comp = self.get_comparison_class(ctype)
# new class of
comp = Comp(self)
# perform comparison
... | p.match(a,b)
def get_comparison_class(self, compare):
'''
Return the compare class by string
'''
m = __import__('core.compares.simple', fromlist=[compare])
# print 'module', m
# print 'compare', compare
k = getattr(m, compare)
return k
class Condi... |
cpantel/gravityFalls | Coursera Crypto 1/StatisticalTests.py | Python | gpl-2.0 | 217 | 0.013825 | #!/usr/bin/python
import sys
class StatisticalTest(object):
def __init__(self):
| pass
maxRunOfLength(x) =< 10 . log2(n)
| count0(x) - count1( | x) | <= 10.sqrt(n)
| count00(x) - n/4 | <= 10.sqrt(n)
|
keremgocen/demo-gui-python | py3env/bin/viewer.py | Python | apache-2.0 | 1,064 | 0.00094 | #!/Users/kerem/github-stuff/demo-gui-python/py3env/bin/python3
#
# The Python Imaging Library
# $Id$
#
from __future__ import print_function
import sys
if sys.version_info[0] > 2:
import tkinter
else:
import Tkinter as tkinter
from PIL import Image, ImageTk
#
# an image viewer
cla | ss UI(tkinter.Label):
def __init__(self, master, im):
if im.mode == "1":
# bitmap image
self.image = ImageTk.BitmapImage(im, foreground="white")
tkinter.Label.__init__(self, master, image=self.image, bd=0,
bg="black")
else:
... | k.PhotoImage(im)
tkinter.Label.__init__(self, master, image=self.image, bd=0)
#
# script interface
if __name__ == "__main__":
if not sys.argv[1:]:
print("Syntax: python viewer.py imagefile")
sys.exit(1)
filename = sys.argv[1]
root = tkinter.Tk()
root.title(filename)
... |
vladimir-v-diaz/securesystemslib | tests/test_formats.py | Python | mit | 15,792 | 0.005256 | #!/usr/bin/env python
"""
<Program Name>
test_formats.py
<Author>
Vladimir Diaz <vladimir.v.diaz@gmail.com>
<Started>
January 2017 (modified from TUF's original formats.py)
<Copyright>
See LICENSE for licensing information.
<Purpose>
Unit test for 'formats.py'
"""
# Help with Python 3 compatibility, whe... | scheme': 'rsassa-pss-sha256',
'keyval': {'public': 'pubkey',
'private': ''}}),
'RSAKEY_SCHEMA': (securesystemslib.formats.RSAKEY_SCHEMA,
{'keytype': 'rsa',
'scheme': 'rsassa-pss-sha256',
... | f',
'keyval': {'public': 'pubkey',
'private': 'privkey'}}),
'FILEINFO_SCHEMA': (securesystemslib.formats.FILEINFO_SCHEMA,
{'length': 1024,
'hashes': {'sha256': 'A4582BCF323BCEF'},
... |
Reagankm/KnockKnock | venv/lib/python3.4/site-packages/nltk/tbl/demo.py | Python | gpl-2.0 | 14,715 | 0.006116 | # -*- coding: utf-8 -*-
# Natural Language Toolkit: Transformation-based learning
#
# Copyright (C) 2001-2015 NLTK Project
# Author: Marcus Uneson <marcus.uneson@gmail.com>
# based on previous (nltk2) version by
# Christopher Maloof, Edward Loper, Steven Bird
# URL: <http://nltk.org/>
# For license information, see... | es = list(Template.expand([wordtpls, tagtpls], combinations=(1,3)))
print("Generated {0} templates for transformation-based learning".format(len(templates | )))
postag(templates=templates, incremental_stats=True, template_stats=True)
def demo_learning_curve():
"""
Plot a learning curve -- the contribution on tagging accuracy of
the individual rules.
Note: requires matplotlib
"""
postag(incremental_stats=True, separate_baseline_data=True, learni... |
HSAR/Ficlatte | comment/urls.py | Python | agpl-3.0 | 1,083 | 0.004625 | #coding: utf-8
#This file is part of Ficlatté.
#Copyright © 2015-2017 Paul Robertson, Jim Stitzel and Shu Sam Chen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of version 3 of the GNU Affero General Public
# License as published by the Free Software Foundation
#... | but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Pu | blic License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^submit/$', 'comment.views.submit_comment', name='su... |
tomprince/gemrb | gemrb/GUIScripts/iwd2/Class.py | Python | gpl-2.0 | 5,585 | 0.03026 | # GemRB - Infinity Engine Emulator
# Copyright (C) 2003 The GemRB Project
#
# 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 versi... | .SetEvent(IE_GUI_BUTTON_ON_PRESS, BackPress)
ClassWindow.SetVisible(WINDOW_VISIBLE)
return
def ClassPress():
global Ha | sSubClass
AdjustTextArea()
if HasSubClass == 0:
return
DoneButton.SetState(IE_GUI_BUTTON_DISABLED)
j = 0
for i in range(1,ClassCount):
ClassName = CommonTables.Classes.GetRowName(i-1)
Allowed = CommonTables.Classes.GetValue(ClassName, "CLASS")
if Allowed > 0:
continue
Button = ClassWindow.GetControl... |
harshilasu/LinkurApp | y/google-cloud-sdk/platform/gcutil/lib/google_api_python_client/oauth2client/util.py | Python | gpl-3.0 | 5,523 | 0.004527 | #!/usr/bin/env python
#
# Copyright 2010 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... | (10) # Raises exception.
fn(required_kw=10) # Ok.
When defining instance or class methods always remember to account for
'self' and 'cl | s':
class MyClass(object):
@positional(2)
def my_method(self, pos1, kwonly1=None):
...
@classmethod
@positional(2)
def my_method(cls, pos1, kwonly1=None):
...
The positional decorator behavior is controlled by the
--positional_parameters_enforcem... |
steventimberman/masterDebater | venv/lib/python2.7/site-packages/django_fluent_comments-1.4.3.dist-info/top_level.txt.py | Python | mit | 16 | 0 | XXXXXXX | XXXXXXXX
| |
willprice/mentor-finder | mentor_finder/models/county.py | Python | gpl-3.0 | 3,324 | 0.000301 | # -*- coding: utf-8 -*-
_counties = [
("Aberdeenshire", "Aberdeenshire"),
("Anglesey", "Anglesey"),
("Angus", "Angus"),
("Argyll", "Argyll"),
("Ayrshire", "Ayrshire"),
("Banffshire", "Banffshire"),
("Bedfordshire", "Bedfordshire"),
("Berwickshire", "Berwickshire"),
("Breconshire", "B... | hamshire"),
("Orkney", "Orkney"),
("Oxfordshire", "Oxfordshire"),
("Peebl | eshire", "Peebleshire"),
("Pembrokeshire", "Pembrokeshire"),
("Perthshire", "Perthshire"),
("Radnorshire", "Radnorshire"),
("Renfrewshire", "Renfrewshire"),
("Ross & Cromarty", "Ross & Cromarty"),
("Roxburghshire", "Roxburghshire"),
("Selkirkshire", "Selkirkshire"),
("Shetland", "Shetlan... |
openbig/odoo-contract | sale_contractmanagement/idoit_license_gen.py | Python | agpl-3.0 | 2,980 | 0.003357 | # -*- coding: utf-8 -*-
from hashlib import sha1
from phpserialize import dumps
from calendar import timegm
from time import strptime
import zlib
#calendar.timegm(time.strptime('01/12/2011', '%d/%m/%Y'))
def create(data):
assert isinstance(data, dict)
assert 'request_data' in data
assert 'contract_data' i... | _data'], list)
mod_identifiers = {
'viva': 'viva',
'rfc': 'rfc',
'relocate_ci': 'CI-Umzug',
| 'swapci': 'Geräteaustausch',
}
contract_data = data['request_data']['contract_data']
product_data = data['request_data']['product_data']
license_data = {
'C__LICENCE__OBJECT_COUNT': 0,
'C__LICENCE__DB_NAME': contract_data['db_name'] or '',
'C__LICENCE__CUSTOMER_NAME': contract_d... |
jjhelmus/scipy | scipy/stats/_multivariate.py | Python | bsd-3-clause | 114,780 | 0.000741 | #
# Author: Joris Vankerschaver 2013
#
from __future__ import division, print_function, absolute_import
import math
import numpy as np
import scipy.linalg
from scipy.misc import doccer
from scipy.special import gammaln, psi, multigammaln, xlogy, entr
from scipy._lib._util import check_random_state
from scipy.linalg.bl... | \
"""See class definition for a detailed description of parameters."""
mvn_docdict_params = {
'_mvn_doc_default_callparams': _mvn_doc_default_callparams,
'_mvn_doc_callparams_note': _mvn_doc_callparams_note,
'_doc_random_state': _doc_random_state
}
mvn_docdict_noparams = {
'_mvn_doc_default_callp... | oc_random_state
}
class multivariate_normal_gen(multi_rv_generic):
r"""
A multivariate normal random var |
EvanMurawski/BeamAnalyzer | beamanalyzer/test/test.py | Python | mit | 6,877 | 0.009597 | __author__ = 'Evan Murawski'
import unittest
import backend
from backend.interactions import *
from backend.beam import Beam
import backend.solver as solver
from backend.solver import SolverError
import backend.shearmomentgenerator as shearmomentgenerator
from backend.shearmomentgenerator import Shear_Moment_... | bs(shear_moment[int(10/self.STEP_SIZE/2) +2][0] - (-5)) < self.ALMOST
assert abs(shear_moment[int(10/self.STEP_SIZE) -1][0] - (-5)) < self.ALMOST
def test_beam1(self):
solver.solve(self.beams[1])
#Test solution
self.assertEqual(-10, self.beams[1].interactions[0].magnitude)
... | tor.generate_numerical(self.beams[1], self.STEP_SIZE)
#Test shear
for item in shear_moment:
assert abs(item[0] - (-10)) < self.ALMOST
#Test moment
assert abs(shear_moment[0][1] - 95) < self.ALMOST
assert abs(shear_moment[int(4/self.STEP_SIZE - 1)][1] - 55 ) ... |
rven/odoo | addons/hr_contract/models/hr_contract.py | Python | agpl-3.0 | 11,699 | 0.005214 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from datetime import date
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
from odoo.osv import expression
class Contract(models.Mode... | tate': 'blocked'})
self.search([
('state', '=', 'open'),
| '|',
('date_end', '<=', fields.Date.to_string(date.today() + relativedelta(days=1))),
('visa_ex |
threatstream/mnemosyne | webapi/admin.py | Python | gpl-3.0 | 2,846 | 0.001054 | # Copyright (C) 2013 Johnny Vestergaard <jkv@unixcluster.dk>
#
# 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 ... | dict(ok=True, msg='')
except Exception, e:
return dict(ok=False, msg=e.message)
@post('/create_role')
def create_role():
try:
shared_state.auth.create_role(post_get('role'), post_get('level'))
return dict(ok=True, msg='')
except Exception, e:
return dict(ok=False, msg=e.me... | ict(ok=True, msg='')
except Exception, e:
return dict(ok=False, msg=e.message)
def postd():
return bottle.request.forms
def post_get(name, default=''):
return bottle.request.POST.get(name, default).strip() |
unpingco/csvkit | csvkit/convert/ndjs.py | Python | mit | 1,769 | 0.005088 | #!/usr/bin/env python
try:
from collections import OrderedDict
import json
except ImportError:
from ordereddict import OrderedDict
import simplejson as json
import itertools
import six
from csvkit import CSVKitWriter
def parse_object(obj, path=''):
"""
Recursively parse JSON objects and a di... | .writerow(row)
output = o.getvalue()
o.close()
| return output
|
usersource/anno | anno_gec_server/api/anno_api.py | Python | mpl-2.0 | 18,371 | 0.003212 | """
API implemented using Google Cloud Endpoints on :class:`.Anno` model
.. http:get:: /anno/1.0/anno/(id)
``anno.anno.get`` - Get the details for a specific anno
:param int id: id of the anno
:returns: details of the anno :class:`.AnnoResponseMessage`
.. http:get:: /anno/1.0/anno
``anno.anno.lis... | TRY:
return Anno.query_by_country(request.app, user)
elif request.query_type == AnnoQueryType.COMMUNITY:
community = Community.get_by_id(request.community)
return Anno.query_by_community(community, limit, select_projection, curs, us | er)
elif request.query_type == AnnoQueryType.APP:
app = AppInfo.get |
danilobellini/dose | dose/terminal.py | Python | gpl-3.0 | 7,486 | 0.002404 | """Dose GUI for TDD: colored terminal."""
from __future__ import print_function
import os, sys, subprocess, signal, colorama
from .misc import attr_item_call_auto_cache
DEFAULT_TERMINAL_WIDTH = 80
class TerminalSize(object):
r"""
Console/terminal width information getter.
There should be only one insta... | he width that can be safely used with a
``"\n"`` at the end without | skipping a line.
The ``retrieve_width`` method can be called to update the ``width``
attribute, but there's also a SIGWINCH (SIGnal: WINdow CHanged)
signal handler updating the width if that's a valid signal in the
operating system.
Several strategies for getting the terminal width are combined
... |
brendan-w/python-OBD | obd/utils.py | Python | gpl-2.0 | 6,075 | 0.000988 | # -*- coding: utf-8 -*-
########################################################################
# #
# python-OBD: A python OBD-II serial module derived from pyobd #
# #
# C... | #
# utils.py #
# #
# This file is part of python-OBD (a derivative of pyOBD) #
# #
# python-OBD is free softw... | odify #
# 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. #
# #
# python-OBD is di... |
evernote/pootle | pootle/apps/staticpages/urls.py | Python | gpl-2.0 | 1,786 | 0.00112 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2012-2013 Zuza Software Foundation
# Copyright 2013 Evernote Corporation
#
# This file is part of Pootle.
#
# Pootle 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 Softw... | im | plied 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 translate; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02... |
nborkowska/kpir2 | kpir2/users/migrations/0004_auto_20160403_2348.py | Python | gpl-3.0 | 581 | 0.001721 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-03 23:48
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0003_auto_2 | 0160403_2058'),
]
operations = [
migrations.AlterField(
model_name='usercompanyinfo',
name='user',
field=models.ForeignKey(on_delete=django | .db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
|
elyezer/robottelo | tests/foreman/ui/test_isodownload.py | Python | gpl-3.0 | 4,978 | 0 | """Test class for ISO downloads UI
:Requirement: Isodownload
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: UI
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
from robottelo.decorators import run_only_on, stubbed, tier1
from robottelo.test import UITestCase
class ISODownloadTes... | """
@stubbed()
@run_only_on('sat')
@tier1
def test_positive_mount(self):
"""Mounting iso to directory accessible to satellite6 works
:id: 44d3c8fa-c01f-438c-b83e-8f6894befbbf
| :Steps:
1. download the iso
2. upload it to sat6 system
3. mount it a local sat6 directory
:expectedresults: iso is mounted to sat6 local directory
:caseautomation: notautomated
:CaseImportance: Critical
"""
@stubbed()
@run_only_on(... |
thegooglecodearchive/marave | marave/editor/spelltextedit.py | Python | gpl-2.0 | 13,856 | 0.009454 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__license__ = 'MIT'
__copyright__ = '2009, John Schember <john@nachtimwald.com>'
__docformat__ = 'restructuredtext en'
import re
import sys
import os
import codecs
# Spell checker support
try:
import enchant
except ImportError:
enchant = None
# Syntax highligh... | e spelling suggests to the menu if ther | e are
# suggestions.
if len(spell_menu.actions()) != 0:
popup_menu.insertSeparator(popup_menu.actions()[0])
popup_menu.insertMenu(popup_menu.actions()[0], spell_menu)
# FIXME: add change dict and dis... |
Ademan/NumPy-GSoC | numpy/core/fromnumeric.py | Python | bsd-3-clause | 71,769 | 0.000195 | # Module containing non-deprecated functions borrowed from Numeric.
__docformat__ = "restructuredtext en"
# functions that are now methods
__all__ = ['take', 'reshape', 'choose', 'repeat', 'put',
'swapaxes', 'transpose', 'sort', 'argsort', 'argmax', 'argmin',
'searchsorted', 'alen',
'r... | ` will be treated:
* 'raise' : an exception is raised
* 'wrap' : value becomes value mod `n`
* 'clip' : values < 0 are mapped to 0, values > n-1 are mapped to n-1
Returns
-------
merged_array : array
The merg | ed result.
Raises
------
ValueError: shape mismatch
If `a` and each choice array are not all broadcastable to the same
shape.
See Also
--------
ndarray.choose : equivalent method
Notes
-----
To reduce the chance of misinterpretation, even though the fo |
vpikulik/lymph | lymph/core/monitoring/pusher.py | Python | apache-2.0 | 1,268 | 0.000789 | import logging
import time
import gevent
import msgpack
import zmq.green as zmq
from lymph.core.components import Component
from lymph.utils.sockets import bind_zmq_socket
logger = logging.getLogger(__name__)
class MonitorPusher(Component):
def __init__(self, container, aggregator, endpoint='127.0.0.1', inter... | .info('binding monitoring endpoint %s', self.endpoint)
self.aggregator = aggregator
def on_start(self):
self.loop_greenlet = self.container.spawn(self.loop)
def on_stop(self, **kwargs):
self.loop_greenlet.kill()
def loop(self):
last_stats | = time.monotonic()
while True:
gevent.sleep(self.interval)
dt = time.monotonic() - last_stats
series = list(self.aggregator)
stats = {
'time': time.time(),
'series': series,
}
last_stats += dt
se... |
ikoula/cloudstack | scripts/vm/network/vnet/cloudstack_pluginlib.py | Python | gpl-2.0 | 17,502 | 0.004571 | # 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... | PATH, "vif-param-get", "uuid=%s" % vif_uuid, "param-name=other-config",
"param-key=cloudstack-network-id"])
return vnet
def get_network_id_for_tunnel_port(tunnelif_name):
vnet = do_cmd([VSCTL_PATH, "get", "interface", tunnelif_name, "options:cloudstack-network-id"])
return vne... | ofport, out_ofports):
action = "".join("output:%s," %ofport for ofport in out_ofports)[:-1]
add_flow(bridge, priority=1100, in_port= |
JackDanger/sentry | src/sentry/web/frontend/auth_close.py | Python | bsd-3-clause | 561 | 0.003565 | from __future__ import absolute_import
from django.shortcuts import render_to_response
from sentry. | web.frontend.base import BaseView
class AuthCloseView(BaseView):
"""This is a view to handle when sentry log in has been opened from
another window. This view loads an html page with a script that sends a message
back to the window opener and closes the window"""
def handle(self, request):
log... | {'logged_in': logged_in})
|
jim-cooley/abletonremotescripts | remote-scripts/samples/APC40_20/ShiftableSelectorComponent.py | Python | apache-2.0 | 9,563 | 0.013071 |
import Live
from _Framework.ModeSelectorComponent import ModeSelectorComponent
from _Framework.ButtonElement import ButtonElement
#from consts import * #see below (not used)
#MANUFACTURER_ID = 71
#ABLETON_MODE = 65
#NOTE_MODE = 65 #67 = APC20 Note Mode; 65 = APC40 Ableton Mode 1
class ShiftableSelectorComponent(ModeS... | d:
#for button in self._select_buttons: #turn off track select buttons (only needed for APC20)
#button.turn_off( | )
self._matrix.reset() #turn off the clip launch grid LEDs
#mode_byte = NOTE_MODE #= 67 for APC20 Note Mode, send as part of sysex string to enable Note Mode
if self._note_mode_active: #if note mode is already on, turn it off:
#mode_byte = ABLETON_MODE... |
anderscui/nails | nails/texts.py | Python | mit | 534 | 0 | # coding=utf-8
import re
RE_WHITESPACE = re.compile(r"(\s)+", re.UNICODE)
def remove_postfix(s, postfix):
if s.endswith(postfix):
return s[:len(s)-len(postfix)]
def r | emove_prefix(s, p | refix):
if s.startswith(prefix):
return s[len(prefix):]
def flatten2str(obj):
if obj is None:
return ''
if isinstance(obj, str):
return obj
if isinstance(obj, (list, tuple)):
return ' '.join(obj)
return str(obj)
def compress_whitespaces(s):
return RE_WHITESPAC... |
platformio/platformio | platformio/managers/package.py | Python | apache-2.0 | 29,447 | 0.000815 | # Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# 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 appli... | ngines", {}):
# if PkgRepoMixin.PIO_VERSION not in requirements.SimpleSpec(
# v['engines']['platformio']):
# continue
specver = semantic_version.Version(v["version"])
if reqspec and specver | not in reqspec:
continue
if not item or semantic_version.Version(item["version"]) < specver:
item = v
return item
def get_latest_repo_version( # pylint: disable=unused-argument
self, name, requirements, silent=False
):
version = None
... |
GrognardsFromHell/TemplePlus | tpdatasrc/tpgamefiles/rules/d20_actions/action02600_feat_divine_armor.py | Python | mit | 348 | 0.04023 | from toee import *
i | mport tpactions
def GetActionName():
return "Divine Armor"
def GetActionDefinitionFlags():
return D20ADF_None
def GetTargetingClassification():
return D20TC_Target0
def GetActionCostType():
return D20ACT_Swift_Action
def AddToSequence(d20action, action_seq, tb_status):
action_seq.add_acti | on(d20action)
return AEC_OK |
bearops/ebzl | ebzl/lib/format.py | Python | bsd-3-clause | 1,944 | 0.000514 | TEXT = "text"
BASH = "bash"
JSON = "json"
DOCKERENV = "dockerenv"
NAME_VALUE_DICT = "nvdict"
DEFAULT = TEXT
CHOICES = (TEXT, BASH, JSON, DOCKERENV, NAME_VALUE_DICT)
def print_dict(dictionary, format_=None):
"""Print a dictionary in a given format. Defaults to text."""
format_ = format_ or DEFAULT
... | value in iter(sorted(dictionary.items())):
print("%s=%s" % (key, value))
elif format_ == BASH:
for key, value in iter(sorted(dictionary.items())):
print("export %s=%s" % (key, value))
elif format_ == JSON:
print(json.dumps(dictionary))
elif format_ == NAME_VALUE_DICT... | print("[")
for key, value in iter(sorted(dictionary.items())):
print('{"name": "%s", "value": "%s"},' % (key, value))
print("]")
def print_list(list_, format_=None):
"""Print a list in a given format. Defaults to text."""
format_ = format_ or DEFAULT
if format_ == TEXT:
... |
matrix-org/synapse | tests/rest/client/test_consent.py | Python | apache-2.0 | 4,541 | 0.00044 | # Copyright 2018 New Vector
#
# 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, s... | channel = make_request(
self.reactor,
FakeSite(resource, self.reactor),
"POST",
consent_uri + "&v=" + version,
access_token=access_token,
shorthand=False,
)
self.assertEqual(channel.code, HTTPStatus.OK)
# Fetch the consent ... | channel = make_request(
self.reactor,
FakeSite(resource, self.reactor),
"GET",
consent_uri,
access_token=access_token,
shorthand=False,
)
self.assertEqual(channel.code, HTTPStatus.OK)
# Get the version from the body, and c... |
MaxWayne/Beginning-Game-Development-with-Python-and-Pygame | Chapter 12/model3d.py | Python | mit | 5,468 | 0.007315 |
from OpenGL.GL import *
from OpenGL.GLU import *
import pygame
import os.path
class Material(object):
def __init__(self):
self.name = ""
self.texture_fname = None
self.texture_id = None
class FaceGroup(object):
def __init__(self):
self.tri_indices = []
self.mater... | resources(self):
# Delete the display list and textures
if self.display_list_id is not None:
gl | DeleteLists(self.display_list_id, 1)
self.display_list_id = None
# Delete any textures we used
for material in self.materials.values():
if material.texture_id is not None:
glDeleteTextures(material.texture_id)
... |
denzp/cef3 | tools/gyp_cef.py | Python | bsd-3-clause | 797 | 0 | # Copyright (c) 2013 The Chromium Embedded Framework Authors.
# Portions copyright 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE fi | le.
# This file is (possibly, depending on python version) imported by gyp_cef
# when it creates sub-processes through the multiprocessing library.
# Importing in Python 2.6 (fixed in 2.7) on Windows doesn't search for
# imports that don't end in .py (and aren't directories with an
# __init__.py). This wrapper makes ... | t gyp_cef" work with those old
# versions and makes it possible to execute gyp_cef.py directly on Windows
# where the extension is useful.
import os
path = os.path.abspath(os.path.split(__file__)[0])
execfile(os.path.join(path, 'gyp_cef'))
|
slyphon/pants | tests/python/pants_test/backend/jvm/tasks/test_bundle_create.py | Python | apache-2.0 | 5,152 | 0.003882 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from pant... | target_type=JvmBinary,
source='Foo.java',
dependencies=[jar_lib])
app_target = self.make_target(spec='//foo:foo-app',
target_type=JvmApp,
basenam... | = self.create_artifact(org='org.example', name='foo', rev='1.0.0')
zip_artifact = self.create_artifact(org='org.pantsbuild', name='bar', rev='2.0.0', ext='zip')
bundle_artifact = self.create_artifact(org='org.apache', name='baz', rev='3.0.0',
classifier='tests')
t... |
toymachine/concurrence | test/testextra.py | Python | bsd-3-clause | 3,776 | 0.011388 | from __future__ import with_statement
import logging
import time
import sys
from concurrence import unittest, Tasklet, Channel, Lock, Semaphore, TaskletPool, DeferredQueue, Deque, TimeoutError, TaskletError, JoinError, Message
class TestTaskletPool(unittest.TestCase):
def testBasic(self):
d = Deque()
... | (1)
for i in range(10):
d.defer(f, i)
Tasklet.sleep(1)
class TestPrimitives(unittest.TestCase):
def testSemaphore(self):
sema = Semap | hore(4)
self.assertEquals(True, sema.acquire())
self.assertEquals(3, sema.count)
self.assertEquals(True, sema.acquire())
self.assertEquals(2, sema.count)
self.assertEquals(True, sema.acquire())
self.assertEquals(1, sema.count)
self.assertEq... |
jimsrc/seatos | shared_lib/shared_funcs.py | Python | mit | 54,269 | 0.01382 | #!/usr/bin/env ipython
# -*- coding: utf-8 -*-
from datetime import datetime, time, timedelta
import numpy as np
import console_colors as ccl
from scipy.io.netcdf import netcdf_file
from ShiftTimes import ShiftCorrection, ShiftDts
import os, argparse
import h5py
from h5py import File as h5
from numpy import (
mean... | flag
VAR_medi[i] = median(VAR_adap.T[i,cond])# medi | ana entre los valores q no tienen flag
VAR_std[i] = std(VAR_adap.T[i,cond]) # std del mismo conjunto de datos
tnorm = adap[0][0]
return [nok, nbad, tnorm, VAR_avrg, VAR_medi, VAR_std, ndata]
def mvs_for_each_event(VAR_adap, nbin, nwndw, Enough, verbose=False):
|
raphaelm/django-i18nfield | tests/settings.py | Python | apache-2.0 | 1,801 | 0 | import os
from django.utils.translation import gettext_lazy as _
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'kk0ai8i0dm-8^%&0&+e-rsmk8#t&)6r*y!wh=xx7l12+6k5mg4'
DEBUG = True
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
... | 'tests.testapp'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'dja... | onsMiddleware',
]
ROOT_URLCONF = 'demoproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
... |
AlexYu-beta/CppTemplateProgrammingDemo | Demo1_8/demo1_8.py | Python | gpl-3.0 | 278 | 0.061151 | from callb | ack_event import *
def getOddNumber(k,getEvenNumber): return 1+getEvenNumber(k)
def main():
k=1
i=getOddNumber(k,double);
print(i)
i=getOddNumber(k,quadruple);
print(i)
i=getOddNumber(k,lambda x:x*8)
print(i)
if _ | _name__=="__main__":main() |
TeamSPoon/logicmoo_workspace | packs_web/butterfly/lib/python3.7/site-packages/isort/profiles.py | Python | mit | 1,601 | 0.000625 | """Common profiles are defined here to be easily used within a project using --profile {name}"""
from typing import Any, Dict
black = {
"multi_line_output": 3,
"include_trailing_comma": True,
"force_grid_wrap": 0,
"use_parentheses": True,
"ensure_newline_before_comments": True,
"line_length": 8... | rce_single_line": True,
"force_sort_within_sections": True,
"lexicographical": True, |
"single_line_exclusions": ("typing",),
"order_by_type": False,
"group_by_package": True,
}
open_stack = {
"force_single_line": True,
"force_sort_within_sections": True,
"lexicographical": True,
}
plone = {
"force_alphabetical_sort": True,
"force_single_line": True,
"lines_after_impo... |
amgowano/oppia | core/domain/collection_domain_test.py | Python | apache-2.0 | 25,252 | 0.000158 | # coding: utf-8
#
# Copyright 2015 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... | _error(
'An objective must be specified for the collection.')
| self.collection.objective = 'An objective'
# Having no category is fine for non-strict validation.
self.collection.validate(strict=False)
# But it's not okay for strict validation.
self._assert_validation_error(
'A category must be specified for the collection.')
... |
mozman/ezdxf | tests/test_02_dxf_graphics/test_243_replace_entity.py | Python | mit | 3,603 | 0 | # Copyright (c) 2020, Manfred Moitzi
# License: MIT License
import pytest
import ezdxf
from ezdxf.entities.dxfgfx import add_entity, replace_entity
from ezdxf.entities import Point
@pytest.fixture(scope="module")
def msp():
return ezdxf.new().modelspace()
@pytest.fixture(scope="module")
def db(msp):
return ... | nvert_ellipse_to_spline(msp, db):
ellipse = msp.add_ellipse(center=(3, 3), major_axis=(2, 0), ratio=0.5)
spline = ellipse.to_spline(replace=False)
assert ellipse.dxf.handle in db
assert spline.dxftype() == "SPLINE"
assert spline.dxf.handle in db
assert ellipse in msp
assert spline in msp
d... | msp, db):
ellipse = msp.add_ellipse(center=(3, 3), major_axis=(2, 0), ratio=0.5)
ellipse_handle = ellipse.dxf.handle
spline = ellipse.to_spline(replace=True)
assert ellipse.is_alive is False
assert spline.dxftype() == "SPLINE"
assert spline.dxf.handle in db
assert spline.dxf.handle == ellips... |
ewheeler/tracpro | tracpro/profiles/models.py | Python | bsd-3-clause | 509 | 0.003929 | from __future__ import absolute_import, unicode_literals
from django.contrib.auth | .models import User
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Profile(models.Model):
"""
Extension for the user class
"""
user = models.OneToOneField(User)
full_name = models.CharField(verbose_name=_("Full name"), max_length=128, null=True)
ch... | on next login"))
|
sai9/weewx-gitsvn | extensions/pmon/install.py | Python | gpl-3.0 | 1,514 | 0.001321 | # $Id$
# installer for pmon
# Copyright 2014 Matthew Wall
from setup import ExtensionInstaller
def loader():
return ProcessMonitorInstaller()
class ProcessMonitorInstaller(ExtensionInstaller):
def __init__(self):
super(ProcessMonitorInstaller, self).__init__(
version="0.2",
na... | 'process': 'weewxd'},
'DataBindings': {
'pmon_binding': {
'database': 'pmon_sqlite',
'table_name': 'archive',
'manager': 'weewx.manager.DaySummaryManager',
'schema': 'user.pmon.sche... | 'pmon_sqlite': {
'database_name': 'pmon.sdb',
'driver': 'weedb.sqlite'}},
'StdReport': {
'pmon': {
'skin': 'pmon',
'HTML_ROOT': 'pmon'}}},
files=[('bin/user', ['bin/u... |
openstack/murano | api-ref/source/conf.py | Python | apache-2.0 | 6,670 | 0 | # -*- coding: utf-8 -*-
#
# 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, softwa... | the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# Additional stuff for the LaTeX preamble.
# latex_preamble = ''
# Documents to append as an appendix to all manuals.
# | latex_appendices = []
# If false, no module index is generated.
# latex_use_modindex = True
|
BadDNA/anolis | web/env/lib/python2.6/site-packages/pip-0.7.2-py2.6.egg/pip/venv.py | Python | bsd-3-clause | 1,972 | 0.001521 | """Tools for working with virtualenv environments"""
import os
import sys
import subprocess
from pip.exceptions import BadCommand
from pip.log import logger
def restart_in_venv(venv, base, site_packages, args):
"""
Restart this script using the interpreter in the given virtual environment
"""
if base ... | lative one makes no sense (or does it?)
if os.path.isabs(base):
venv = os.path.join(base, venv)
if venv.startswith('~'):
| venv = os.path.expanduser(venv)
if not os.path.exists(venv):
try:
import virtualenv
except ImportError:
print 'The virtual environment does not exist: %s' % venv
print 'and virtualenv is not installed, so a new environment cannot be created'
sys... |
twiindan/selenium_lessons | 04_Selenium/exercices/expedia.py | Python | apache-2.0 | 654 | 0.007645 | from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
# Configure the baseURL
baseUrl = "https://www.expedia.es"
# Create a webDriver instance and maximize window
driver = webdriver.Firefox()
driver.maximi | ze_window()
# Navigage to URL and put a 10 seconds implicit wait
driver.get(baseUrl)
driver.implicitly_wait(10)
# Find and click on element | "Flights"
# Find departure textbox and type "Barcelona"
# Find departure textbox and type "Madrid"
# Find departure time and type "23/11/2017"
# Close Calendar
# Find the "Find" button and click on
# Quit driver
|
akehrer/fiddle | fiddle/controllers/FiddleTabWidget.py | Python | gpl-3.0 | 9,860 | 0.001724 | # Copyright (c) 2015 Aaron Kehrer
# Licensed under the terms of the MIT License
# (see fiddle/__init__.py for details)
# Import standard library modules
import os
# Import additional modules
import chardet
from PyQt4 import QtCore, QtGui
from fiddle.controllers.Editors import *
from fiddle.config import FILE_TYPES,... | elf._saved = True
self.basepath = None
self.filename = None
self.extension = None
self.encoding = 'utf-8' # Default to UTF-8 encoding
# Set the layout and insert the editor
self.editor = None
self.setLayout(QtGui.QVBoxLayout())
self.layout().setMargin(... | found = (0, 0) # line, col
self.filepath = filepath
self.watcher = None
@property
def filepath(self):
return self._filepath
@filepath.setter
def filepath(self, path):
global new_file_iter
if path is not None:
self._filepath = path
self.... |
peterhinch/micropython-mqtt | mqtt_as/range_ex.py | Python | mit | 2,773 | 0.003967 | # range_ex.py Test of asynchronous mqtt client with clean session False.
# Extended version publishes SSID
# (C) Copyright Peter Hinch 2017-2019.
# Released under the MIT licence.
# Public brokers https://github.com/mqtt/mqtt.github.io/wiki/public_brokers
# This demo is for wireless range tests. If OOR the red LED wi... | r:
print('Co | nnection failed.')
return
n = 0
s = '{} repubs: {} outages: {} rssi: {}dB free: {}bytes'
while True:
await asyncio.sleep(5)
gc.collect()
m = gc.mem_free()
print('publish', n)
# If WiFi is down the following will pause for the duration.
await client.pub... |
poppogbr/genropy | packages/showcase/webpages/dev/remote.py | Python | lgpl-2.1 | 2,026 | 0.008391 | # -*- coding: UTF-8 -*-
#--------------------------------------------------------------------------
# Copyright (c) : 2004 - 2007 Softwell sas - Milano
# Written by : Giovanni Porcari, Michele Bertoldi
# Saverio Porcari, Francesco Porcari , Francesco Cavazzana
#--------------------------------------... | root, **kwargs):
bc = root.borderContainer()
top = bc.contentPane(region='top', height='100px')
top.button('Build', fire='build')
top.button('Add element', fire='add')
top.dataController("""var pane = genro.nodeById('remoteContent')
pane._('div',{he... | lid blue','float':'left',
remote:{'method':'test'}});
""", _fired="^add")
center = bc.contentPane(region='center').div(nodeId='remoteContent')
center.div().remote('test', _fired='^build')
def remote_test(self, pane, **kwargs)... |
ducted/duct | duct/tests/test_sflow.py | Python | mit | 362 | 0 | from twisted.trial import unittest
from twisted.int | ernet import defer
from duct.protocol.sflow import protocol
from duct | .tests import globs
class Test(unittest.TestCase):
def test_decode(self):
proto = protocol.Sflow(globs.SFLOW_PACKET, '172.30.0.5')
self.assertTrue(proto.version == 5)
self.assertTrue(len(proto.samples) == 5)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.