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 |
|---|---|---|---|---|---|---|---|---|
natedileas/ImageRIT | Server/qt_CameraWidget.py | Python | gpl-3.0 | 1,349 | 0.006672 | import time
import threading
import json
import cv2
from PyQt5 import QtCore
from PyQt5.QtGui import QImage
from effects import process
class ImageRIT_PyQt(QtCore.QObject):
newFrame = QtCore.pyqtSignal(QImage)
def __init__(self, cameraId, state_func):
super(ImageRIT_PyQt, self).__init__()
... |
self.state_func = state_func
self._timer = QtCore.QTimer(self)
self._timer.timeout.connect(self.query_image)
self._timer.start(1000/30)
@QtCore.pyqtSlot()
def query_image(self):
#time_elapsed = 1 / 30.
#while 1:
# start = ti | me.time()
# grab frame
flag, frame = self.cameraDevice.read()
if not flag:
print ('flag')
return
# get state
config = self.state_func()
#if config is not None: return
# process
processed_frame = numpy2qimage(process(frame, confi... |
th3sys/capsule | nightwatch.py | Python | mit | 16,596 | 0.002169 | import boto3
import logging
import argparse
import os
from botocore.exceptions import ClientError
from boto3.dynamodb.conditions import Key, Attr
import json
import decimal
import time
import datetime
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import contracts
fro... | % (params.Regi | on, params.Instance))
def AttemptsCount(self):
timestamp = int((datetime.datetime.now() - datetime.timedelta(hours=2)).timestamp()) * 1000
logs = boto3.client('logs')
log_group = '/aws/docker/Capsule'
data = logs.describe_log_streams(logGroupName=log_group, orderBy='LastEventTime', ... |
HUGG/NGWM2016-modelling-course | Lessons/03-Analytical-solutions-heat-transfer/scripts/plot_steady_state_heat_eq_advection.py | Python | mit | 1,797 | 0.008347 | import numpy as np
import matplotlib.pyplot as plt
import sys
### Plot the analytical solution of the heat equation
# * Steady-state
# * Constant advection velocity
# * Constant heat diffusivity
# * Constant heat production
#
# Choosable boundary conditions
# - Fixed surface temperature T=0
# - Fixed bo... | ot
xlimits = (0.0, 600.0)
###### End of configurable parameters ######
### Main program:
# Calculate diffusivity
kappa = k / (rho * Cp)
# Calc depth range for the plot
N = 1000 # num of points we use for plotting
z = np.linspace(0, L, N)
# Calculate integration constants
### Evaluate temperature at chosen range
... | line to plot the temperature gradient (dT/dz = q/k) at the bottom boundary
Tbot_grad = [T[N-1], T[N-1] - ( k*(T[N-1]-T[N-2])/(z[N-1]-z[N-2]) )*(L/3.0)/k]
zbot_grad = [-z[N-1], -z[N-1] + (L/3.0)]
# Plot the geotherm
plt.figure()
plt.plot(T, -z, "-b") # T on horizontal axis, z on vertical, pointing down (minus sign), ... |
phracek/rebase-helper | rebasehelper/completion.py | Python | gpl-2.0 | 3,343 | 0.001197 | # -*- coding: utf-8 -*-
#
# This tool helps you to rebase package to the latest version
# Copyright (C) 2013-2014 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Pu | blic License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the | implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Bosto... |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-2.1/Lib/distutils/command/install.py | Python | mit | 22,295 | 0.003185 | """distutils.command.install
Implements the Distutils 'install' command."""
# created 1999/03/13, Greg Ward
__revision__ = "$Id: install.py,v 1.56 2001/01/16 16:16:03 akuchling Exp $"
import sys, os, string
from types import *
from distutils.core import Command, DEBUG
from distutils.sysconfig import get_config_vars... | re, but it might be useful in future.) They
# are not user options, because if the user told the install
# command where the build directory is, that wouldn't affect the
# build command.
self.build_base = None
self.build_lib = None
# Not defined yet because we don't kno... |
#self.install_man = None
#self.install_html = None
#self.install_info = None
self.record = None
# -- Option finalizing methods -------------------------------------
# (This is rather more involved than for most commands,
# because this is where the policy for installing t... |
be-cloud-be/horizon-addons | partner-contact/partner_address_street3/hooks.py | Python | agpl-3.0 | 1,003 | 0 | # -*- coding: utf-8 -*-
# Copyright 2014 Nicolas Bessi, Alexandre Fayolle, Camptocamp SA
# Copyright 2016 Sodexis
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
def post_init_hook(cr, registry):
""" Add street3 to address format """
query = """
UPDATE res_country
SET address_f... | rom address format """
# Remove %(street3)s\n from address_format
query = """
UPDATE res_country
SET address_format = replace(
address_format,
E'%(street3)s\n',
''
)
"""
cr.execute(query)
# Remove %(street3)s from address_format
query = """
... | ry)
|
mikel-egana-aranguren/SADI-Galaxy-Docker | galaxy-dist/eggs/GeneTrack-2.0.0_beta_1_dev_48da9e998f0caf01c5be731e926f4b0481f658f0-py2.7.egg/genetrack/fitlib.py | Python | gpl-3.0 | 7,159 | 0.014248 | """
Data fitting and peak prediction routines
"""
import genetrack
from genetrack import logger, conf
from itertools import *
import numpy, operator
from math import log, exp
def normal_function( w, sigma ):
"""
Defaulf fitting function, it returns values
from a normal distribution over a certain width.
... | is peak
selected.append( ( peakx, peaky ) )
# block the region
left = locind - exclusion
right = locind + exclusion
empty[left:right] = numpy.zeros (righ | t - left, numpy.int8)
selected.sort()
return selected
def fixed_width_predictor(x, y, params):
"""
Generates peaks from a x,y dataset.
>>> from genetrack import util
>>>
>>> y = [ 0.0, 1.0, 2.5, 1.0, 3.5, 1.0, 0.0, 0.0, 10.5, 2.0, 1.0, 0.0 ]
>>> x = range(len(y))
>>>
>>... |
dschreij/Datamerger | setup-py2exe.py | Python | gpl-2.0 | 1,779 | 0.037662 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
This file is part of OpenSesame.
Datamerger is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as pub | lished by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Datamerger is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANT | ABILITY 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 OpenSesame. If not, see <http://www.gnu.org/licenses/>.
This scripts builds OpenSesame as a standalone application for Mac OS.
Usage:
py... |
MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-3.6.0/Lib/test/test_capi.py | Python | mit | 27,270 | 0.006051 | # Run the _testcapi module tests (tests for the Python/C API): by defn,
# these are all functions _testcapi exports whose name begins with 'test_'.
import os
import pickle
import random
import re
import subprocess
import sys
import sysconfig
import textwrap
import time
import unittest
from test import support
from te... | LL_pointer(self):
self.assertRaises(ValueError, _testcapi.make_memoryview | _from_NULL_pointer)
def test_exc_info(self):
raised_exception = ValueError("5")
new_exc = TypeError("TEST")
try:
raise raised_exception
except ValueError as e:
tb = e.__traceback__
orig_sys_exc_info = sys.exc_info()
orig_exc_info = _te... |
osmcode/pyosmium | src/osmium/osm/__init__.py | Python | bsd-2-clause | 4,292 | 0.003961 | import osmium.osm.mutable
from ._osm import *
def create_mutable_node(node, **args):
""" Create a mutable node replacing the properties given in the
named parameters. Note that this function only creates a shallow
copy which is still bound to the scope of the original object.
"""
return osm... | + ', '.join(['{0}={{1.{0}!r}}'.format(x) for x in attr_list])\
+ ')'
return lam | bda o: fmt_string.format(o.__class__.__name__, o)
def _list_repr(obj):
return 'osmium.osm.{}([{}])'.format(obj.__class__.__name__,
', '.join(map(repr, obj)))
def _list_elipse(obj):
objects = ','.join(map(str, obj))
if len(objects) > 50:
objects = objects[:47... |
raghon1/seafile | docker-suitecrm/scripts/setup-seafile-mysql.py | Python | gpl-3.0 | 45,788 | 0.002402 | #coding: UTF-8
'''This script would guide the seafile admin to setup seafile with MySQL'''
import sys
import os
import time
import re
import shutil
import glob
import subprocess
import hashlib
import getpass
import uuid
import warnings
import MySQLdb
from ConfigParser import ConfigParser
try:
import readline # ... | welcome_msg = '''\
-----------------------------------------------------------------
This script will guide you to setup your seafile server using MySQL.
Make sure you have read seafile server manual at
%s
Press ENTER to continue
-----------------------------------------------------------------''' % SERVER_MA... | |
hugs/django | tests/modeltests/ordering/models.py | Python | bsd-3-clause | 3,031 | 0.003299 | """
6. Specifying ordering
Specify default ordering for a model using the ``ordering`` attribute, which
should be a list or tuple of field names. This tells Django how to order
``QuerySet`` results.
If a field name in ``ordering`` starts with a hyphen, that field will be
ordered in descending order. Otherwise, it'll ... | in the same format as the ordering
# attribute in models.
>>> Article.objects.order_by('headline')
[<Article: Article 1>, <Article: Article 2>, <Article: Article 3>, <Article: Article 4>]
>>> Article.objects.order_by('pub_date', '-headline')
[<Articl | e: Article 1>, <Article: Article 3>, <Article: Article 2>, <Article: Article 4>]
# Only the last order_by has any effect (since they each override any previous
# ordering).
>>> Article.objects.order_by('id')
[<Article: Article 1>, <Article: Article 2>, <Article: Article 3>, <Article: Article 4>]
>>> Article.objects.or... |
rwl/PyCIM | CIM15/CDPSM/Geographical/IEC61970/__init__.py | Python | mit | 1,545 | 0.001942 | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... | e Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WA | RRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWIS... |
Level-Up/django-ponypusher | setup.py | Python | gpl-3.0 | 651 | 0.032258 | from distutils.core import setup
from setuptools | import find_packages
from ponypusher import VERSION
setup(
#this is the name of the package to install from pypi/chishop
name='django-ponypusher',
description='Pusher app library for django',
author='Raymond McGinlay',
author_email='ray@lvlup.us',
#version number is derived from VERSION attribute defined in __init.py... | to be installed in package
packages=['ponypusher', ],
#python pusher library is required
install_requires=['pusher',],
license='GPL v3',
#Description that will appear on pypi/chishop
long_description=open('README.rst').read(),
include_package_data=True,
)
|
rizar/attention-lvcsr | libs/fuel/docs/conf.py | Python | mit | 9,795 | 0.000409 | # -*- coding: utf-8 -*-
#
# Fuel documentation build configuration file, created by
# sphinx-quickstart2 on Wed Oct 8 17:59:44 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All... | e page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are par | ts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# late |
jaygoswami2303/course_dashboard_api | v2/dbv.py | Python | mit | 133 | 0 | MYSQL_DB = 'edxapp'
MYSQL_USER | = 'root'
MYSQL_PSWD = ''
MONGO_DB = 'edxapp'
MONGO_DISC | USSION_DB = 'cs_comments_service_development'
|
Azure/azure-sdk-for-python | sdk/modelsrepository/azure-iot-modelsrepository/samples/get_models_sample.py | Python | mit | 3,524 | 0.003689 | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from azure... | EPENDENCY_MODE_ENABLED,
)
from azure.core.exceptions import (
ResourceNotFoundError,
ServiceRequestError,
ServiceResponseError,
HttpResponseError,
)
import pprint
dtmi = "dtmi | :com:example:TemperatureController;1"
dtmi2 = "dtmi:com:example:TemperatureController;2"
# By default the clients in this sample will use the Azure Device Models Repository endpoint
# i.e. https://devicemodels.azure.com/
# See client_configuration_sample.py for examples of alternate configurations
def get_model():
... |
aheadley/Minecraft-Overviewer | overviewer_core/textures.py | Python | gpl-3.0 | 193,926 | 0.019244 | # This file is part of the Minecraft Overviewer.
#
# Minecraft Overviewer 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... | xception):
"To be thrown when a texture is not found."
pass
color_map = ["white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray",
"silver", "cyan", "purple", "blue", "brown", "g | reen", "red", "black"]
##
## Textures object
##
class Textures(object):
"""An object that generates a set of block sprites to use while
rendering. It accepts a background color, north direction, and
local textures path.
"""
def __init__(self, texturepath=None, bgcolor=(26, 26, 26, 0), northdirectio... |
kgsn1763/deep-learning-from-scratch | ch07/train_convnet.py | Python | mit | 1,553 | 0.004919 | #!/usr/bin/env python
# coding: utf-8
import sys, os
sys.path.append(os.pardir) # 親ディレクトリのファイルをインポートするための設定
import numpy as np
import matplotlib.pyplot as plt
from dataset.mnist import load_mnist
from simple_convnet import SimpleConvNet
from common.trainer import Trainer
# データの読み込み
(x_train, t_train), (x_test, t_tes... | 処理に時間のかかる場合はデータを削減
# x_train, t_train = x_train[:5000], t_train[:5000]
# x_test, t_test = x_test[:1000], t_test[:1000]
max_epochs = 20
network = SimpleConvNet(input_dim=(1, 28, 28),
conv_param={'filter_num': 30, 'filter_size': 5, 'pad': 0, 'stride': 1},
hidde | n_size=100, output_size=10, weight_init_std=0.01)
trainer = Trainer(network, x_train, t_train, x_test, t_test,
epochs=max_epochs, mini_batch_size=100,
optimizer='Adam', optimizer_param={'lr': 0.001},
evaluate_sample_num_per_epoch=1000)
trainer.train()
# パラメータの保存
n... |
btcgroup2/bitcoin | test/functional/test_framework/util.py | Python | mit | 19,182 | 0.004171 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Helpful routines for regression testing."""
from base64 import b64encode
from binascii import hexlify,... | ound:" + e.error['message'])
except Exception as e:
raise AssertionError("Unexpected exception raised: " + type(e).__name__)
else:
raise AssertionError("No exception raised")
def assert_is_hex_string(string):
try:
int(string, 16)
except Exception as e:
raise AssertionErr... | raise AssertionError("Expected a string, got type %r" % type(string))
elif length and len(string) != length:
raise AssertionError(
"String of length %d expected; got %d" % (length, len(string)))
elif not re.match('[abcdef0-9]+$', string):
raise AssertionError(
"Str... |
belokop/indico_bare | indico/modules/rb/controllers/admin/__init__.py | Python | gpl-3.0 | 1,335 | 0 | # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico 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 (a... | U
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see | <http://www.gnu.org/licenses/>.
from flask import session
from werkzeug.exceptions import Forbidden
from indico.modules.rb.controllers import RHRoomBookingBase
from indico.modules.rb.util import rb_is_admin
from indico.util.i18n import _
class RHRoomBookingAdminBase(RHRoomBookingBase):
"""
Adds admin author... |
tzpBingo/github-trending | codespace/python/tencentcloud/tms/v20201229/tms_client.py | Python | mit | 3,829 | 0.003083 | # -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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... | erning permissions and
# limitations under the License.
import json
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from | tencentcloud.common.abstract_client import AbstractClient
from tencentcloud.tms.v20201229 import models
class TmsClient(AbstractClient):
_apiVersion = '2020-12-29'
_endpoint = 'tms.tencentcloudapi.com'
_service = 'tms'
def TextModeration(self, request):
"""本接口(Text Moderation)用于提交文本内容进行智能审核任... |
grapesmoker/qems2 | qems2/qsub/migrations/0015_auto_20150119_1018.py | Python | gpl-2.0 | 677 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('qsub', '0014_auto_20 | 150117_1910'),
]
operations = [
migrations.AddField(
model_name='bonus',
name='category_entry',
field=models.ForeignKey(to='qsub.CategoryEntry', null=True),
preserve_default=True,
),
migrations.AddField(
model_name='tossup',
... | try', null=True),
preserve_default=True,
),
]
|
franpandol/curso-django-snippets | snippets_project/settings.py | Python | gpl-3.0 | 4,420 | 0.003167 | """
Django settings for snippets_project project.
Generated by 'django-admin startproject' using Django 1.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
impor... | #'djangobower',
#http://django-crispy-forms.readthedocs.io/en/latest/
'crispy_f | orms',
#'fm', # Form ModalView
#'bootstrap3_datetime',
'django_extensions',
'braces',
'registration',
'django_tables2',
)
PROJECT_APPS = (
'snippets',
'web',
#'util',
)
INSTALLED_APPS = DJANGO_APPS + EXTERNAL_APPS + PROJECT_APPS
MIDDLEWARE_CLASSES = [
'django.middleware... |
proversity-org/edx-app-ios | script/whitelabel.py | Python | apache-2.0 | 8,765 | 0.00194 | #!/usr/bin/env python
"""
Script to update the current edX iOS App with different names, resources, etc.
Requirements:
pip install pyyaml
"""
import argparse
import logging
import os
import shutil
import subprocess
import sys
import yaml
class WhitelabelApp:
"""
Update the current edX iOS App using co... | lf.project_properties and self.config_dir:
logging.info("Creating %s", self.project_properties)
content = "edx.dir = '{config_dir}'"
with open(self.project_properties, 'w') as f:
f.write(content.format(config_dir=self.config_dir))
else:
logging.deb... | set", self.project_properties)
def update_plist(self):
"""
Update the app's plist file.
"""
for name, value in self.plist.items():
if self._update_plist(name, value):
logging.info("Updated %s: %s=%s", self.project_plist, name, value)
else:
... |
kevintroy/huffman_encoding | huffman.py | Python | gpl-2.0 | 4,298 | 0.003961 | # Huffman's algorithm for variable-length encoding
# Takes a plaintext and returns a codebook together with the coded text
def huffman(plaintext):
# helper function: construct the frequency table for the plaintext
def frequency_table(plaintext):
table = {}
for char in plaintext:
if... | n
# Then we call recursively until all nodes are assembled into the tree
def huffman_tree(nodes_list):
# base case: all nodes have been combined into one tree, i.e. we're done
if len(nodes_list) < 2:
return nodes_list
else:
nodes_list.sort(key= lambda i: i[1], rev... | af_node0 = nodes_list.pop() # take the two nodes with least frequency
leaf_node1 = nodes_list.pop() # and combine them into a branch
branch_node = (leaf_node0[0] + " or " + leaf_node1[0],
leaf_node0[1] + leaf_node1[1],
[leaf_node0, leaf_no... |
Junior743/poc-pip_install | codigos/teste.py | Python | mit | 194 | 0.015464 | import os
class Principal():
| def __init__(self, valor):
print(Principal | .calculaValor(valor))
def calculaValor(valor):
valor = valor + 10
return valor
|
pkimber/cms | cms/models.py | Python | apache-2.0 | 233 | 0.004292 | # -*- encoding: utf-8 -*-
from django.db import models
import | reversion
from base.model_utils import TimeStampedModel
from base.singleton import SingletonModel
from block.models import (
Page, |
PageSection,
Section,
)
|
kaleid0scope/SITE-database | DjangoWebProject/DjangoWebProject/app/lecture.py | Python | gpl-3.0 | 7,157 | 0.034943 | # -*- coding: UTF-8 -*-
from django.shortcuts import render
from DjangoWebProject import settings
from django.http import HttpRequest
from django.template import RequestContext
from django.template.loader import get_template
from datetime import datetime
from django.shortcuts import render_to_response
from django.cont... | project.score = choice.score
project.complete = choice.complete
if request.POST.has_key('passyes'):
| project.status = '通过'
elif request.POST.has_key('passno'):
project.status = '未通过'
project.inspector = inspector
project.save()
return render_with_type(request,'Index/LectureIndex.html',{'projects':Lec... |
flakey-bit/plugin.audio.spotify | resources/libs/cherrypy/test/test_caching.py | Python | gpl-3.0 | 12,738 | 0.000628 | import datetime
import gzip
from itertools import count
import os
curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
import sys
import threading
import time
import urllib
import cherrypy
from cherrypy._cpcompat import next, ntob, quote, | xrange
from cherrypy.lib import httputil
gif_bytes = ntob(
'GIF89a\x01\x00\x01\x00\x82\x00\x01\x99"\x1e\x00\x00\x00\x00\x00'
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
'\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x02\x03\x02\x08\t\x00;'
)
from cherrypy.test import helper
class CacheTest(h... | (self):
self.counter = 0
self.control_counter = 0
self.longlock = threading.Lock()
@cherrypy.expose
def index(self):
self.counter += 1
msg = "visit #%s" % self.counter
return msg
@cherry... |
viiru-/pytrainer | pytrainer/test/gui/test_color.py | Python | gpl-2.0 | 1,599 | 0.011257 | # -*- coding: utf-8 -*-
#Copyright (C) Nathan Jones ncjones@users.sourceforge.net
#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 v... | quals(0x3333, gdk_color.blue)
self.assertEquals(0xffff, gdk_color.green)
self.assertEquals(0xaaaa, gdk_color.red)
def test_convert_to_color_should_create_c | olor_with_equivalent_rgb_values(self):
gdk_col = gtk.gdk.color_parse("#aaff33")
color = self._converter.convert_to_color(gdk_col)
self.assertEqual(0xaaff33, color.rgb_val)
|
quattor/aquilon | lib/aquilon/worker/commands/del_cluster_systemlist.py | Python | apache-2.0 | 1,563 | 0 | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2009,2010,2011,2012,2013,2014,2015,2016,2017 Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You ma... | .del_cluster_member_priority import \
CommandDelClusterMemberPriority
class CommandDelClusterSystemList(CommandDelClusterMemberPriority):
required_parameters = ["cluster", "hostname"]
resource_class = SystemList
def render(self, hostname, **kwargs):
super(CommandDelClusterSystemList, self).r... | (hostname=None,
metacluster=None,
comments=None,
member=hostname,
**kwargs)
|
LividInstruments/LiveRemoteScripts | Codec_v2/Map.py | Python | mit | 3,024 | 0.040344 | # by amounra 0216 : http://www.aumhaa.com
"""
Codec_Map.py
Created by amounra on 2010-10-05.
Copyright (c) 2010 __artisia__. All rights reserved.
This file allows the reassignment of the controls from their default arrangement. The order is from left to right;
Buttons are Note #'s and Faders/Rotaries are Controlle... | LividRGB.OFF
cla | ss Transport:
OverdubOn = LividRGB.BlinkFast.RED
OverdubOff = LividRGB.RED
StopOn = LividRGB.BLUE
StopOff = LividRGB.BLUE
class Device:
NavOn = LividRGB.MAGENTA
NavOff = LividRGB.OFF
BankOn = LividRGB.YELLOW
BankOff = LividRGB.OFF
ChainNavOn = LividRGB.RED
ChainNavOff = LividRGB.OFF
ContainNav... |
alanjw/GreenOpenERP-Win-X86 | python/Lib/pstats.py | Python | agpl-3.0 | 27,126 | 0.003613 | """Class for printing reports on profiled python code."""
# Written by James Roskind
# Based on prior profile module by Sjoerd Mullender...
# which was hacked somewhat by: Guido van Rossum
# Copyright Disney Enterprises, Inc. All Rights Reserved.
# Licensed to PSF under a Contributor Agreement
#
# License... | __ != other.__class__:
other = Stats(other)
self.files += other.files
self.total_calls += other.total_calls
self.prim_calls += other.prim_calls
self.total_tt += other.total_tt
for func in other.top_level:
self.top_level[func] = None
if se... | ritems():
if func in self.stats:
old_func_stat = self.stats[func]
else:
old_func_stat = (0, 0, 0, 0, {},)
self.stats[func] = add_func_stats(old_func_stat, stat)
return self
def dump_stats(self, filename):
"""Write the prof... |
ngageoint/geoq | geoq/core/kml_view.py | Python | mit | 12,540 | 0.00303 | from django.views.generic import ListView
from django.http import HttpResponse
from .models import Job
from geoq.maps.models import FeatureType
from django.shortcuts import get_object_or_404
from datetime import datetime
from pytz import timezone
from webcolors import name_to_hex, normalize_hex
from xml.sax.saxutils i... | locations = job.feature_set.all()\
.extra(tables=['maps_featuretype'])\
.extra(where=['maps_featuretype.id=maps_feature.template_id'])\
.order_by('maps_featuretype.name')
last_template = ""
skip_the_first = True
template_has_started = False
for lo... | n locations:
template_name = str(loc.template.name)
if template_name != last_template:
if skip_the_first:
skip_the_first = False
else:
output += ' </Folder>\n'
output += ' <Folder><name>'+template_name+'<... |
Turupawn/website | games/templatetags/append_to_get.py | Python | agpl-3.0 | 1,303 | 0.000767 | from django import template
register = template.Library()
def easy_tag(func):
"""Decorator to facilitate template tag creation"""
def inner(parser, token):
"""deal with the repetitive parts of parsing template tags"""
try:
return func(*token.split_contents())
except TypeErr... | de(template.Node): |
def __init__(self, dict):
self.dict_pairs = {}
for pair in dict.split(','):
pair = pair.split('=')
self.dict_pairs[pair[0]] = template.Variable(pair[1])
def render(self, context):
get = context['request'].GET.copy()
for key in self.dict_pairs:
... |
lem9/weblate | weblate/permissions/tests.py | Python | gpl-3.0 | 15,824 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2017 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <https://weblate.org/>
#
# 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, eith... | = Language.objects.get_default()
self.trans = Translation.objects.create(
| subproject=self.subproject, language=self.language,
filename="this/is/not/a.template"
)
app, perm = self.PERMISSION.split('.')
self.permission = Permission.objects.get(
codename=perm, content_type__app_label=app
)
self.group.permissions.add(s... |
MFoster/breeze | breeze/breeze/settings/base.py | Python | bsd-3-clause | 6,127 | 0.001795 | # Django settings for breeze project.
from unipath import Path
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
PROJECT_DIR = Path(__file__).ancestor(3)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_p... | handles the media served from MEDI | A_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STAT... |
dlundquist/ansible | lib/ansible/utils/template.py | Python | gpl-3.0 | 13,049 | 0.004905 | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any lat... | nja2 extensions to load '''
'''
if some extensions are set via jinja_extensions in ansible.cfg, we try
to load them with the jinja environment
'''
jinja_exts = []
if C.DEFAULT_JINJA2_EXTENSIONS:
'''
Let's make sure the configuration directive doesn't contain spaces
and s... | '''
jinja_exts = C.DEFAULT_JINJA2_EXTENSIONS.replace(" ", "").split(',')
return jinja_exts
class Flags:
LEGACY_TEMPLATE_WARNING = False
# TODO: refactor this file
FILTER_PLUGINS = None
_LISTRE = re.compile(r"(\w+)\[(\d+)\]")
JINJA2_OVERRIDE='#jinja2:'
def lookup(name, *args, **kwargs):
from ... |
dmlc/tvm | tests/python/unittest/test_tir_transform_simplify.py | Python | apache-2.0 | 5,007 | 0.000399 | # 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... | and limitations
# under the License.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
wi | th ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def... |
CFIS-Octarine/octarine | validate/gui/views/__init__.py | Python | gpl-3.0 | 42 | 0 | __author__ = "David Rusk <drusk@uvic.c | a>"
| |
dsparrow27/vortex | src/ds/vortex/examples/simple.py | Python | mit | 2,226 | 0.004492 | """
Very simple example for creating and adding nodes to a graph
"""
from ds.vortex.core import graph
from ds.vortex.nodes.constants import scalar
from ds.vortex.nodes.math.basic import sum
from ds.vortex.nodes.math.basic import multiply
def testExample():
"""Simple test example adding three math nodes,... | # example of setting a input value
mult1.getPlug("multiplyBy").value = 2
| # connect nodes together via the plug object, the connect method returns the Edge Object when can be used to access
# or set edge data
# You can connect only from outputs to input or inputs to outputs, inputs can only have one connection
scalar1.getPlug("output").connect(add1.getPlug("value1"))
s... |
mikewolfli/django-goflow | sampleproject/urls.py | Python | bsd-3-clause | 1,453 | 0.006194 | from django.conf.urls import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# django-flags for internationalization
(r'^lang/', include('sampleproject.flags.urls')),
# FOR DEBUG AND TES... | ble admin documentation:
(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# FOR TEST - insert before admin/(.*)
(r'^admin/workflow/', include('goflow.apptools.urls_admin')),
# special
(r'^admin/apptools/', include('goflow.apptools.urls_admin')),
# Uncomment the next line for... | static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
)
|
thilaire/missionBoard | src/MissionBoard/EventManager.py | Python | gpl-3.0 | 2,031 | 0.031512 | # coding=utf-8
import logging
from MissionBoard.ATBridge import ATBridge
from MissionBoard.State import Init
logger = logging.getLogger()
class EventManager(ATBridge):
"""Main Class to deal with the different loops, queue, state and bridge with the AT tiny"""
def __init__(self, loops, states):
"""Create the ma... | isInitState or func.__class__ in self.state.funcNext:
# we need to check
if self.state.isOver(func):
self.nextState()
def start(self):
"""fct to be overloaded
will be run when everything is ready"""
pass
def run(self):
"""run the loops, the start method and they the (endless) SPI loop"""
# sta... | f.start()
# run the loops (one per thread)
for l in self.functionalities:
l.run()
# and run the SPI loop
self.runSPI()
|
gyoto/Gyoto | python/gyoto/spectrometer.py | Python | gpl-3.0 | 417 | 0.004796 | '''Gyoto::Spectrome | ter namespace
In order to emulate the C++ Gyoto::Spectrometer namespace, this module will
load gyoto.std and gyoto.lorene (if available) and expose all Spectrometers
in here.
'''
import gyoto._namespaces as _namespaces
from gyoto.cor | e import Spectrometer as Generic
__all__ = _namespaces.make_namespace(Generic, globals())
del _namespaces
Complex=ComplexSpectrometer
Uniform=UniformSpectrometer
|
misli/django-verified-email-field | verified_email_field/settings.py | Python | bsd-3-clause | 902 | 0.003326 | import os
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
def _get_setting(name, default):
attr = f'VERIFIED_EMAIL_{name}'
return os.environ.get(attr, getattr(settings, attr, default))
CACHE_PREFIX = _get_setting('CACHE_PREFIX', 'verified_email_field_')
CODE_LENGTH ... | xt')
MAIL_TEMPLATE_HTML = _get_ | setting('MAIL_TEMPLATE_TXT', 'verified_email_field/mail.html')
MAIL_MAILER = _get_setting(
'MAIL_MAILER',
'Django Verified Email Field (https://github.com/misli/django-verified-email-field)',
)
CREATE_USER = bool(_get_setting('CREATE_USER', True))
|
flashbyte/Sudoku | testcases.py | Python | gpl-3.0 | 2,339 | 0.000428 |
#this is a test
sudoku_testcases = [
{
'description': 'this is a test',
| 'testcase': [
[9, 0, 0, 0, 1, 7, 0, 0, 0],
[8, 0, 3, 0, 2, 0, 0, 0, 0],
[7, 0, 0, 0, 3, 5, 0, 0, 0],
[0, 0, 0, 0, 7, 9, 0, 0, 0],
[2, 0, 0, 0, 0, 8, 0, 0, 0],
[0, 8, 9, 5, 0, 0, 7, 2, 3],
[3, 0, 0, 0, 5, 1, 0, 0, 0],
[0... | {
'description': 'this is an easy one',
'testcase': [
[0, 0, 7, 0, 2, 1, 5, 3, 0],
[2, 0, 5, 0, 0, 0, 0, 0, 0],
[8, 4, 1, 7, 0, 0, 6, 0, 0],
[0, 0, 2, 4, 6, 5, 0, 1, 3],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[3, 1, 0, 2, 8, 9, 7, 0, 0],
... |
ad-m/foundation-manager | foundation/teryt/views.py | Python | bsd-3-clause | 1,853 | 0.00054 | from django.views.generic import DetailView
from braces.views import SelectRelatedMixin
from django_filters.views import FilterView
from .models import JST
from .filters import JSTFilter
from foundation.offices.models import Office
from dal import autocomplete
class JSTListView(SelectRelatedMixin, FilterView):
fi... | lete(autocomplete.Select2QuerySetView):
def get_queryset(self):
qs = JST.objects.county().all()
voivodeship = self.forwarded.get( | 'voivodeship', None)
if self.q:
qs = qs.filter(name__istartswith=self.q)
if voivodeship:
return qs.filter(parent=voivodeship)
return qs.none()
class CommunityAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
qs = JST.objects.community... |
hniemeyer/HardSphereSim | EventManager.py | Python | gpl-3.0 | 4,177 | 0.015322 | """
Module defining the Event class which is used to manage collissions and check their validity
"""
from itertools import combinations
from copy import copy
from particle import Particle
class EventParticle(object):
def __init__(self, particle1, particle2):
self.particle1 = particle1
self.pa... | 0.1]), 0.05, 2.0)
b = Particle(np.array([0.4, 0.5]), np.array([-0.1, 0.01]), 0.05, 2.0)
manager = EventManager([a,b])
for i in range(20):
plt.title(a.t)
plt.scatter([a._x[0], b._x[0]], [a._x[1], b._x[1]])
print a._x
print b._x
plt.xlim([0,1 | ])
plt.ylim([0,1])
plt.show()
manager.step()
|
spulec/moto | tests/test_mq/test_server.py | Python | apache-2.0 | 382 | 0 | import json
import sure # noqa # pylint: disable=unused-im | port
from moto import mock_mq
import moto.server as server
@mock_mq
def test_mq_list():
backend = server.create_backend_a | pp("mq")
test_client = backend.test_client()
resp = test_client.get("/v1/brokers")
resp.status_code.should.equal(200)
json.loads(resp.data).should.equal({"brokerSummaries": []})
|
cupy/cupy | cupy/_core/_codeblock.py | Python | mit | 966 | 0 | class CodeBlock:
"""Code fragment for the readable format.
"""
def __init__(self, head, codes):
self._head = '' if head == '' else head + ' '
self._codes = codes
def _to_str_list(self, indent_width=0):
codes = []
codes.append(' ' * indent_width + self._head + '{')
... | return codes
def __str__(self):
"""Emit CUDA pro | gram like the following format.
<<head>> {
<<begin codes>>
...;
<<end codes>>
}
"""
return '\n'.join(self._to_str_list())
|
ChameleonCloud/openstack-nagios-plugins | openstacknagios/nova/Images.py | Python | gpl-3.0 | 2,216 | 0.002256 | # Copyright (C) 2016 Jordan Tardif http://github.com/jordant
# Jordan Tardif <jordan@dreamhost.com>
#
# 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 Lic... | ', metavar='RANGE', default='0:',
help='return warning if repsonse time is outside RANGE (default: 0:, never warn)')
argp.add_argument('-c', '--critical', metavar='RANGE', default='0:',
help='return critical if repsonse time is outside | RANGE (default 1:, never critical)')
args = argp.parse_args()
check = osnag.Check(
NovaImages(args=args),
osnag.ScalarContext('gettime', args.warn, args.critical),
osnag.Summary(show=['gettime'])
)
check.main(verbose=args.verbose, timeout=args.timeout)
if __name__ == '__main... |
wave2future/gdkit | python/sendcrashreport.py | Python | bsd-2-clause | 1,814 | 0.049614 | try:
import sys,re,os,subprocess,smtplib
from optparse import OptionParser
except Exception,e:
exit(100)
options=None
args=None
try:
usage = "usage: sendcrashreport.py -f /Library/Logs/CrashReports/MyFile.crash [-c /tmp/myvile]"
parser=OptionParser(usage=usage)
parser.add_option("-f",dest="file",help="the core d... | .MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
except Exception,e:
sys.stderr.write(e)
exit(0)
try:
corefile=options.file.lstrip().rstrip()
comments=opti | ons.comments
if(comments): comments = comments.lstrip().rstrip()
if not corefile: exit(0)
if not os.path.exists(corefile): exit(0)
if comments and not os.path.exists(comments): comments=False
msg=MIMEMultipart()
msg['From']="gitybot@macendeavor.com"
msg['To']="support@macendeavor.com"
msg['Subject']="GityBot: C... |
akosyakov/intellij-community | python/testData/quickFixes/PyRemoveArgumentQuickFixTest/unexpected_after.py | Python | apache-2.0 | 32 | 0.0625 |
def | foo(a) | :
pass
foo(1)
|
CloudBoltSoftware/cloudbolt-forge | blueprints/google_cloud_function/create.py | Python | apache-2.0 | 9,886 | 0.007688 | from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build
from google.oauth2 import service_account
from common.methods import set_progress
from infrastructure.models import CustomField, Environment
from pathlib import Path
import json, tempfile
import os
import zipf... |
filename=Path(sourcecode).name
if path.startswith(settings.MEDIA_URL):
set_progress("Converting relative URL to filesystem path")
path = path.replace(settings.MEDIA_URL, settings | .MEDIA_ROOT)
path = os.path.join(settings.MEDIA_ROOT, path)
archive=io.BytesIO()
with zipfile.ZipFile(archive, 'w') as zip_archive:
with open(path, 'r') as file:
zip_file = zipfile.ZipInfo(filename)
zip_archive.writestr(zip_file, file.read())
archive.seek(0)
media=Med... |
supermeng/console | apis/specs.py | Python | mit | 15,232 | 0.000525 | # -*- coding: utf-8
import re
import copy
import humanfriendly
import json
import jsonpickle
from lain_sdk.yaml.parser import ProcType, resource_instance_name
from .utils import get_system_volumes_from_etcd
class AppType:
Normal = 'app'
Service = 'service'
Resource = 'resource'
ResourceInstance = 'r... | return \
self.Name != "" and \
self.Namespace != "" and \
self.NumInstances >= 0 and \
isinstance(self.Pod, PodSpec) and \
self.Pod.verify_params()
def equals(self, s):
return \
s.Name == self.Name and \
s.Namespace =... | space and \
s.NumInstances == self.NumInstances and \
s.RestartPolicy == self.RestartPolicy and \
s.Pod.equals(self.Pod)
class AppSpec:
AppName = ''
PodGroups = []
def clone(self):
s = AppSpec()
s.AppName = self.AppName
s.PodGroups = [pg.clone(... |
TheTimmy/spack | var/spack/repos/builtin/packages/xapian-core/package.py | Python | lgpl-2.1 | 1,768 | 0.000566 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | pers to easily
add advan | ced indexing and search facilities to their own applications.
It supports the Probabilistic Information Retrieval model and also
supports a rich set of boolean query operators."""
homepage = "https://xapian.org"
url = "http://oligarchy.co.uk/xapian/1.4.3/xapian-core-1.4.3.tar.xz"
version('1.4... |
pcmoritz/ray-1 | rllib/agents/cql/cql_tf_policy.py | Python | apache-2.0 | 15,256 | 0 | """
TensorFlow policy class used for CQL.
"""
from functools import partial
import numpy as np
import gym
import logging
from typing import Dict, List, Type, Union
import ray
import ray.experimental.tf_utils
from ray.rllib.agents.sac.sac_tf_policy import \
apply_gradients as sac_apply_gradients, \
compute_and_... | (model, policy.dist_class,
| model_out_t, num_actions)
next_actions, next_logp = policy_actions_repeat(model, policy.dist_class,
model_out_tp1, num_actions)
q1_rand = q_values_repeat(model, model_out_t, rand_actions)
q1_curr_actions = q_values_repeat(mod... |
BrotherPhil/django | tests/many_to_one_null/models.py | Python | bsd-3-clause | 885 | 0.00113 | """
Many-to-one relationships that can be null
To define a many-to-one relationship that can have a null | foreign key, use
``ForeignKey()`` with ``null=True`` .
"""
from | django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Reporter(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Article(models.Model):
headline = models... |
enachb/freetel-code | src/wxWidgets-2.9.4/misc/scripts/update_doc_utils.py | Python | lgpl-2.1 | 1,788 | 0.005593 | ##############################################################################
# Name: misc/scripts/update_doc_utils.py
# Purpose: base utilities for others update_doc_*.py scripts
# Created: 2007-08-1
# RCS-ID: $Id$
# Copyright: (c) 2007 Francesco Montorsi
# Licence: wxWindows licence
#############... | ######################
import sys, os, glob, distutils.file_util
DOCS_PATH="../../docs/latex/wx"
# C | alls the given callback with the name of a documented class, its .tex related file,
# the content of that .tex file and the number of the line of the relative \class tag,
# for all documented class in DOCS_PATH. If the callback returns false the processing is stopped.
# Returns the number of .tex files processed.
def s... |
kdart/pycopia3 | core/pycopia/ipv4.py | Python | apache-2.0 | 21,442 | 0.003031 | #!/usr/bin/python3.4
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# 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... | return IPv4 object address as hexadecimal string
"""
__slots__ = ["_address", "_mask"]
def __init__(self, address, mask=None):
# determine input type and convert if necessary
self._address = 0x0; self._mask = None
self.__handleAddress(address)
# handle the optional mask para... | is None:
if mask is None:
if self._address & 0x80000000 == 0:
self._mask = 0xff000000
elif self._address & 0x40000000 == 0:
self._mask = 0xffff0000
else:
self._mask = 0xffffff00
else:
... |
rohitranjan1991/home-assistant | homeassistant/components/homematic/const.py | Python | mit | 6,962 | 0.000144 | """Constants for the homematic component."""
DOMAIN = "homematic"
DISCOVER_SWITCHES = "homematic.switch"
DISCOVER_LIGHTS = "homematic.light"
DISCOVER_SENSORS = "homematic.sensor"
DISCOVER_BINARY_SENSORS = "homematic.binary_sensor"
DISCOVER_COVER = "homematic.cover"
DISCOVER_CLIMATE = "homematic.climate"
DISCOVER_LOCK... | witchLevel",
"ColdWarmDimmer",
"IPWDimmer",
],
DISCOVER_SENSORS: [
| "SwitchPowermeter",
"Motion",
"MotionV2",
"MotionIPV2",
"MotionIPContactSabotage",
"RemoteMotion",
"MotionIP",
"ThermostatWall",
"AreaThermostat",
"RotaryHandleSensor",
"WaterSensor",
"PowermeterGas",
"LuxSensor",
... |
vsajip/django | django/contrib/gis/shortcuts.py | Python | bsd-3-clause | 1,126 | 0.007105 | from io import BytesIO
import zipfile
from django.conf import settings
from django.http import HttpResponse
from django.template import loader
def compress_kml(kml):
"Returns compressed KMZ from the given KML string."
kmz = BytesIO()
zf = zipfile.ZipFile(kmz, 'a', zipfile.ZIP_DEFLATED)
zf.writestr('do... | application/vnd.google-earth.kml+xml')
def render_to_kmz(*args, **kwargs):
"""
Compresses the KML content and returns as KMZ (using the correct
MIME type).
"""
return HttpResponse(compress_kml(loader.render_to_string(*args, **kwargs)),
content_type='application/vnd.google-earth.kmz')
def ... | Response(loader.render_to_string(*args, **kwargs),
content_type='text/plain')
|
bicard/raspberrypi | quad-store-sensors/37in1/knock-rgb-led-smd.py | Python | gpl-3.0 | 1,005 | 0.029851 | import RPi.GPIO as GPIO
KnockPin = 11
LedPin = 12
Led_status = 1
def setup():
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO.setup(LedPin, GPIO.O | UT) # Set LedPin's mode is output
GPIO.setup(KnockPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led
def swLed(ev=None):
global Led_status
Led_sta | tus = not Led_status
GPIO.output(LedPin, Led_status) # switch led status(on-->off; off-->on)
print "LED: " + ("on" if Led_status else "off")
def loop():
GPIO.add_event_detect(KnockPin, GPIO.FALLING, callback=swLed, bouncetime=200) # wait for falling
while True:
pass # Don't do anything
def destroy():
... |
tchellomello/home-assistant | homeassistant/components/http/request_context.py | Python | apache-2.0 | 502 | 0 | """Middleware to set the request context."""
from aiohttp.web import midd | leware
from homeassistant.core import callback
# mypy: allow-untyped-defs
@callback
def setup_request_context(app, context):
"""Create request context middleware for the app."""
@middleware
async def request_context_middleware(request, handler):
"""Request context middleware."""
context... |
app.middlewares.append(request_context_middleware)
|
RamZallan/conditional | conditional/blueprints/intro_evals.py | Python | mit | 6,796 | 0.001324 | from datetime import datetime
import structlog
from flask import Blueprint, request
from conditional.util.ldap import ldap_get_intro_members
from conditional.models.models import FreshmanCommitteeAttendance
from conditional.models.models import CommitteeMeeting
from conditional.models.models import FreshmanAccount
... | for m in HouseMeeting.query.filter(
HouseMeeting.id.in_(h_meetings)
)
],
'technical_seminars':
[s.name for s in TechnicalSeminar.query.filter(
TechnicalSeminar.id.in_(
[a.semina... | ry.filter(
FreshmanSeminarAttendance.fid == fid.id)
if TechnicalSeminar.query.filter(TechnicalSeminar.id == a.seminar_id).first().approved]
))
],
'social_events': '',
'freshman_project': "Pending",
... |
codinuum/cca | src/ast/analyzing/langs/java/parsing/src/genclasstbl.py | Python | apache-2.0 | 3,392 | 0.004717 | #!/usr/bin/en | v python3
#
# Copyright 2012-2020 Codinuum Software Lab <https://codinuum.com>
#
# 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
#
#... | R CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
import sys
import subprocess
output_file_name = 'classtbl.ml'
classpath_tbl = {
'linux' : [ '/usr/lib/jvm/java-8-openjdk-amd64/jre/lib',
... |
bigswitch/nova | nova/tests/functional/api_sample_tests/test_availability_zone.py | Python | apache-2.0 | 1,634 | 0 | # Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | va.conf
from nova.tests.functional.api_sample_tests import test_servers
CONF = nova.conf.CONF
class AvailabilityZoneJsonTest(test_servers.ServersSampleBase):
ADMIN_API = True
extension_name = "os-availability-zone"
def _get_flags(self):
f = super(AvailabilityZoneJsonTest, self)._get_flags()
... | '] = CONF.osapi_compute_extension[:]
f['osapi_compute_extension'].append(
'nova.api.openstack.compute.contrib.availability_zone.'
'Availability_zone')
return f
def test_availability_zone_list(self):
response = self._do_get('os-availability-zone')
self._verify... |
jgoclawski/django-facebook-auth | facebook_auth/management/commands/debug_user_tokens.py | Python | mit | 433 | 0 | from django.core.management.base import BaseCommand
from facebook_auth import model | s
class Command(BaseCommand):
def handle(self, *args, **options):
users = (models.UserTo | ken.objects.distinct('provider_user_id')
.values_list('provider_user_id', flat=True))
for user in users:
models.debug_all_tokens_for_user.delay(user)
self.stdout.write('Debugging user "%s"' % user)
|
garaud/puppetmaster | test/network_test.py | Python | gpl-2.0 | 8,973 | 0.00078 | # Copyright (C) 2008-2010 INRIA - EDF R&D
# Author: Damien Garaud
#
# This file is part of the PuppetMaster project. It checks the module
# 'network'.
#
# This script is free; you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation; eit... | f.assertTrue(isinstance(status, int))
self.assertTrue(isinstance(statusout, tuple))
self.assertTrue(isinstance(statusout[0], int))
self.assertTrue(isinstance(wait_return, tuple))
# The status must be '0'.
| self.assertTrue(status == 0)
self.assertTrue(statusout[0] == 0)
self.assertTrue(popen4_instance.wait() == 0)
self.assertTrue(subproc.wait() == 0)
self.assertTrue(wait_return[0] == 0)
# For a random host.
if self.is_file:
index = random.randint(0, self.net.Ge... |
viranch/exodus | resources/lib/sources/ymovies.py | Python | gpl-3.0 | 8,937 | 0.012085 | # -*- coding: utf-8 -*-
'''
Exodus Add-on
Copyright (C) 2016 Exodus
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 l... |
r = [(i[0], i[1][0][0], i[1][0][1]) for i in r if i[1]]
r = [i[0] for i in r if t == cleantitle.get(i[1]) and season == '%01d' % int(i[2])][:2]
r = [(i, re.findall('(\d+)', i)[-1]) for i in r]
| for i in r:
try:
y, q = cache.get(self.ymovies_info, 9000, i[1])
if not y == year: raise Exception()
return urlparse.urlparse(i[0]).path + '?episode=%01d' % int(episode)
except:
pass
except:... |
FRC4080Turner/Python-Sprocket_Center_Calculator | src/Sprocket_Center_Calculator-v2/prompts.py | Python | mit | 964 | 0 | # prompts
def ansiOrPitch():
text = 'Are you using the ANSI trade # or the decimal pitch?'
return text
def setAnsi():
text = 'Type the 2 or 3 digit ANSI trade number.'
return text
def setPitch():
text = 'Type the decimal pitch of your chain.'
return text
def setSprocket1():
text = 'T... | return text
def invalidAnsiNumber():
text = 'The givein value is not an ANSI standard roller chain size.'
return text
def sprocketsTooClose():
text = 'The sp | rockets are too close together.'
return text
|
V11/volcano | server/sqlmap/plugins/dbms/mssqlserver/__init__.py | Python | mit | 1,081 | 0.000925 | #!/usr/bin/env python
"""
Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
from lib.core.enums import DBMS
from lib.core. | settings import MSSQL_SYSTEM_DBS
from lib.core.unescaper import unescaper
from plugins.dbms.mssqlserver.enumeration import Enumeration
from plugins.dbms.mssqlserver.filesystem import Filesystem
from plugins.dbms.mssqlserver.fingerprint import Fingerprint
from plugins.dbms.mssqlserver.syntax import Syntax
from plugins.d... | rint, Enumeration, Filesystem, Miscellaneous, Takeover):
"""
This class defines Microsoft SQL Server methods
"""
def __init__(self):
self.excludeDbsList = MSSQL_SYSTEM_DBS
Syntax.__init__(self)
Fingerprint.__init__(self)
Enumeration.__init__(self)
Filesystem.__i... |
vbsteja/code | Python/Data Science/titanic kaggle/predict_survival.py | Python | apache-2.0 | 1,018 | 0.024558 | #import the required libraries
import pandas as pd
import numpy as np
import os
print(os.getcwd())
df = pd.read_csv("train.csv")
#read the data into a DataFrame
#update the categorial values of Sex into binary values
df.loc[df['Sex'] == 'female','Sex'] = 0
df.loc[df['Sex'] == 'male','Sex'] = 1
df.Embarked.fillna(0)
... | axis=1)
df = df.drop('Ticket',axis = 1)
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
scaler = MinMaxScaler()
X_train,X_test,Y_train,T_test = train_test_split(df,df_label | ,test_size = 0.10)
#print(df.loc[df['Embarked'] == pd.NaT])
print(df.Embarked.unique())
print(df.Pclass.unique())
print(X_train)
print(X_test)
print(Y_train)
print(df.columns.values)
#print(df.describe())
|
pauleveritt/pycharm_polyglot | src/modules/app.py | Python | mit | 49 | 0.020408 | fro | m lib import incrementer
pri | nt(incrementer(2)) |
mikf/gallery-dl | test/test_cookies.py | Python | gpl-2.0 | 7,492 | 0.000801 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2017-2022 Mike Fährmann
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
import os
import sys
import unittest
from unittes... | t:").session.cookies
self.assertEqual(len(cookies), 0)
self.assertEqual(mock_warning.call_count, 1)
self.assertEqual(mock_warning.call_args[0][0], "cookies: %s")
| self.assertIsInstance(mock_warning.call_args[0][1], exc)
class TestCookiedict(unittest.TestCase):
def setUp(self):
self.cdict = {"NAME1": "VALUE1", "NAME2": "VALUE2"}
config.set((), "cookies", self.cdict)
def tearDown(self):
config.clear()
def test_dict(self):
cookies ... |
rohitranjan1991/home-assistant | tests/components/pvoutput/test_init.py | Python | mit | 2,660 | 0.000376 | """Tests for the PVOutput integration."""
from unittest.mock import MagicMock
from pvo import (
PVOutputAuthenticationError,
PVOutputConnectionError,
PVOutputNoDataError,
)
import pytest
from homeassistant.components.pvoutput.const import DOMAIN
from homeassistant.config_entries import SOURCE_REAUTH, Conf... |
await hass.config_entrie | s.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
flow = flows[0]
assert flow.get("step_id") == "reauth_confirm"
assert flow.g... |
Grumbel/dirtool | experiments/udisks/udisks.py | Python | gpl-3.0 | 3,662 | 0.002185 | #!/usr/bin/env python3
import dbus
import xml
import xml.dom.minidom
import xml.etree.ElementTree as ET
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib
DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
ud_manager_obj = bus.get_object("org.freedesktop.UDisks2", "/org/freedesktop/... | .decode())
print()
except Exception as err:
pass # print(err)
if False:
ud_manager = dbus.Interface(ud_manager_obj, 'org.freedesktop.DBus.ObjectManager')
for dev in ud_manager.GetManagedObjects():
print(dev)
device_obj = bus.get_object("org.freedesktop.UDisks2", dev)
| device_intro = dbus.Interface(device_obj, "org.freedesktop.DBus.Introspectable")
xml_text = device_intro.Introspect()
root = ET.fromstring(xml_text)
dom = xml.dom.minidom.parseString(xml_text)
# dom.documentElement.findall("node")
device_props = dbus.Interface(device_o... |
asolntsev/selenium | py/selenium/webdriver/common/action_chains.py | Python | apache-2.0 | 12,537 | 0.000479 | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | :Args:
| - on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element:
self.move_to_element(on_element)
if self._driver.w3c:
self.w3c_actions.pointer_action.click()
self.w3c_actions.key_action.pause()
sel... |
joezuntz/emcee | src/emcee/moves/de.py | Python | mit | 1,581 | 0 | # -*- coding: utf-8 -*-
import numpy as np
from .red_blue import RedBlueMove
__all__ = ["DEMove"]
class DEMove(RedBlueMove):
r"""A proposal using differential evolution.
This `Differential evolution proposal
<http://www.stat.columbia.edu/~gelman/stuff_for_blog/cajo.pdf>`_ is
implemented following ... | Args:
sigma (float): The standard deviation of the Gaussian used to stretch
the proposal vector.
gamma0 (Optional[float]): The mean stretch factor for the proposal
vector. By default, it is :math:`2.38 / \sqrt{2\,\mathrm{ndim}}`
as recommended by the two | references.
"""
def __init__(self, sigma=1.0e-5, gamma0=None, **kwargs):
self.sigma = sigma
self.gamma0 = gamma0
kwargs["nsplits"] = 3
super(DEMove, self).__init__(**kwargs)
def setup(self, coords):
self.g0 = self.gamma0
if self.g0 is None:
# P... |
cupy/cupy | cupyx/scipy/fft/__init__.py | Python | mit | 591 | 0 | # flake8: NOQA
from cupyx.scipy.fft._fft import (
fft, ifft, fft2, ifft2, fftn, ifftn,
rfft, irfft, rfft2, irfft2, rfftn, irfftn,
hfft, ihfft, hfft2, ihfft2, hfftn, ihfftn
)
from cupyx.scipy.fft._fft import (
__ua_domain__, __ua_convert__, __ua_function__)
from cupyx.scipy.fft._fft import _scipy_150, _s... | _len # NOQA
from cupy.fft import ffts | hift, ifftshift, fftfreq, rfftfreq
from cupyx.scipy.fftpack import get_fft_plan
from cupyx.scipy.fft._realtransforms import (
dct, dctn, dst, dstn, idct, idctn, idst, idstn
)
|
sggottlieb/cmfieldguide | cmfieldguide/cmsdetector/signatures/opentext.py | Python | unlicense | 2,215 | 0.013544 | """
This signature contains test to see if the site is running on OpenText Web Site Management.
"""
__author__ = "Steven Brent"
__copyright__ = "CM Fieldguide"
__credits__ = ["Steven Brent","Markus Giesen"]
__license__ = "Unlicense"
__version__ = "0.1"
__maintainer__ = "Steven Brent"
__email__ = "scbrent@gmail.com"
__s... | ement (formerly RedDot / RedDot Solutions) will contain this
"""
return 1
elif site.home_page.contains_pattern("<!--\sPageID\s\d{1,6}\s-\spublished by Open Text Web Solutions"):
"""
*Some* sites running version 9.x to 10.x of OpenText Web Site Management will cont... | Sites running version 11.x of OpenText Web Site Management will contain this
"""
return 1
else:
return 0
def test_has_rde_tag(self, site):
"""
RedDot components sometime embed special rde tags.
"""
if site.home_page.contain... |
matthewfranglen/postgres-elasticsearch-fdw | tests/start.py | Python | mit | 738 | 0.001355 | #!/usr/bin/env python
# pylint: disable=line-too-long
""" Start the containers """
import argparse
from lib.docker_compose_tools import set_up
def main():
""" Start the containers """
parser = argparse.ArgumentParser(description="Set up testing environment.")
parser.add_argument("--pg", help="Postgr | eSQL version")
parser.add_argument("--es", help="Elasticsearch version")
args = parser.parse_args()
pg_version = args.pg
es_version = args.es
print(
"S | tarting environment with PostgreSQL {pg_version} with Elasticsearch {es_version}...".format(
pg_version=pg_version, es_version=es_version
)
)
set_up(pg_version, es_version)
if __name__ == "__main__":
main()
|
kecheon/yablist | bidders/migrations/0003_bidder_address.py | Python | mit | 407 | 0 | # -*- coding: utf-8 - | *-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migrati | on):
dependencies = [
('bidders', '0002_bidder_photo'),
]
operations = [
migrations.AddField(
model_name='bidder',
name='address',
field=models.CharField(max_length=200, null=True),
),
]
|
obriencj/python-javatools | tests/distinfo.py | Python | lgpl-3.0 | 1,430 | 0 | # This library is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be usefu... | self):
self.assertEqual(0, main(["argv0", "--jar-classes", self.dist]))
# distinfo-specific option is accepted:
de | f test_distinfo_options(self):
self.assertEqual(0, main(["argv0", "--dist-provides", self.dist]))
|
buaabyl/pycurl-win32 | tests/xferinfo_cb_test.py | Python | lgpl-2.1 | 2,113 | 0.000473 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vi:ts=4:et
import unittest
import pycurl
from . import util
from . import appmanager
setup_module, teardown_module = appmanager.setup(('app', 8380))
class XferinfoCbTest(unittest.TestCase):
def setUp(self):
self.curl = pycurl.Curl()
self.curl.seto... | self.curl.setopt(pycurl.NOPROGRESS, False)
try:
self.curl.perform()
self.fail('should | have raised')
except pycurl.error as e:
assert e.args[0] in [pycurl.E_ABORTED_BY_CALLBACK], \
'Unexpected pycurl error code %s' % e.args[0]
assert called['called']
|
ktan2020/legacy-automation | tools/fetch.py | Python | mit | 2,850 | 0.021754 | import ConfigParser
from optparse import OptionParser
import subprocess, sys, os
if sys.platform == "win32":
import shutil
shutil.rmtree(os.path.join(os.getenv('APPDATA'),'Subversion','auth'), True)
cwd = os.getcwd()
def vararg_cb(option, opt_str, value, parser):
assert va... | hell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
map(lambda x: sys.stdout.write(x), iter(p.stdout.readline,""))
rc = p.wait()
if rc != 0: sys.stderr.write(" !!!! WARN: svn_export failed for [%s] !!!!\n" % c)
os.chdir(os.path.join(cwd,s))
p = ... | s.STDOUT)
map(lambda x: sys.stdout.write(x), iter(p.stdout.readline,""))
rc = p.wait()
os.chdir(cwd)
if rc != 0: sys.stderr.write(" !!!! WARN: rally failed for [%s] !!!!\n" % c)
else:
for c in options.comp:
assert c in l, "Specified option %s not in Config... |
Hao-Liu/avocado | selftests/functional/test_sysinfo.py | Python | gpl-2.0 | 2,399 | 0.003335 | import os
import sys
import shutil
import tempfile
if sys.version_info[:2] == (2, 6):
import unittest2 as unittest
else:
import unittest
from avocado.utils import process
basedir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..')
basedir = os.path.abspath(basedir)
class SysInfoTest(uni... | --job-results-dir %s --sysinfo=on passtest' % self.tmpdir
result | = process.run(cmd_line)
expected_rc = 0
self.assertEqual(result.exit_status, expected_rc,
'Avocado did not return rc %d:\n%s' % (expected_rc, result))
output = result.stdout + result.stderr
for line in output.splitlines():
if 'JOB LOG' in line:
... |
gustavoam/django-messages | tests/manage.py | Python | bsd-3-clause | 472 | 0 | #!/usr/bin/env python
import os
import sys
from django import VERSION
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.path.pardir))
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
if VERSION < (1, 6):
test_runners_args = {
'TEST_RUNNER'... | }
from django.core.manage | ment import execute_from_command_line
execute_from_command_line(sys.argv)
|
ztuowen/chill-dev | Manual/tests/test_permute.py | Python | gpl-3.0 | 155 | 0.019355 | from chill import *
source('mm.c')
procedure('mm')
#format: rose
loop(0)
known('a | mbn > 0')
known('an > 0')
kn | own('bm > 0')
permute([3,1,2])
print_code()
|
gilt/incubator-airflow | airflow/contrib/operators/datastore_export_operator.py | Python | apache-2.0 | 4,628 | 0.002593 | # -*- 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, software
... | ified Cloud Storage bucket
to backup data. If this namespace does not exist in GCS, it will be created.
:type namespace: str
:param datastore_conn_id: the n | ame of the Datastore connection id to use
:type datastore_conn_id: string
:param cloud_storage_conn_id: the name of the cloud storage connection id to force-write
backup
:type cloud_storage_conn_id: string
:param delegate_to: The account to impersonate, if any.
For this to work, the serv... |
stevenmizuno/QGIS | python/plugins/processing/algs/grass7/ext/r_horizon.py | Python | gpl-2.0 | 2,298 | 0.001745 | # -*- coding: utf-8 -*-
"""
********** | *****************************************************************
r_horizon.py
------------
Date : September 2017
Copyright : (C) 2017 by Médéric Ribreux
Email : medspx at medspx dot fr
************************************************************************... | *
* 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. ... |
brain-tec/l10n-switzerland | l10n_ch_zip/hooks.py | Python | agpl-3.0 | 506 | 0 | # Copyright 2019 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl)
from odoo.tools import convert_file
def import_csv_data(cr, registry):
"""Imp | ort CSV data as it is faster than xml and because we can't use
| noupdate anymore with csv"""
filenames = ['data/res.better.zip.csv']
for filename in filenames:
convert_file(
cr, 'l10n_ch_zip',
filename, None, mode='init', noupdate=True,
kind='init', report=None,
)
|
gauravbose/digital-menu | digimenu2/restaurant/migrations/0005_auto_20150629_1201.py | Python | bsd-3-clause | 603 | 0.001658 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import mode | ls, migrations
class Migration(migrations.Migration):
dependencies = [
('restaurant', '0004_menu_image_path'),
]
operations = [
migrations.RemoveField(
model_name='cart',
name='cart_id',
),
migrations.AddField(
model_name='cart',
... | ialize=False, verbose_name='ID'),
preserve_default=False,
),
]
|
minghuascode/pyj | pyjs/jsonrpc/mongrel2/__init__.py | Python | apache-2.0 | 1,193 | 0.002515 | """
Copyright (c) 2006 Jan-Klaas Kollhof
This file is part of jsonrpc.
jsonrpc is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later ... | ce, Suite 330, Boston, MA 02111-1307 USA
"""
from pyjs.jsonrpc import JSONRPCServiceBase, jsonremote
class Mongrel2JSONRPCService(JSONRPCServiceBase):
def __init__(self, conn):
self.__conn = conn
JSONRPCServiceBase.__init__(self)
def __call__(self):
print "call"
req = self.... | int req
response = self.process(req.body)
self.__conn.reply_http(req, response)
|
Die-Turtles/application | taskCards/models.py | Python | gpl-2.0 | 3,381 | 0.044366 | from django.db import models
from django.contrib.auth import models as auth
import datetime
from application import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
typeChoices = (
('task', 'Task'),
('userStory', 'User Story'),
)
statusChoices = (
('toDo', 'To do')... | ate | goryChoices = (
('frontend', 'Frontend'),
('backend', 'Backend'),
('design', 'Design'),
)
purposeChoices = (
('bugfix', 'Bugfix'),
('feature', 'Feature'),
)
class WorkGroup(models.Model):
name = models.CharField(
max_length=200,
unique = True,
)
def __unicode__(self):
return u'%s' % (self.name)
c... |
Dubrzr/golb | articles/urls.py | Python | mit | 774 | 0.002584 | from django.conf.urls import url
from articles import views
urlpatterns = [
url(r'^$', views.list_all, name='articles'),
url(r'^(?P<id>[0-9]+)/$', views.article, name='article'),
url(r'^admin/$', views.adm | in, name='admin_articles'),
url(r'^add/$', views.add, name='add_article'),
url(r'^delete/$', views.delete, name='del_article'),
url(r'^file-upload/$', views.upload_file, name='upload_file'),
url(r'^edit/(?P<id>[0-9]+)/$', views.edit, name='edit_article') | ,
url(r'^edit/(?P<id>[0-9]+)/(?P<history_id>[0-9]+)/$', views.edit, name='edit_article'),
url(r'^history/(?P<id>[0-9]+)/$', views.history, name='history_article'),
url(r'^update_state/(?P<id>[0-9]+)/(?P<state>[A-Z]+)/$', views.update_state, name='update_state_article'),
]
|
rusenask/stubo-app | stubo/service/run_stubo.py | Python | gpl-3.0 | 6,663 | 0.001801 | # -*- coding: utf-8 -*-
"""
:copyright: (c) 2015 by OpenCredo.
:license: GPLv3, see LICENSE for more details.
"""
import logging
import time
import sys
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import socket
import tornado.web, tornado.ioloop, tornado.httpserver
from tornado.util... | cfg
def get_cluster_name(self):
name = 'unknown'
try:
with open(r'/opt/stubo_ng/etc/cluster_name.txt') as f:
name = f.read().strip()
except Exception, e:
| log.warn(e)
return name
def get_app(self):
hooks_cls = self.cfg.get('hooks_cls',
'stubo.ext.transformer.StuboDefaultHooks')
self.cfg['hooks'] = resolve_class(hooks_cls)
tornado_app = tornado.web.Application(
static_path=static_path(),
... |
gabyx/RIBMosaic | render_ribmosaic/setup.py | Python | gpl-3.0 | 2,423 | 0.002476 | # #############################################################################
# AUTHOR BLOCK:
# #############################################################################
#
# RIB Mosaic RenderMan(R) IDE, see <http://sourceforge.net/projects/ribmosaic>
# by Eric Nathen Back aka WHiTeRaBBiT, 01-24-2010
# This script... | ####
# END BLOCKS
# ################################# | ############################################
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(name="ribify", version="0.0",
ext_modules = [Extension("ribify", ["rm_ribify.py"])])
|
LukeM12/samba | buildtools/wafsamba/wafsamba.py | Python | gpl-3.0 | 32,000 | 0.0105 | # a waf tool to add autoconf-like macros to the configure section
# and for SAMBA_ macros for building libraries, binaries etc
import Build, os, sys, Options, Task, Utils, cc, TaskGen, fnmatch, re, shutil, Logs, Constants
from Configure import conf
from Logs import debug
from samba_utils import SUBST_VARS_RECURSIVE
Ta... | v.HAVE_LD_VERSION_SCRIPT:
if private_library:
version = "%s_%s" % (Utils.g_module.APPNAME, Utils.g_module.VERSION)
elif vnum:
| version = "%s_%s" % (lib |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.