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 |
|---|---|---|---|---|---|---|---|---|
Johnetordoff/osf.io | api_tests/files/serializers/test_file_serializer.py | Python | apache-2.0 | 8,118 | 0.003449 | from datetime import datetime
import pytest
from pytz import utc
from addons.base.utils import get_mfr_url
from api.files.serializers import FileSerializer, get_file_download_link, get_file_render_link
from api_tests import utils
from osf_tests.factories import (
UserFactory,
PreprintFactory,
NodeFactory,... | req = make_drf_request_with_version(version='2.0')
data = FileSerializer(file_one, context={'request': req}).data['data']
assert modified_tz_aware == data['attributes']['date_modified']
# test_date_modified_formats_to_new_format
req = make_drf_request_with_ | version(version='2.2')
data = FileSerializer(file_one, context={'request': req}).data['data']
assert datetime.strftime(
modified, new_format
) == data['attributes']['date_modified']
# test_date_created_formats_to_old_format
req = make_drf_request_with_version(version... |
rdorado79/chatbotlib | chatbot/loader.py | Python | mit | 1,057 | 0.012299 | from lxml import etree
import sys
from chatbot.core import Chatbot
class ReadChatbotDefinitionException(Exception):
def __init__(self, message):
self.message = message
def load(filename,context={}):
c = Chatbot(context=context)
c.load(filename)
return c
'''
try:
parser = etree.XMLParser()
... | as err:
print("File n | ot found: '"+filename+"'")
sys.exit(2)
'''
|
keithfancher/Todo-Indicator | todotxt/test_list.py | Python | gpl-3.0 | 11,017 | 0.00118 | #!/usr/bin/env python
# Copyright 2012-2014 Keith Fancher
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This p... | self.assertTrue(test_list.items[1].is_completed)
self.assertEqual | ('Item three', test_list.items[2].text)
self.assertEqual(None, test_list.items[2].priority)
self.assertTrue(test_list.items[2].is_completed)
def test_mark_item_completed_with_full_text(self):
todo_text = "(A) Item one\n(Z) Item two\nx Item three\n\n \n"
test_list = TodoTxtList(None,... |
openstack/cinder | cinder/volume/drivers/dell_emc/powermax/provision.py | Python | apache-2.0 | 32,178 | 0 | # Copyright (c) 2020 Dell Inc. or its subsidiaries.
# 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
#
# ... |
array, storage_group, srp, slo, workload, extra_specs,
do_disable_compression)
LOG.debug("Create storage group took: %(delta)s H:MM:SS.",
{'delta': self.utils.get_time_delta(start_time,
| time.time())})
LOG.info("Storage group %(sg)s created successfully.",
{'sg': storagegroup_name})
else:
LOG.info("Storage group %(sg)s already exists.",
{'sg': storagegroup_name})
return ... |
egcodes/haberbus | aristotle/tests/test_util.py | Python | gpl-3.0 | 63 | 0 | from unittest im | port Te | stCase
class Test(TestCase):
pass
|
Fusion-Data-Platform/fdp | fdp/lib/datasources.py | Python | mit | 1,353 | 0 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 24 12:49:36 2017
@author: drsmith
"""
import os
from .globals import FdpError
def canonicalMachineName(machine=''):
aliases = {'nstxu': ['nstx', 'nstxu', 'nstx-u'],
'diiid': ['diiid', 'diii-d', 'd3d'],
'cmod': ['... | ',
'port': '8000'},
'diiid': {'hostname': 'atlas.gat.com',
| 'port': '8000'}
}
EVENT_SERVERS = {
'nstxu': {'hostname': 'skylark.pppl.gov',
'port': '8000'},
'diiid': {'hostname': 'atlas.gat.com',
'port': '8000'},
'ltx': {'hostname': 'lithos.pppl.gov',
'port': '8000'}
}
LOGBOOK_CREDENTIALS = {
'nstxu': {'server': 'sql200... |
brain-tec/server-tools | html_text/models/ir_fields_converter.py | Python | agpl-3.0 | 2,350 | 0 | # Copyright 2016-2017 Jairo Llopis <[email protected]>
# Copyright 2016 Tecnativa - Vicent Cubells
# License AGPL-3.0 or later (https://www.gnu.org/ | licenses/agpl).
import logging
from lxml import etree, html
from odoo import api, models
_logger = logging.getLogger(__name__)
class IrFieldsConverter(models.AbstractModel):
_inherit = "ir.fields.conv | erter"
@api.model
def text_from_html(self, html_content, max_words=None, max_chars=None,
ellipsis=u"…", fail=False):
"""Extract text from an HTML field in a generator.
:param str html_content:
HTML contents from where to extract the text.
:param int ... |
enthought/etsproxy | enthought/enable/base_tool.py | Python | bsd-3-clause | 85 | 0 | # proxy | module
from __future__ import absolute_import
from enable.base_tool impor | t *
|
adfinis-sygroup/freedomvote | app/core/widgets.py | Python | gpl-3.0 | 1,773 | 0.007332 | from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from django.forms.widgets import ClearableFileInput, CheckboxInput
from easy_thumbnails.files import get_thumbnailer
from django.templatetags.static import static
from django.utils.encoding import force_text
class ImagePrevi... | f value and hasattr(value, 'url') else static('images/placeholder.svg'))
)
}
template = '%(initial)s%(input)s'
substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs)
if not self.is_required:
template = '%(initial)s%(clear_template)s%... | ubstitutions['clear_checkbox_name'] = conditional_escape(checkbox_name)
substitutions['clear_checkbox_id'] = conditional_escape(checkbox_id)
substitutions['clear'] = CheckboxInput().render(checkbox_name, False, attrs={'id': checkbox_id})
substitutions['clear_template'] = self.clear_c... |
JeanOlivier/Laveqed | gui_laveqed.py | Python | gpl-3.0 | 20,280 | 0.015927 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from Tkinter import *
from ttk import *
from ScrolledText import ScrolledText as Text
from PIL import Image, ImageTk
import tkFileDialog,os,cairo,tempfile,time,shutil,tkFont
from laveqed import laveqed
from rsvg_windows import rsvg_windows
try:
import rsvg
except ImportErro... | ght
text.tag_configure('red',foreground='red')
text.tag_configure('green',foreground='green')
text.tag_configure('purple',foreground='purple')
text.tag_configure('blue',foreground='blue')
| # Bold baby!
text.tag_configure('bold',font=self.bold_font)
def _buildWidgets(self):
self.text_widget=Text(self.text_frame,bd=2,padx=4,pady=4,\
wrap=WORD,font=(FONTNAME,14),undo=True)
self.text_widget.pack(fill='both',expand=True,padx=4,pady=4)
self.bold_font ... |
AusDTO/dto-digitalmarketplace-buyer-frontend | app/main/forms/brief_forms.py | Python | mit | 3,546 | 0.003384 | from wtforms import IntegerField, SelectMultipleField
from wtforms.validators import NumberRange
from dmutils.forms import DmForm
import flask_featureflags
class BriefSearchForm(DmForm):
page = IntegerField(default=1, validators=(NumberRange(min=1),))
status = SelectMultipleField("Status", choices=(
(... | except KeyError:
raise TypeError("Expected keyword argument 'framework' with framework information")
try:
# data_a | pi_client argument only needed so we can fit in with the current way the tests mock.patch the
# the data_api_client directly on the view. would be nice to able to use the global reference to this
self._data_api_client = kwargs.pop("data_api_client")
except KeyError:
raise Typ... |
mikel-egana-aranguren/SADI-Galaxy-Docker | galaxy-dist/eggs/nose-0.11.1-py2.7.egg/nose/result.py | Python | gpl-3.0 | 5,943 | 0.001514 | """
Test Result
-----------
Provides a TextTestResult that extends unittest._TextTestResult to
provide support for error cl | asses (such as the builtin skip and
deprecated classes), and hooks for plugins to take over or extend
reporting.
"""
import logging
from unittest import _TextTestResult
from nose.config import Config
from nose.util import isclass, ln as _ln # backwards compat
log = logging.getLogger('nose.result')
def _exception_de... | class TextTestResult(_TextTestResult):
"""Text test result that extends unittest's default test result
support for a configurable set of errorClasses (eg, Skip,
Deprecated, TODO) that extend the errors/failures/success triad.
"""
def __init__(self, stream, descriptions, verbosity, config=None,
... |
ramineni/myironic | ironic/db/sqlalchemy/api.py | Python | apache-2.0 | 22,173 | 0.000316 | # -*- encoding: utf-8 -*-
#
# Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# 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
#
# ... | F
CONF.import_opt('heartbeat_timeout',
'ironic.conductor.manager', |
group='conductor')
LOG = log.getLogger(__name__)
_FACADE = None
def _create_facade_lazily():
global _FACADE
if _FACADE is None:
_FACADE = db_session.EngineFacade.from_config(CONF)
return _FACADE
def get_engine():
facade = _create_facade_lazily()
return facade.get_engi... |
2014c2g5/2014cadp | wsgi/local_data/brython_programs/brython_fourbar1.py | Python | gpl-3.0 | 11,960 | 0.012758 | #要注意 javascript 轉 python 語法差異
#document.getElementById -> doc[]
#module Math -> math
#Math.PI -> math.pi
#abs -> fabs
#array 可用 list代替
import math
import time
from browser import doc
import browser.timer
# 點類別
class Point(object):
# 起始方法
def __init__(self, x, y):
self.x = x
self.y = y
... | 作為設定 Head 的參考
def setRT(self, r, t):
self.r = r
self.t = t
x = self.r * math.cos(self.t)
y = self.r * math.sin(self.t)
self.Tail.Eq(self.p1)
self.Head.setPoint(self.Tail.x + x,self.Tail.y + y)
# getR 方法 for Line
def getR(self):
# x 分量與 y 分量
x ... | x + y * y)
# 根據定義 atan2(y,x), 表示 (x,y) 與 正 x 軸之間的夾角, 介於 pi 與 -pi 間
def getT(self):
x = self.p2.x - self.p1.x
y = self.p2.y - self.p1.y
if (math.fabs(x) < math.pow(10,-100)):
if(y < 0.0):
return (-math.pi/2)
else:
return (math.pi/2... |
jamielennox/tempest | tempest/tests/test_auth.py | Python | apache-2.0 | 15,978 | 0 | # Copyright 2014 IBM Corp.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | self.auth_provider.cache = 'foo'
self.auth_provider.clear_auth()
self.assertIsNone(self.auth_provider.cache)
def test_set_and_reset_alt_auth_data(self):
self.auth_provider.set_alt_auth_data('foo', 'bar')
self.assertEqual(self.auth_provider.alt_part, 'foo')
self.assertEqual(... | lf.assertIsNone(self.auth_provider.alt_part)
self.assertIsNone(self.auth_provider.alt_auth_data)
def test_auth_class(self):
self.assertRaises(TypeError,
auth.AuthProvider,
fake_credentials.FakeCredentials)
class TestKeystoneV2AuthProvider(BaseAu... |
rbramwell/pulp | server/pulp/server/managers/auth/user/cud.py | Python | gpl-2.0 | 7,971 | 0.001756 | """
Contains the manager class and exceptions for operations surrounding the creation,
update, and deletion on a Pulp user.
"""
from gettext import gettext as _
import re
from celery import task
from pulp.server import config
from pulp.server.async.tasks import Task
from pulp.server.db.model.auth import User
from pu... | he last super user
if factory.user_query_manager().is_last_super_user(login):
raise PulpDataException(_("The last superuser [%s] cannot be deleted" % login))
# Revoke all permissions from the user
permission_manager = factory.permission_ma | nager()
permission_manager.revoke_all_permissions_from_user(login)
User.get_collection().remove({'login': login}, safe=True)
def ensure_admin(self):
"""
This function ensures that there is at least one super user for the system.
If no super users are found, the default admi... |
bentiss/hid-replay | tools/capture_usbmon.py | Python | gpl-2.0 | 13,959 | 0.02479 | #!/bin/env python
# -*- coding: utf-8 -*-
#
# Hid replay / capture_usbmon.py
#
# must be run as root.
#
# This program is useful to capture both the raw usb events from an input
# device and its kernel generated events.
#
# Requires several tools to be installed: usbmon, evemu and pyudev
#
# Copyright (c) 2014 Benjamin... | start_evemu(self):
# start an evemu-record of the event node
print "dumping evdev events in", self.get_name()
self.output = open(self.get_name(), 'w')
evemu_command = "evemu-record /dev/input/{0}".format(self.device.sys_name)
print evemu_command
self.p = | subprocess.Popen(shlex.split(evemu_command), stdout=self.output)
class USBInterface(UDevObject):
def __init__(self, device, parent):
UDevObject.__init__(self, device, parent, EventNode)
self.intf_number = device.sys_name.split(':')[-1]
self.lsusb()
def is_child_type(self, other):
return other.subsystem == ... |
story645/hpcc | set_partition/sets/gensets.py | Python | mit | 414 | 0.004831 | """
Hannah Aizenman
10/13/2013
Generates a random subset of size 10^P for p in [1,MAX_P) from [0, 10^8)
"""
import random
MAX_P = 8
max_value = | 10**MAX_P
large_set = range(max_value)
for p in xrange(1,MAX_P):
print "list of size: 10^{0}".format(p)
f = open("p{0}.txt".format(p), 'w')
sample = random.sample(large_set, 10**p)
f.wri | te("\n".join(map(lambda x: str(x), sample)))
f.close()
|
dek-odoo/python-samples | python exercises/dek_program078.py | Python | apache-2.0 | 584 | 0.003425 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#- Author : (DEK) Devendra Kavthekar
# program078:
# Please write a program to generate a list with 5 random numbers between
# 100 and 200 inclusive.
# Hints:
# Use random.sample() to generate a list of | random values.
import random
def main(startLimit, endLimit):
print random.sample(range(startLimit, endLimit + 1), 5)
if __name__ == '__main__':
# startLimit = int(raw_input("Input Start Value: "))
# endLimit = int(raw_input("Input Stop Value: "))
# main(startLimit, | endLimit)
main(100, 200)
|
Laurawly/tvm-1 | python/tvm/topi/unique.py | Python | apache-2.0 | 12,249 | 0.003102 | # 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... | The output tensor data type.
binop: function, optional
A binary associative op to use for calculating difference. The function takes two
TIR expressions and produce a new TIR expression. By default it uses tvm.tir.Sub to
compute the adjacent difference.
Returns
-------
ou... | ata[i], data[i-1])
where i > 0 and i < len(data).
"""
return te.extern(
[data.shape],
[data],
lambda ins, outs: _calc_adjacent_diff_ir(ins[0], outs[0], binop=binop),
dtype=[out_dtype],
name="_calc_adjacent_diff",
tag="_calc_adjacent_diff_cpu",
)
@hyb... |
lcpt/xc | verif/tests/elements/crd_transf/test_element_axis_03.py | Python | gpl-3.0 | 3,424 | 0.034765 | # -*- coding: utf-8 -*-
__author__= "Luis C. Pérez Tato (LCPT) and Ana Ortega (AOO)"
__copyright__= "Copyright 2015, LCPT and AOO"
__license__= "GPL"
__version__= "3.0"
__email__= "[email protected]"
import xc_base
import geom
import xc
from solution import predefined_solutions
from model import predefined_spaces... | ctionAngle= 0
fuerte= beam3d.getVDirStrongAxisGlobalCoord(True) # initialGeometry= True
debil= beam3d.getVDirWeakAxisGlobalCoord(True) # initialGeometry= True
sectionAngle= beam3d.getStrongAxisAngle()
ratio1= ((debil[0])**2+(debil[2])**2)
ratio2= ((fuerte[0])**2+(fuerte[1])**2)
# Constraints
modelSpace.fixNode000_00... | ler= preprocessor.getLoadHandler
lPatterns= loadHandler.getLoadPatterns
#Load modulation.
ts= lPatterns.newTimeSeries("constant_ts","ts")
lPatterns.currentTimeSeries= "ts"
lp0= lPatterns.newLoadPattern("default","0")
lp0.newNodalLoad(2,xc.Vector([0,-F,F,0,0,0]))
#We add the load case to domain.
lPatterns.addToDomain... |
plotly/python-api | packages/python/plotly/plotly/validators/barpolar/hoverlabel/font/_familysrc.py | Python | mit | 475 | 0.002105 | import _plotly_utils.basevalidators
class FamilysrcVa | lidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name="familysrc", parent_name="barpolar.hoverlabel.font", **kwargs
):
super(FamilysrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.po... | pe", "none"),
role=kwargs.pop("role", "info"),
**kwargs
)
|
valentin-krasontovitsch/ansible | lib/ansible/modules/messaging/rabbitmq/rabbitmq_exchange.py | Python | gpl-3.0 | 6,655 | 0.002705 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2015, Manuel Sousa <[email protected]>
# 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_vers... | nt is a key/value dictionary
required: false
default: {}
extends_documentation_fragment:
- rabbitmq
'''
EXAMPLES = '''
# Create direct exchange
- rabbitmq_exchange:
name: directExchange
# Create topic exchange on vhost
- rabbitmq_exchange:
name: topicExchange
| type: topic
vhost: myVhost
'''
import json
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six.moves.urllib import parse as urllib_parse
from ansible.module_utils.rabbitmq import rabbitmq... |
WangWenjun559/Weiss | classifier/liblinear.py | Python | apache-2.0 | 9,368 | 0.028288 | #!/usr/bin/env python
from ctypes import *
from ctypes.util import find_library
from os import path
import sys
__all__ = ['liblinear', 'feature_node', 'gen_feature_nodearray', 'problem',
'parameter', 'model', 'toPyModel', 'L2R_LR', 'L2R_L2LOSS_SVC_DUAL',
'L2R_L2LOSS_SVC', 'L2R_L1LOSS_SVC_DUAL', ... | nce(xi, dict):
index_range = xi.keys()
elif isinstance(xi, (list, tuple)):
| xi = [0] + xi # idx should start from 1
index_range = range(1, len(xi))
else:
raise TypeError('xi should be a dictionary, list or tuple')
if feature_max:
assert(isinstance(feature_max, int))
index_range = filter(lambda j: j <= feature_max, index_range)
if issparse:
index_range = filter(lambda j:xi[j] !... |
BastienFaure/jarvis | src/pentest/tests/__main__.py | Python | mit | 1,036 | 0 | import os
import argparse
from pentest import __version__
def get_parser():
"""
Creates a new argument parser.
"""
parser = argparse.ArgumentParser('jarvis')
version = '%(prog)s ' + __version__
parser.add_argument('--version', '-v', action='version', version=version)
return parser
def m... | try:
import pytest
except ImportError:
raise SystemExit(
'You need py.test to run the test suite.\n'
'You can install it using your distribution package manager or\n'
' $ python -m pip install pytest --user'
)
# Get data from test_module
impo... | __))
pytest.main([test_path, '-m', 'not documentation'])
if __name__ == '__main__':
main()
|
TraMZzz/GoGreen | go_green/users/serializers.py | Python | mit | 1,359 | 0.002208 | # -*- coding: ut | f-8 -*-
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from rest_framework.validators import UniqueValidator
from .models import User
from go_green.badge.serializers import BadgeViewSetSerializer
class UserViewSetSerializer(serializers... | erializer):
badges = BadgeViewSetSerializer(many=True, read_only=True)
email = serializers.EmailField(validators=[UniqueValidator(queryset=User.objects.all())])
class Meta:
model = User
fields = (u'id', u'username', u'email', u'first_name',
u'last_name', u'clean_count',
... |
trangel/OPTpy | examples/data/__init__.py | Python | gpl-3.0 | 391 | 0.005115 |
import os
pseudo_dir = os.path.join(os.path.dirname(__file__), 'pseudos')
# TODO
# Gotta handle the pseudos a bit better.
# GaAs
struc | ture_GaAs = os.path.join(os.path.dirname(__file__), 'structures', 'GaAs.json')
pseudos_GaAs = ['31-Ga.PBE.UPF', '33-As.PBE.UPF']
# Si
structure_Si = os.path.join(os.path.dirname(__f | ile__), 'structures', 'Si.json')
pseudos_Si = ['14-Si.pspnc']
del os
|
lthurlow/Network-Grapher | proj/external/numpy-1.7.0/numpy/core/tests/test_getlimits.py | Python | mit | 2,703 | 0.005179 | """ Test functions for limits module.
"""
from numpy.testing import *
from numpy.core import finfo, iinfo
from numpy import half, single, double, longdouble
import numpy as np
##################################################
class TestPythonFloat(TestCase):
def test_singleton(self):
| ftype = finfo(float)
ftype2 = finfo(float)
assert_equal(id(ftype),id(ftype2))
class TestHalf(TestCase):
def test_singleton(self):
ftype = finfo(half)
ftype2 = finfo(half)
assert_equal(id(ftype),id(ftype2))
|
class TestSingle(TestCase):
def test_singleton(self):
ftype = finfo(single)
ftype2 = finfo(single)
assert_equal(id(ftype),id(ftype2))
class TestDouble(TestCase):
def test_singleton(self):
ftype = finfo(double)
ftype2 = finfo(double)
assert_equal(id(ftype),id(fty... |
kenshay/ImageScript | ProgramData/SystemFiles/Python/Lib/site-packages/psutil/tests/test_linux.py | Python | gpl-3.0 | 58,553 | 0.000273 | #!/usr/bin/env python
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Linux specific tests."""
from __future__ import division
import collections
import contextlib
import errno
import io
import os
i... | t_free_version_info() >= (3, 3, 12), "old free version")
@retry_before_failing()
def test_used(self):
free = free_physmem()
free_value = free.used
psutil_value = psutil.virtual_memory().used
self.assertAlmostEqual(
free_value, psutil_value, delta=MEMORY_TOLERANCE,
... | alue, _ = free_physmem()
# psutil_value = psutil.virtual_memory().free
# self.assertAlmostEqual(
# free_value, psutil_value, delta=MEMORY_TOLERANCE)
vmstat_value = vmstat('free memory') * 1024
psutil_value = psutil.virtual_memory().free
self.assertAlmostEqual(
... |
google/grr | grr/core/grr_response_core/lib/util/statx.py | Python | apache-2.0 | 8,579 | 0.007227 | #!/usr/bin/env python
"""A module for working with extended file stat collection.
This module will try to collect as detailed stat information as possible
depending on platform capabilities (e.g. on Linux it will use `statx` [1] call.
[1]: https://www.man7.org/linux/man-pages/man2/statx.2.html
"""
import ctypes
impor... | "stx_btime", _StatxTimestampStruct), |
("stx_ctime", _StatxTimestampStruct),
("stx_mtime", _StatxTimestampStruct),
# Device identifier (if the file represents a device).
("stx_rdev_major", ctypes.c_uint32),
("stx_rdev_minor", ctypes.c_uint32),
# Device identifier of the filesystem the file resides on.
("stx_dev_maj... |
ESS-LLP/erpnext-healthcare | erpnext/hooks.py | Python | gpl-3.0 | 14,269 | 0.020324 | from __future__ import unicode_literals
from frappe import _
app_name = "erpnext"
app_title = "ERPNext"
app_publisher = "Frappe Technologies Pvt. Ltd."
app_description = """ERP made simple"""
app_icon = "fa fa-th"
app_color = "#e74c3c"
app_email = "[email protected]"
app_license = "GNU General Public License (v3)"
sour... | for_contact.has_website_permission",
"Supplier Quotation": "erpnext.controllers.website_list_for_contact.has_website_permission",
"Delivery Note": "erpnext.controllers.website_lis | t_for_contact.has_website_permission",
"Issue": "erpnext.support.doctype.issue.issue.has_website_permission",
"Timesheet": "erpnext.controllers.website_list_for_contact.has_website_permission",
"Lab Test": "erpnext.healthcare.web_form.lab_test.lab_test.has_website_permission",
"Patient Encounter": "erpnext.healthca... |
em92/pickup-rating | qllr/blueprints/ratings/methods.py | Python | mit | 3,787 | 0.001056 | import json
from math import ceil
from asyncpg import Connection
from qllr.common import MATCH_LIST_ITEM_COUNT
from qllr.db import cache
from qllr.settings import PLAYER_COUNT_PER_PAGE
KEEPING_TIME = 60 * 60 * 24 * 30
SQL_TOP_PLAYERS_BY_GAMETYPE = """
SELECT
p.steam_id,
p.name,
p.model,
... | ctive is False:
start_timestamp = cach | e.LAST_GAME_TIMESTAMPS[gametype_id] - KEEPING_TIME
result = []
player_count = 0
async for row in con.cursor(query, start_timestamp, gametype_id):
if row[0] != None:
result.append(
{
"_id": str(row[0]),
"name": row[1],
... |
olasitarska/django | tests/serializers/models.py | Python | bsd-3-clause | 3,125 | 0.00064 | # -*- coding: utf-8 -*-
"""
42. Serialization
``django.core.serializers`` provides interfaces to converting Django
``QuerySet`` objects to and from "flat" data (i.e. strings).
"""
from __future__ import unicode_literals
from decimal import Decimal
from django.db import models
from django.utils import six
from django... | .FloatField()
@python_2_unicode_compatible
class Team(object):
def __init__(self, title):
self.title = title
def __str__(self):
raise NotImplementedError("Not so simple")
def to_string(self):
return "%s" % self.title
class TeamField(models.CharField):
def __init__(self):
... | ue, connection):
return six.text_type(value.title)
def to_python(self, value):
if isinstance(value, Team):
return value
return Team(value)
def from_db_value(self, value, connection):
return Team(value)
def value_to_string(self, obj):
return self._get_va... |
sailthru/mongo-connector | tests/test_oplog_manager.py | Python | apache-2.0 | 17,080 | 0.00041 | # Copyright 2013-2014 MongoDB, 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 agreed to in writin... | 'test.*': True,
'gridfs.*': {'gridfs': True}
}
),
)
def tearDown(self):
try:
self.opman.join()
except RuntimeError:
pass # OplogThread may not have been started
self.primary_conn.drop_da... | sor method"""
# timestamp is None - all oplog entries excluding no-ops are returned.
cursor = self.opman.get_oplog_cursor(None)
self.assertEqual(cursor.count(),
self.primary_conn["local"]["oplog.rs"].find(
{'op': {'$ne': 'n'}}).count())
... |
Azure/azure-sdk-for-python | sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2021_04_01/models/__init__.py | Python | mit | 28,223 | 0.000177 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | maticOSUpgradePolicy
from ._models_py3 import AutomaticOSUpgradeProperties
from ._models_py3 import AutomaticRepairsPolicy
from ._ | models_py3 import AvailabilitySet
from ._models_py3 import AvailabilitySetListResult
from ._models_py3 import AvailabilitySetUpdate
from ._models_py3 import AvailablePatchSummary
from ._models_py3 import BillingProfile
from ._models_py3 import BootDiagnostics
from ._models_py3 import BootDiagnosticsInstanceView
from ._... |
yugangw-msft/azure-cli | src/azure-cli/azure/cli/command_modules/botservice/_exception_handler.py | Python | mit | 1,308 | 0.003058 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | IError | (message)
if isinstance(ex, CloudError) and ex.status_code == 404:
return None
if isinstance(ex, ClientRequestError):
message = 'Error occurred in sending request. Please file an issue on {0}'.format(
'https://github.com/microsoft/botframework-sdk'
)
raise CLIError(me... |
jakev/dtf | python-dtf/tests/unit/test_prop.py | Python | apache-2.0 | 5,430 | 0 | # Android Device Testing Framework ("dtf")
# Copyright 2013-2016 Jake Valletta (@jake_valletta)
#
# 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
... | sdk
assert prop.get_prop('INFO', 'sdk') == sdk
testutils.undeploy()
return 0
# prop_del() tests
def test_del_empty_config():
"""Attempts to delete a property without a valid config"""
testutils.deploy_config_raw("")
assert prop.del_prop('info', 'sdk') != 0
testutils.undeploy()
r... | "
contents = ("[Info]\n"
"sdk = 23")
testutils.deploy_config_raw(contents)
prop.del_prop('info', 'sdk')
testutils.undeploy()
return 0
def test_del_property_invalid():
"""Attempts to delete a property that doesnt exist"""
contents = ("[Info]\n"
"vmtype... |
modoboa/modoboa | modoboa/admin/migrations/0018_auto_20201204_0935.py | Python | isc | 357 | 0 | # Generated by Django 2.2.12 on 2020-12-04 08:35
from django.db import migrations, models
class Migration(migrations.Migration):
|
dependencies = [
('admin', '0017_alarm'),
]
operations = [
migrations.AlterField(
mo | del_name='alarm',
name='title',
field=models.TextField(),
),
]
|
benjello/openfisca-france | openfisca_france/model/caracteristiques_socio_demographiques/logement.py | Python | agpl-3.0 | 4,749 | 0.005925 | # -*- coding: utf-8 -*-
from numpy import logical_not as not_, logical_or as or_
from numpy.core.defchararray import startswith
from openfisca_france.model.base import * # noqa analysis:ignore
class coloc(Variable):
column = BoolCol
entity_class = Individus
label = u"Vie en colocation"
class lo... | propriétaire du logement a un lien de parenté avec la personne de référence ou son conjoint"
class statut_occupation_logement(Variable):
column = EnumCol(
enum = Enum([
u"Non renseigné",
| u"Accédant à la propriété",
u"Propriétaire (non accédant) du logement",
u"Locataire d'un logement HLM",
u"Locataire ou sous-locataire d'un logement loué vide non-HLM",
u"Locataire ou sous-locataire d'un logement loué meublé ou d'une chambre d'hôtel",
u"Logé gr... |
bplower/legendary-waffle-lib | test/test_universe_create.py | Python | apache-2.0 | 2,904 | 0.007576 | #!/usr/bin/env python
"""
This pretty much just tests creating a user, a universe, a planet, a building type name, a building
type, and a building.
"""
import os
import sys
import sqlalchemy
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import legendary_waffle
# Database setup
... | name": 1, # The pkid of the building type name 'Control Center'
"description": "This is the | control center",
"default_condition": 100,
"default_firepower": 0,
"default_storage": 100,
"rhr_passive": 0,
"rhr_active": 0,
"rhr_destructive": 0,
"build_resource_reqs": 500,
}
legendary_waffle.model_create(db, legendary_waffle.models.BuildingType, **building_type_config)
print "Building T... |
unho/virtaal | virtaal/views/widgets/storecellrenderer.py | Python | gpl-2.0 | 10,840 | 0.00369 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2008-2010 Zuza Software Foundation
#
# This file is part of Virtaal.
#
# 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 ... | '', source_x, y, self.source_layout)
widget.get_style().paint_layout(window, gtk.STATE_NORMAL, False,
cell_area, widget, '', target_x, y, self.target_layout)
# METHODS #
def _get_pango_layout(self, widget, text, width, font_descri | ption):
'''Gets the Pango layout used in the cell in a TreeView widget.'''
# We can't use widget.get_pango_context() because we'll end up
# overwriting the language and font settings if we don't have a
# new one
layout = pango.Layout(widget.create_pang |
staranjeet/fjord | vendor/packages/translate-toolkit/translate/convert/test_po2sub.py | Python | bsd-3-clause | 2,446 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pytest import importorskip
from translate.convert import po2sub
from translate.convert import test_convert
from translate.misc import wStringIO
from translate.storage import po
# Technically subtitles can also use an older gaupol
importorskip("aeidon")
class Test... | estPO2Sub):
"""Tests running actual po2sub commands on files"""
convertmodule = po2sub
defaultoptions = {"progress": "none"}
def test_help(self):
"""tests getting help"""
options = test_convert.TestConvertCommand.test_help(self)
options = self.help_check(options, "-t TEMPLATE, -... | "--threshold=PERCENT")
options = self.help_check(options, "--fuzzy")
options = self.help_check(options, "--nofuzzy", last=True)
|
pmichel31415/reddit-iambic-pentameter | rip/poet.py | Python | mit | 5,989 | 0.001002 | # -*- coding: utf-8 -*-
from __future__ import print_function, division
import sys
from collections import defaultdict
import numpy as np
import numpy.random as npr
import util
import poetry
import curse
import image
import title
class Poet(object):
"""Composes poems (duh...)"""
def __init__(self, config_f... | # Probability of picking a rhyme
# This probability is proportional to the number of verses for each rhyme.
# In particular, for rhymes with only one verse, the probability is set to 0
self.p_rhymes = {r: (len(v) - 1) for r, v in self.rhymes.items()}
self.names_rhymes, self.p_rhymes = z... | title.get_title_generator(self.title)
def add_period(self, line):
"""Adds a period at the end of line"""
if not line[-1] in '.,!?;':
line = line + '.'
elif line[-1] in ',:;':
line = line[:-1] + '.'
return line
def find_rhyming_verse(self, rhyme, verse=N... |
wrwrwr/turtle-trans | turtletrans/translate.py | Python | mit | 444 | 0 | """
Some common utilities.
"""
from turtle import Turtle
def turtle_subclass(name):
"""
| Creates a subclass of Turtle with the given name.
"""
return type(name, (Turtle,), {})
def translate_methods(cls, translations):
"""
Creates aliases for method names.
"""
for method, aliases in translations.items():
func = getattr(cls, | method)
for alias in aliases:
setattr(cls, alias, func)
|
blackberry/ALF | alf/debug/_gdb.py | Python | apache-2.0 | 19,799 | 0.002879 | ################################################################################
# Name : GDB Wrapper
# Author : Jesse Schwartzentruber & Tyson Smith
#
# Copyright 2014 BlackBerry Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Lice... | tox86-gdb"),
"armle": os.path.join(_common.PATH_DBG, "ntoarm-gdb"),
| }[platform.processor()]
TOOL_GDB_NTO = TOOL_GDB
TOOL_KDSRV = None
assert os.access(TOOL_GDB, os.X_OK), "%s is not executable" % TOOL_GDB
elif platform.system() == "Windows":
TOOL_GDB = distutils.spawn.find_executable('gdb.exe', os.pathsep.join([os.environ['PATH'], _common.PATH_DBG]))
TOOL... |
kislyuk/cartographer | postproc_db.py | Python | agpl-3.0 | 1,920 | 0.005208 | #!/usr/bin/env python3
import os, sys, logging, urllib, time, string, json, argparse, collections, datetime, re, bz2, math
from concurrent.futures import ThreadPoolExecutor, wait
import lz4
pool = ThreadPoolExecutor(max_workers=16)
logging.basicConfig(level=logging.DEBUG)
sys. | path.append(os.path.join(os.path.dirname(__file__), "lib", "python"))
from carta import (logger, POI)
from mongoengine import *
connect('carta')
zoomspacing = [round(0.0001*(1.6**n), 4) for n in | range(21, 1, -1)]
def compute_occlusions(box):
SW, NE = box
points = list(POI.objects(at__geo_within_box=(SW, NE)))
print("Starting", SW, NE, len(points))
for i, p1 in enumerate(points):
for j, p2 in enumerate(points[i+1:]):
coords1, coords2 = p1.at['coordinates'], p2.at['coordinat... |
orionblastar/K666 | freek666/urls.py | Python | mit | 299 | 0 | from django.conf.urls import include, url
from django.views.generic.base import RedirectView
from djan | go.views.generic.base import TemplateView
urlpatt | erns = [
url(r'^index.html$', TemplateView.as_view(template_name="index.html")),
# url(r'^$', RedirectView.as_view(url="/index.html")),
]
|
Upande/MaMaSe | apps/partners/forms.py | Python | apache-2.0 | 134 | 0.014925 | from django import fo | rms
class PartnerLogoForm(forms.Form):
partner_logo = fo | rms.ImageField(
label='Select a file',
) |
MWisBest/PyBot | Commands/synonym/__init__.py | Python | gpl-3.0 | 23 | 0 | fro | m .synonym im | port *
|
yepengxj/theano_exercises | 02_advanced/01_symbolic/03_energy_soln.py | Python | bsd-3-clause | 2,327 | 0.002149 | import numpy as np
import theano
from theano import function
from theano.sandbox.rng_mrg import MRG_RandomStreams
import theano.tensor as T
def energy(W, V, H):
"""
W : A theano matrix of RBM weights
num visible x num hidden
V : A theano matrix of assignments to visible units
Each row is a... | T.nnet.sigmoid(T.dot(v, W))
h = rng_factory.binomial(p=ph, size=ph.shape, dtype=W.dtype)
c | lass _ElemwiseNoGradient(theano.tensor.Elemwise):
def grad(self, inputs, output_gradients):
raise TypeError("You shouldn't be differentiating through "
"the sampling process.")
return [ theano.gradient.DisconnectedType()() ]
block_gradient = _ElemwiseNoGradient(th... |
Linaro/squad | squad/core/migrations/0011_testrun_metadata_fields.py | Python | agpl-3.0 | 959 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-20 13:42
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0010_testrun_datetime'),
]
operations = [
migrations.AddField(
... | ),
migrations.AddField(
model_name='testrun',
name='job_id',
field=models.CharField(max_length=128, null=True),
),
migrations.AddField(
model_name='testrun',
name='job_status',
field=models.CharField(max_length=128, null=Tru... | migrations.AddField(
model_name='testrun',
name='job_url',
field=models.CharField(max_length=2048, null=True),
),
]
|
moodpulse/l2 | statistic/structure_sheet.py | Python | mit | 67,638 | 0.001698 | import json
from collections import OrderedDict
import openpyxl
from openpyxl.styles import Border, Side, Alignment, Font, NamedStyle
from openpyxl.utils.cell import get_column_letter
from directions.models import IstochnikiFinansirovaniya
from doctor_call.models import DoctorCall
from hospitals.tfoms_hospital import... |
ws1.row_dimensions[2].height = 115
columns = [
('№ п/п', 5),
(' | Время поступления', 8),
('Услуга (дата-время подтверждения)', 14),
('Направление', 11),
('Фамилия, имя, отчество больного', 20),
('Дата рождения', 10),
('Постоянное место жительства или адрес родственников, близких и N телефона', 23),
('Каким учреждением был направлен или... |
bikash/h2o-dev | py2/testdir_single_jvm/test_parse_covtype_2.py | Python | apache-2.0 | 3,121 | 0.013137 | import unittest, sys
sys.path.extend(['.','..','../..','py'])
import h2o2 as h2o
import h2o_cmd, h2o_import as h2i, h2o_browse as h2b
from h2o_test import find_file, dump_json, verboseprint
expectedZeros = [0, 4914, 656, 24603, 38665, 124, 13, 5, 1338, 51, 320216, 551128, 327648, 544044, 577981,
573487, 576189, 5686... | portFolderPath = "standard"
hex_key = 'covtype.hex'
csvPathname = importFolderPath + "/" + csvFilename
parseResult = h2i.import_parse(bucket='home-0 | xdiag-datasets', path=csvPathname, schema='local',
timeoutSecs=timeoutSecs, hex_key=hex_key,
chunk_size=4194304*2, doSummary=False)
pA = h2o_cmd.ParseObj(parseResult)
iA = h2o_cmd.InspectObj(pA.parse_key)
print iA.missingList, iA.labelList, iA.numRow... |
Mlieou/oj_solutions | leetcode/python/ex_576.py | Python | mit | 898 | 0.004454 | class Solution(object):
def findPaths(self, m, n, N, i, j):
"""
:type m: int
:type n: int
:type N: int
:type i: int
:type j: int
:rtype: int
"""
if not N: return 0
board = [[[0] * n for _ in range(m | )] for _ in range(2)]
for c in range(1, N+1):
prev = (c - 1) % 2
curr = c % 2
for x | in range(m):
for y in range(n):
board[curr][x][y] = 0
board[curr][x][y] += board[prev][x-1][y] if x > 0 else 1
board[curr][x][y] += board[prev][x+1][y] if x < m-1 else 1
board[curr][x][y] += board[prev][x][y-1] if y > 0 else... |
jimrybarski/fylm_critic | tests.py | Python | mit | 250 | 0 | """
Auto-discovers all unittests in the | tests directory and runs them
"""
import unittest
loader = unittest.TestLoader()
tests = loader.discover('tests', pattern='*.py', top_level_dir='.')
testRunner = unittest.TextTestRunner()
tes | tRunner.run(tests)
|
xmendez/wfuzz | src/wfuzz/ui/console/mvc.py | Python | gpl-2.0 | 10,785 | 0.000556 | import sys
from collections import defaultdict
import threading
try:
from itertools import zip_longest
except ImportError:
from itertools import izip_longest as zip_longest
from wfuzz.fuzzobjects import FuzzWordType, FuzzType, FuzzPlugin
from .common import exec_banner, Term
from .getch import _Getch
from .o... | self.term = Term()
self.printed_lines = 0
def _print_verbose(self, res, print_nres=True):
txt_colour = (
Term.noColour if not res.is_baseline or not self.colour else Term.fgCyan
)
if self.previous and self.colour and not print_nres:
| txt_colour = Term.fgCyan
location = ""
if "Location" in res.history.headers.response:
location = res.history.headers.response["Location"]
elif res.history.url != res.history.redirect_url:
location = "(*) %s" % res.history.url
server = ""
if "Server" in... |
guillaume-philippon/aquilon | lib/aquilon/consistency/checks/branch.py | Python | apache-2.0 | 3,427 | 0.000584 | #!/usr/bin/env python
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2013,2014 Contributor
#
# 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 co... | branch
# Find all of the branches that are in the template king, this
# includes both domains and sandbox's
kingdir = self.config.get("broker", "kingdir")
out = run_git(['for-each-ref', '--format=%(refname:short)',
| 'refs/heads'], path=kingdir, loglevel=logging.DEBUG)
git_branches = set(out.splitlines())
# The trash branch is special
if self.config.has_option("broker", "trash_branch"):
git_branches.remove(self.config.get("broker", "trash_branch"))
# Branches in the database a... |
cameronmaske/skipper | skipper/utils.py | Python | bsd-2-clause | 1,012 | 0 | import re
def get_subset(a, keys):
return dict((k, a[k]) for k in keys if k in a)
def find(array, properties):
keys = properties.keys()
for a in array:
dict_a = | a
if hasattr(a, '__dict__'):
| dict_a = a.__dict__
subset = get_subset(dict_a, keys)
if subset == properties:
return a
return None
def missing_keys(a, b):
return [k for k in a.keys() if k not in b.keys()]
def get_index(x, index):
"""
Get the element at the index of the list or return None
>>> e... |
clusterpy/clusterpy | clusterpy/core/toolboxes/cluster/componentsAlg/areacl.py | Python | bsd-3-clause | 1,990 | 0.00201 | # encoding: latin2
"""Algorithm utilities
G{packagetree core}
"""
__author__ = "Juan C. Duque"
__credits__ = "Copyright (c) 2009-11 Juan C. Duque"
__license__ = "New BSD License"
__version__ = "1.0.0"
__maintainer__ = "RiSE Group"
__email__ = "[email protected]"
from clusterpy.core.toolboxes.cluster.componentsAl... | nteger
@param id: Id of the polygon/area
@type neighs: list
@param neighs: Neighborhood ids
@type da | ta: list.
@param data: Data releated to the area.
@type variance: boolean
@keyword variance: Boolean indicating if the data have variance matrix
"""
self.id = id
self.neighs = neighs
if variance == "false":
self.data = data
else:
n... |
Danielhiversen/home-assistant | homeassistant/components/snmp/sensor.py | Python | apache-2.0 | 6,642 | 0.000602 | """Support for displaying collected data over SNMP."""
from datetime import timedelta
import logging
import pysnmp.hlapi.asyncio as hlapi
from pysnmp.hlapi.asyncio import (
CommunityData,
ContextData,
ObjectIdentity,
ObjectType,
SnmpEngine,
UdpTransportTarget,
UsmUserData,
getCmd,
)
imp... | *self._request_args, ObjectType(ObjectIdentity(self._baseoid))
)
if errindication and not self._accept_errors:
_LOGGER.error("SNMP error: %s", errindication)
elif errstatus and not self._accept_errors:
_LOGGER.error(
"SNMP error: %s at %s",
... | )
elif (errindication or errstatus) and self._accept_errors:
self.value = self._default_value
else:
for resrow in restable:
self.value = resrow[-1].prettyPrint()
|
hunsteve/AIQGen | urls.py | Python | mit | 2,114 | 0.005676 | from django.conf.urls import url
from AIQGen.views.index import index
from AIQGen.views.astar import astar
from AIQGen.views.minimax import minimax
from AIQGen.views.printview import testPrintView
from AIQGen.views.problemprintview import problemPrintView
from AIQGen.views.test import testList, testCreate, testUpdate,... | elete'),
url(r' | ^testproblemlist/(?P<pk>\d+)$', testProblemList, name='test_problem_list'),
url(r'^testproblemremove/(?P<pk>\d+)$', testProblemRemove, name='test_problem_remove'),
url(r'^testproblemadd/(?P<test_key>\d+)/(?P<problem_key>\d+)$', testProblemAdd, name='test_problem_add'),
url(r'^problems$', problem... |
wholland/env | vim/runtime/bundle/ultisnips/plugin/UltiSnips/tests/test_diff.py | Python | mit | 4,789 | 0.006264 | #!/usr/bin/env python
# encoding: utf-8
import unittest
import os.path as p, sys; sys.path.append(p.join(p.dirname(__file__), ".."))
from _diff import diff, guess_edit
from geometry import Position
def transform(a, cmds):
buf = a.split("\n")
for cmd in cmds:
ctype, line, col, char = cmd
if... | wanted = (
("I", 0, 5, "\n"),
("I", 1, 0, "World"),
("I", 1, 5, "\n"),
("I", 2, 0, "World"),
("I", 2, 5, "\n"),
("I", 3, 0, "World"),
)
class TestCrash(_Base, unittest.TestCase):
a = 'hallo Blah mitte=sdfdsfsd\nhallo kjsdhfjksdhfkjhsdfkh mittekjshdkfhkhsdfdsf'
... | o b mittekjshdkfhkhsdfdsf'
wanted = (
("D", 1, 6, "kjsdhfjksdhfkjhsdfkh"),
("I", 1, 6, "b"),
)
class TestRealLife(_Base, unittest.TestCase):
a = 'hallo End Beginning'
b = 'hallo End t'
wanted = (
("D", 0, 10, "Beginning"),
("I", 0, 10, "t"),
)
class TestRealLife... |
UNINETT/nav | python/nav/web/portadmin/forms.py | Python | gpl-2.0 | 1,575 | 0 | #
# Copyright (C) 2014 Uninett AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 3 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope... | FormHelper()
self.helper.fo | rm_action = 'portadmin-index'
self.helper.form_method = 'GET'
self.helper.layout = Layout(
Row(
Column('query', css_class='medium-9'),
Column(Submit('submit', 'Search', css_class='postfix'),
css_class='medium-3'),
css_cla... |
alexandonian/ptutils | tests/_test_config.py | Python | mit | 600 | 0.008333 | import re
import sys
import yaml
import pprint
import torch.nn as nn
import torch.optim as optim
sys.path.insert(0, '.')
sys.path.insert(0, '..')
# from ptutils.model import AlexNet
from ptutils.session import Session
from ptutils.utils import frozendict
# from ptutils.module import Mod | ule, State, Configuration
from ptutils.base import Module, Configurati | on
from ptutils.database import DBInterface, MongoInterface
from ptutils.data import ImageNetProvider, ImageNet, HDF5DataReader
CONFIG_FILE = 'resources/config.yml'
c = Configuration(CONFIG_FILE)
sess = Session(c)
# print(c)
# print(sess)
|
ShenggaoZhu/django-sortedone2many | sortedone2many/utils.py | Python | mit | 1,509 | 0.002651 | # -*- coding: utf-8 -*-
from django.utils import six
from sortedone2many.fields import SortedOneToManyField
def inject_extra_field_to_model(from_model, field_name, field):
if not isinstance(from_model, six.string_types):
field.contribute_to_class(from_model, field_name)
return
raise Exception... | field.contribute_to_class(sender, field_name)
# # TODO: `add_field` is never called. `class_prepared` already fired or never fire??
# class_prepared.connect(add_field)
def add_sorted_one2many_relation(model_one,
model_many,
field_name... | ne):
field_name = field_name_on_model_one or model_many._meta.model_name + '_set'
related_name = related_name_on_model_many or model_one._meta.model_name
field = SortedOneToManyField(model_many, related_name=related_name)
field.contribute_to_class(model_one, field_name)
|
ESSolutions/ESSArch_Core | ESSArch_Core/essxml/ProfileMaker/migrations/0010_auto_20170808_1114.py | Python | gpl-3.0 | 573 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-08-08 09:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ProfileMaker', '0009_auto_20161020_0959'),
]
operations = [
| migrations.AddField(
model_name='extensionpackage',
name='nsmap',
field=models.JSONField(default={}),
),
migrations.AddField(
model_name='templatepackage',
name='nsmap',
field=models.JSO | NField(default={}),
),
]
|
reyoung/Paddle | python/paddle/fluid/tests/unittests/test_dropout_op.py | Python | apache-2.0 | 5,697 | 0 | # Copyright (c) 2018 PaddlePaddle 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 app... | ropoutOp):
def setUp(self):
self.op_type = "dropout"
self.inputs = {'X': np.random.random((32, 64, 2 | )).astype("float32")}
self.attrs = {
'dropout_prob': 0.0,
'fix_seed': True,
'is_test': False,
'dropout_implementation': 'upscale_in_train'
}
self.outputs = {
'Out': self.inputs['X'],
'Mask': np.ones((32, 64, 2)).astype('floa... |
sderenth/Scrapy-Draft-Data | RealGM/PlayerGameLogs.py | Python | mit | 3,667 | 0.00709 | import scrapy
import psycopg2
from bs4 import BeautifulSoup
try:
conn = psycopg2.connect(database='my_database', user='user_name', password='password', host='localhost')
print("Connected Foo!!")
except:
print("I am unable to connect to the database.")
cur = conn.cursor()
cur.execute("""SELECT p... | ,
"FGM" int,
"FGA" int,
"FG%" float,
"3PM" int,
"3PA" int,
"3P%" float,
... |
"FTA" int,
"FT%" float,
"ORB" int,
"DRB" int,
"REB" int,
"AST" int,
... |
stianrh/askbot-nordic | askbot/migrations/0014_rename_schema_from_forum_to_askbot.py | Python | gpl-3.0 | 55,671 | 0.008083 | # encoding: utf-8
import os
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
app_dir_name = os.path.basename(os.path.dirname(os.path.dirname(__file__)))
class Migration(SchemaMigration):
def forwards(self, orm):
if app_dir_name == 'forum':
... | rField', [], {'max_length': '40'}),
'summary': ('django.db.models.fields.CharField', [], {'max_length': '180'}),
'text': ('django.db.models.fields.TextField', [], {}),
'wiki': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'})
... | 'added_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
... |
mrquim/mrquimrepo | repo/plugin.video.salts/scrapers/treasureen_scraper.py | Python | gpl-2.0 | 3,727 | 0.004293 | """
SALTS XBMC Addon
Copyright (C) 2014 tknorris
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.
T... | method
def provides(cls):
return frozenset([VIDEO_TYPES.MOVIE])
@classmethod
def get_name(cls):
return 'treasureen'
def get_sources(self, video):
source_url = self.get_url(video)
hosters = []
if not source_url or source_url == FORCE_NO_MATCH: return hosters
... | erty': 'og:title'}, req='content')
meta = scraper_utils.parse_movie_link(title[0].attrs['content']) if title else {}
fragment = dom_parser2.parse_dom(html, 'p', {'class': 'download_message'})
if fragment:
for attrs, _content in dom_parser2.parse_dom(fragment[0].content, 'a', req='hre... |
jbalogh/zamboni | apps/paypal/__init__.py | Python | bsd-3-clause | 10,184 | 0.000295 | import contextlib
import socket
import urllib
import urllib2
import urlparse
import re
from django.conf import settings
from django.utils.http import urlencode
import commonware.log
from statsd import statsd
from amo.helpers import absolutify
from amo.urlresolvers import reverse
class PaypalError(Exception):
i... | : request_token, 'verifier': verification_code})
return r['token']
def _call(url, paypal_data, ip=None):
request = urllib2.Request(url)
if 'requestEnvelope.errorLanguage' not in paypal_data:
paypal_data['requestEnvelope.errorLanguage'] = 'en_US'
for key, value in [
('security-use... | ', settings.PAYPAL_EMBEDDED_AUTH['USER']),
('security-password', settings.PAYPAL_EMBEDDED_AUTH['PASSWORD']),
('security-signature', settings.PAYPAL_EMBEDDED_AUTH['SIGNATURE']),
('application-id', settings.PAYPAL_APP_ID),
('request-data-format', 'NV'),
('respon... |
cnbeining/onedrivecmd | onedrivecmd/utils/session.py | Python | agpl-3.0 | 8,409 | 0.010703 | #!/usr/bin/env python
#coding:utf-8
# Author: Beining --<[email protected]>
# Purpose: Session helper for onedrivecmd
# Created: 09/24/2016
import onedrivesdk
import logging
import json
from time import time
try:
from static import *
from helper_file import *
except ImportError:
from .static import *
f... | status_dict['client.auth_provider._session']['access_token'],
status_dict['client.auth_provider._session']['client_id'],
status_dict['client.auth_provider._session']['auth_server_url'],
... | |
kerneltask/micropython | ports/cc3200/tools/smoke.py | Python | mit | 1,883 | 0.000531 | from machine import Pin
from machine import RTC
import time
import os
"""
Execute it like this:
python3 run-tests --target wipy --device 192.168.1.1 ../cc3200/tools/smoke.py
"""
pin_map = [23, 24, 11, 12, 13, 14, 15, 16, 17, 22, 28, 10, 9, 8, 7, 6, 30, 31, 3, 0, 4, 5]
test_bytes = os.urandom(1024)
def test_pin_rea... | "test" not in ls)
print(ls)
# test the real time clock
rtc = RTC()
while rtc.now()[6] > 800:
pass
time1 = rtc.now()
time.sleep_ms(1000)
time2 = rtc.now()
print(time2[5] - time1[5] == 1)
| print(time2[6] - time1[6] < 5000) # microseconds
|
noam09/deluge-telegramer | telegramer/include/telegram/userprofilephotos.py | Python | gpl-3.0 | 2,091 | 0.002391 | #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2018
# Leandro Toledo de Souza <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... | rn None
data = super(UserProfilePhotos, cls).de_json(data, bot)
data['photos'] = [PhotoSize.de_list(photo, bot) for phot | o in data['photos']]
return cls(**data)
def to_dict(self):
data = super(UserProfilePhotos, self).to_dict()
data['photos'] = []
for photo in self.photos:
data['photos'].append([x.to_dict() for x in photo])
return data
|
citrix-openstack-build/trove | trove/extensions/security_group/views.py | Python | apache-2.0 | 3,880 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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
#
# ... | ,
"security-groups", str(self.secgroup['id']))
links = [
{
'rel': 'self',
'href': href
}
]
return links
def _build_rules(self):
rules = []
if self.rules is None:
return rules
... | .rules:
rules.append({'id': str(rule['id']),
'protocol': rule['protocol'],
'from_port': rule['from_port'],
'to_port': rule['to_port'],
'cidr': rule['cidr'],
})
return rul... |
michaelmurdock/mmlib | fname_info.py | Python | bsd-2-clause | 11,171 | 0.017545 | # fname_info.py
'''
fname.py module wraps the cfname class, which is used to simplify the task
of dealing with filenames.
'''
from __future__ import print_function
import os.path
class cfname_info(object):
'''
An instance of cfname_info class is used to represent a single filename.
After ... | : Expectation is to run without failure.
'''
try:
| inst = cfname(dirname=d, filename=f, fullname=fn, suffix=s)
except ValueError as e:
return (False, 'Unexpected exception with test %d: %s' % (id, str(e)))
return (True, '')
def unit_test_neg(id, d, f, fn, s):
'''
Negative unit test harness: Expectation is to fail.
... |
cgarrard/osgeopy-code | Chapter4/listing4_2.py | Python | mit | 1,083 | 0.000923 | import os
from osgeo import ogr
def layers_to_feature_dataset(ds_name, gdb_fn, dataset_name):
"""Copy layers to a feature dataset in a file geodatabase."""
# Open the input datasource.
in_ds = ogr.Open(ds_name)
| if in_ds is None:
raise RuntimeError('Could not open datasource')
# Open the geodatabase or create it if it doesn't exist.
gdb_driver = ogr.GetDriverByName('FileGDB')
if os.path.exists(gdb_fn):
gdb_ds = gdb_driver.Open(gdb_fn, 1)
else:
| gdb_ds = gdb_driver.CreateDataSource(gdb_fn)
if gdb_ds is None:
raise RuntimeError('Could not open file geodatabase')
# Create an option list so the feature classes will be
# saved in a feature dataset.
options = ['FEATURE_DATASET=' + dataset_name]
# Loop through the layers in the in... |
balarsen/Scrabble | scrabble/test.py | Python | bsd-3-clause | 72 | 0.013889 | real = complex(1, 1).re | al
imag = comple | x(1, 1).imag
print(real, imag)
|
ecino/compassion-switzerland | muskathlon/forms/partner_coordinates_form.py | Python | agpl-3.0 | 3,075 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# @author: Emanuel Cino <ecino | @compassion.ch>
#
# The licence is in the file __manifest__.py
#
##############################################################################
import re
from odoo import models, tools, _
testing = tools.config.get('test_enable')
if not testing:
# prevent these forms to be registered when running tests
... | oordinatesForm(models.AbstractModel):
_name = 'cms.form.partner.coordinates'
_inherit = 'cms.form'
form_buttons_template = 'cms_form_compassion.modal_form_buttons'
form_id = 'modal_coordinates'
_form_model = 'res.partner'
_form_model_fields = [
'name', 'email... |
six8/python-clom | src/clom/_compat.py | Python | mit | 240 | 0 | PY2 = (str is bytes)
PY3 = (str is not bytes)
if PY | 3:
number_types = (int, float)
integer_types = int
string_types | = str
else:
number_types = (int, long, float)
integer_types = (int, long)
string_types = basestring
|
Orav/kbengine | kbe/res/scripts/common/Lib/site-packages/setuptools/script template.py | Python | lgpl-3.0 | 167 | 0 | # EASY-INS | TALL-SCRIPT: %(spec)r,%(script_name)r
__requ | ires__ = """%(spec)r"""
import pkg_resources
pkg_resources.run_script("""%(spec)r""", """%(script_name)r""")
|
js850/PyGMIN | pygmin/optimize/result.py | Python | gpl-3.0 | 2,911 | 0.005496 | # Result object copied from scipy 0.11
__all__=['Result']
class Result(dict):
""" Represents the optimization re | sult.
Attributes
----------
coords : ndarray
The solution of the optimization.
success : bool
Whether or not the optimizer exited successfully.
status : int
Termination status of the optimi | zer. Its value depends on the
underlying solver. Refer to `message` for details.
message : str
Description of the cause of the termination.
energy : ndarray
energy at the solution
grad : ndarray
gradient at the solution
nfev : int
Number of evaluations of the func... |
HL7/hl7-c-cda-ex | db_create.py | Python | epl-1.0 | 625 | 0.0016 | #!flask/bin/python
from app.db import db
import os.path
import git
import ipdb
import git
import shutil
from parse_meta_data import parse |
LOCAL_EXAMPLES_REPO_DIR = "./ccda_examples_repo"
BRANCH = 'permalinksHashObject'
shutil.rmtree(LOCAL_EXAMPLES_REPO_DIR)
repo = git.Repo.clone_from("https://github.com/schmoney/C-CDA-Examples.git", LOCAL_EXAMPLES_REPO_DIR)
repo.git.pull("origin", BRANCH)
parse(LOCAL_EXAMPLES_REPO_DIR)
basedir = os.path.abspath(os.pat... | mples = db.examples.find().count()
print "loaded {} sections and {} examples".format(sections, examples)
|
unioslo/cerebrum | Cerebrum/modules/hr_import/errors.py | Python | gpl-2.0 | 948 | 0 | # -*- coding: utf-8 -*-
#
# Copyright 2021 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum 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 y... | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for mo | re details.
#
# You should have received a copy of the GNU General Public License
# along with Cerebrum; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""
Errors relating to the hr-import
"""
class NonExistentOuError(Exception):
"""An error to raise... |
derdon/chef | chef/external/pretty.py | Python | isc | 20,504 | 0.000536 | # -*- coding: utf-8 -*-
"""
pretty
~~
Python advanced pretty printer. This pretty printer is intended to
replace the old `pprint` python module which does not allow developers
to provide their own pretty print callbacks.
This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira... | nt to support python 2.4 and lower you can use this code::
class MyList(list):
def __pretty__(self, p, cycle):
if cycle:
p.text('MyList(...)')
else:
p.begin_group(8, 'MyList([')
for idx, item in enumerate(s... | p.breakable()
p.pretty(item)
p.end_group(8, '])')
If you just want to indent something you can use the group function
without open / close parameters. Under python 2.5 you can also use this
code::
with p.indent(2):
...
Or u... |
postpdm/ich_bau | support/views.py | Python | apache-2.0 | 440 | 0.025 | from django.shortcuts import render, redir | ect
from django.http import HttpResponseRedirect
from .models import SupportProject
# Create your views here.
def index( request ):
| sp = SupportProject.objects.all()
if sp.count() == 1:
return HttpResponseRedirect( sp.first().project.get_absolute_url() )
else:
context_dict = { 'sps' : sp, }
return render( request, 'support/index.html', context_dict )
|
AVatch/django-rest-boilerplate | djb/manage.py | Python | mit | 246 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.env | iron.setdefault("DJANGO_SETTINGS_MODULE", "djb.settings")
from django.core.management import execute_from_command_line
execute_from_ | command_line(sys.argv)
|
AjayKrP/Computer-Network | LEAKY-BUCKET/client.py | Python | gpl-3.0 | 2,214 | 0.00813 | import socket
from packet import send_data, send_close
import random, time, pickle
import threading
from packet import *
listening = True
total_acked = 0
def listen_ack(sock):
global total_acked
while listening:
raw_data, _ = sock.recvfrom(2048)
ack_packet = pickle.loads(raw_data)
if a... | ; it can only function" \
" in the context of a complete operating system. Linux is normally used in combination with the GNU operating | system:" \
" the whole system is basically GNU with Linux added, or GNU/Linux. All the so-called Linux distributions are really " \
"distributions of GNU/Linux!"
main(('127.0.0.1',8081,), data.split(' '))
|
invliD/lana-dashboard | lana_dashboard/lana_data/migrations/0008_wireguard.py | Python | agpl-3.0 | 1,317 | 0.003042 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-04-07 17:45
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('lana_data', '0007_peering'),
]
operations = [
... | name='WireGuardTunnelEndpoint',
fields=[
('tunnelendpoint_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='lana_data.Tunn | elEndpoint')),
('port', models.IntegerField(blank=True, help_text='Defaults to remote AS number if ≤ 65535.', null=True, verbose_name='Port')),
('public_key', models.CharField(blank=True, max_length=255, null=True, verbose_name='Public key')),
],
bases=('lana_data... |
pexip/pygobject | examples/demo/demos/infobars.py | Python | lgpl-2.1 | 3,918 | 0.001531 | #!/usr/bin/env python
# -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
#
# Copyright (C) 2010 Red Hat, Inc., John (J5) Palmieri <[email protected]>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License a... | se, False, 0)
bar = Gtk.InfoBar()
vbox.pack_start(bar, Fa | lse, False, 0)
bar.set_message_type(Gtk.MessageType.ERROR)
label = Gtk.Label(label='This is an info bar with message type Gtk.MessageType.ERROR')
bar.get_content_area().pack_start(label, False, False, 0)
bar = Gtk.InfoBar()
vbox.pack_start(bar, False, False, 0)
bar.set_m... |
MERegistro/meregistro | meregistro/apps/registro/forms/ExtensionAulicaConexionInternetForm.py | Python | bsd-3-clause | 1,222 | 0.013912 | # -*- coding: utf-8 -*-
from apps.registro.models.ExtensionAulicaConexionInternet import ExtensionAulicaConexionInternet
from apps.registro.models.TipoConexion import TipoConexion
from django.core.exceptions import ValidationError
from django import forms
class ExtensionAulicaConexionInternetForm(forms.ModelForm):
... | sionAulicaConexionInternet
exclude = ['extension_aulica']
def __chequear_si_tiene_conexion(self, field):
if self.cleaned_data['tiene_conexion']:
if (self.cleaned_data[field] is None
or self.cleaned_data[field] == ''):
raise ValidationError('Este campo es obligatorio.')
return self.c... | ned_data[field]
return None
def clean_tipo_conexion(self):
return self.__chequear_si_tiene_conexion('tipo_conexion')
def clean_proveedor(self):
return self.__chequear_si_tiene_conexion('proveedor')
def clean_costo(self):
return self.__chequear_si_tiene_conexion('costo')
def clean_cantidad(se... |
hydroshare/hydroshare_temp | urls.py | Python | bsd-3-clause | 5,696 | 0.005794 | from __future__ import unicode_literals
from django.conf.urls import patterns, include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from mezzanine.core.views import direct_to_template
from mezzanine.conf import settings
from hs_core.api import v1_api
from theme import views a... | settings.PACKAGE_NAME_FILEBROWSER)),
)
# Put API URLs before Mezzanine so that Mezzanine doesn't consume them
urlpatterns += patterns('',
(r'^api/', include(v1_api.urls) ),
url("^api/%s/doc/" % (v1_api.api_name,),
include('tastypie_swagg... | namespace='tastypie_swagger'),
kwargs={'tastypie_api_module':'hs_core.api.v1_api',
'namespace':'tastypie_swagger'}
),
url('^hsapi/', include('hs_core.urls'))
... |
wschoenell/chimera_imported_googlecode | src/chimera/util/image.py | Python | gpl-2.0 | 13,397 | 0.006121 |
import chimera.core.log
from chimera.core.remoteobject import RemoteObject
from chimera.core.exceptions import ChimeraException
from chimera.core.version import _chimera_name_, _chimera_long_description_
from chimera.util.coord import Coord
from chimera.util.position import Position
from chimera.util.filenamesequenc... | s(dirname):
os.makedirs(dirname)
if not os.path.isdir(dirname):
raise OSError("A file with the same name as the desired directory already exists. ('%s')" % dirname)
if os.path.exists(finalname):
finalname = os.path.join(dirname, "%s-% | 04d%s%s" % (filename, int (random.random()*1000), os.path.extsep, ext))
return finalname
class Image (DictMixin, RemoteObject):
"""
Class to manipulate FITS images with a Pythonic taste.
The underlying framework comes from the very good PyFITS library
with some PyWCS stuff to... |
vaibhavg2896/PythonSimpleGUI | Rock-paper-scissor-lizard-Spock.py | Python | gpl-3.0 | 2,546 | 0.022388 | ##########################################################
#07:10 PM
#Thursday, June 11, 2016 (GMT+5:30)
#@ author : VAIBHAV GUPTA(15454)
#########################################################
# Rock-paper-scissors-lizard-Spock template
import simplegui
# helper functions
def name_to_number(name):
# de... | t and fill in your code below
if name=="rock":
return 0
elif name=="Spock":
return 1
elif name=="paper":
return 2
elif name=="lizard":
return 3
elif name=="scissors":
return 4
else:
return None
# convert name to number using if/elif/else... |
def number_to_name(number):
# delete the following pass statement and fill in your code below
if number==0:
return "rock"
elif number==1:
return "Spock"
elif number==2:
return "paper"
elif number==3:
return "lizard"
elif number==4:
return "scissors"
e... |
rymcimcim/django-foosball | game/migrations/0001_initial.py | Python | mit | 2,887 | 0.003117 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-10-01 18:03
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):
initial = True
dependencies = [
migratio... | e=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('winner_score', models.PositiveSmallIntegerField()),
('looser_score', models.PositiveSmallIntegerField()),
... | ('added_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='MatchSet',
fields=[
('... |
google/mediapipe | mediapipe/python/image_test.py | Python | apache-2.0 | 7,872 | 0.003684 | # Copyright 2021 The MediaPipe 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 ... | GRAY8, data=mat)
self.assertTrue(np.array_equal(mat, image.numpy_view()))
with self.assertRaisesRegex(IndexError, 'index dimen | sion mismatch'):
print(image[w, h, 1])
with self.assertRaisesRegex(IndexError, 'out of bounds'):
print(image[w, h])
self.assertEqual(42, image[2, 2])
def test_create_image_from_rgb_cv_mat(self):
w, h, channels = random.randrange(3, 100), random.randrange(3, 100), 3
mat = cv2.cvtColor(
... |
abramhindle/UnnaturalCodeFork | python/testdata/launchpad/lib/lp/services/job/tests/test_runner.py | Python | agpl-3.0 | 23,096 | 0.000346 | # Copyright 2009 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Tests for job-running facilities."""
import logging
import re
import sys
from textwrap import dedent
from time import sleep
from lazr.jobrunner.jobrunner import (
LeaseHel... | D, job_2.job.status)
oops = self.oopses[-1]
self.assertIn('Fake exception. Foobar, I say!', oops['tb_text'])
self | .assertEqual(["{'foo': 'bar'}"], oops['req_vars'].values())
def test_oops_messages_used_when_handling(self):
"""Oops messages should appear even when exceptions are handled."""
job_1, job_2 = self.makeTwoJobs()
def handleError():
reporter = errorlog.globalErrorUtility
... |
QinerTech/QinerApps | openerp/addons/account/models/account_move.py | Python | gpl-3.0 | 68,633 | 0.005129 | # -*- coding: utf-8 -*-
import time
from openerp import api, fields, models, _
fr | om openerp.osv import expression
from openerp.exceptions import RedirectWarning, UserError
from openerp.tools.misc import formatLang
from openerp.tools import float_is_zero
from openerp.tools.safe_eval import safe_eval
#----------------------------------------------------------
# Entries
#----------------------------... | depends('name', 'state')
def name_get(self):
result = []
for move in self:
if move.state == 'draft':
name = '* ' + str(move.id)
else:
name = move.name
result.append((move.id, name))
return result
@api.multi
@api.dep... |
Forage/Gramps | gramps/gen/filters/rules/event/_hasreferencecountof.py | Python | gpl-2.0 | 1,730 | 0.00578 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2007 Stephane Charette
#
# 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 optio... | -------------------------------------------
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.get_translation().gettext
#-------------------------------------------------------------------------
#
# GRAMPS modules
#
#----------- | --------------------------------------------------------------
from .._hasreferencecountbase import HasReferenceCountBase
#-------------------------------------------------------------------------
# "Events with a certain reference count"
#-------------------------------------------------------------------------
class... |
tri2sing/LinearAlgebraPython | test_hw7.py | Python | apache-2.0 | 743 | 0.048452 | from hw7 import QR_solve
from mat import coldict2mat
from mat import Mat
from orthonormalization import aug_orthonormalize
from QR import factor
from vec import Vec
from vecutil import list2vec
print('Augmented | Orthonormalize')
L = [list2vec(v) for v in [[4,3,1,2],[8,9,-5,-5],[10,1,-1,5]]]
print(coldict2mat(L))
Qlist, Rlist = aug_orthonormalize(L)
print(coldict2mat(Qlist))
print(coldict2mat(Rlist | ))
print((coldict2mat(Qlist)*coldict2mat(Rlist)))
print('QR Solve')
A=Mat(({'a','b','c'},{'A','B'}), {('a','A'):-1, ('a','B'):2, ('b','A'):5, ('b','B'):3,('c','A'):1, ('c','B'):-2})
print(A)
Q, R = factor(A)
print(Q)
print(R)
b = Vec({'a','b','c'}, {'a':1,'b':-1})
x = QR_solve(A,b)
print(x)
residual = A.transpose()*(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.