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 |
|---|---|---|---|---|---|---|---|---|
renegelinas/mi-instrument | mi/dataset/parser/test/test_ctdav_nbosi_auv.py | Python | bsd-2-clause | 1,901 | 0.002104 | #!/usr/bin/env python
"""
@package mi.dataset.parser.test
@fid mi-instrument/mi/dataset/parser/test/test_ctdav_nbosi_auv.py
@author Rene Gelinas
@brief Test code for a ctdav_nbosi_auv data parser
"""
import os
from nose.plugins.attrib import attr
from mi.core.log import get_logger
from mi.dataset.driver.ctdav_nbosi... | Assert the expected number of particles | is captured and there are no exceptions
"""
stream_handle = open(os.path.join(RESOURCE_PATH, 'CP05MOAS-A6264_AUVsubset.csv'), 'rU')
parser = CtdavNbosiAuvParser(stream_handle,
self.exception_callback)
particles = parser.get_records(10000)
se... |
uni2u/neutron | neutron/plugins/bigswitch/plugin.py | Python | apache-2.0 | 39,750 | 0.000126 | # Copyright 2012 Big Switch Networks, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | pconst.L3_ROUTER_NAT)
def _get_all_data(self, get_ports=True, get_floating_ips=True,
get_routers=True):
admin_context = qcontext.get_admin_context()
networks = []
# this method is used by the ML2 driver so it can't directly invoke
# the self.get_(ports... | s = plugin.get_networks(admin_context) or []
for net in all_networks:
mapped_network = self._get_mapped_network_with_subnets(net)
flips_n_ports = mapped_network
if get_floating_ips:
flips_n_ports = self._get_network_with_floatingips(
mapped... |
schriftgestalt/drawbot | tests/testExport.py | Python | bsd-2-clause | 12,252 | 0.002285 | from __future__ import print_function, division, absolute_import
from fontTools.misc.py23 import *
import sys
import os
import unittest
import glob
import drawBot
import random
import AppKit
from drawBot.context.tools.gifTools import gifFrameCount
from drawBot.misc import DrawBotError
from testSupport import StdOutCol... | e)
def test_imageJPEGProgressive(self):
self.makeTestDrawing()
defaultSize = self._saveImageAndReturnSize(".jpg")
progressiveSize = self._saveImageAndReturnSize(".jpg", imageJPEGProgressive=True)
self.assertGreater(defaultSize, progressiveSize)
def test_imageJP | EGCompressionFactor(self):
self.makeTestDrawing()
lowCompressionSize = self._saveImageAndReturnSize(".jpg", imageJPEGCompressionFactor=1.0)
mediumCompressionSize = self._saveImageAndReturnSize(".jpg", imageJPEGCompressionFactor=0.5)
highCompressionSize = self._saveImageAndReturnSize(".jp... |
vicky2135/lucious | src/oscar/apps/catalogue/abstract_models.py | Python | bsd-3-clause | 41,477 | 0.000072 | import logging
import os
from datetime import date, datetime
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.contrib.staticfiles.finders import find
from django.core.cache import cache
from django.c... | def generate_slug(self):
"""
Generates a slug for a category. This makes no attempt at generating
a unique slug.
"""
return slugify(self.name)
def ensure_slug_uniqueness(self):
"""
Ensures that the category's slug is unique amongst it's siblings.
... | iblings().exclude(pk=self.pk)
next_num = 2
while siblings.filter(slug=unique_slug).exists():
unique_slug = '{slug}_{end}'.format(slug=self.slug, end=next_num)
next_num += 1
if unique_slug != self.slug:
self.slug = unique_slug
self.save()
def ... |
martinb07/mysmarthome | plugins/sonos/__init__.py | Python | gpl-3.0 | 30,168 | 0.001392 | #!/usr/bin/env python3
# vim: set encoding=utf-8 tabstop=4 softtabstop=4 shiftwidth=4 expandtab
# ########################################################################
# Copyright 2013 KNX-User-Forum e.V. http://knx-user-forum.de/
#########################################################################
# This file ... | an_ip)
if self._broker_url:
logger.warning("No broker url given, assuming current ip and default broker port: {url}".
format(url=self._broker_url))
| else:
logger.error("Could not detect broker url !!!")
return
# normalize broker url
if not self._broker_url.startswith('http://'):
self._broker_url = "http://{url}".format(url=self._broker_url)
# ini vars
self._listen_host = liste... |
linuxsoftware/dominoes | davezdominoes/gamecoordinator/security.py | Python | agpl-3.0 | 5,040 | 0.002183 | # ------------------------------------------------------------------------------
# Security Central
# ------------------------------------------------------------------------------
from .models import User
from pyramid.security import Allow, Everyone, Authenticated, ALL_PERMISSIONS
from pyramid.authentication import Se... |
"""The root security domain"""
__acl__ = [(Allow, Everyone, ()),
(Allow, Authen | ticated, ('view', 'edit', 'play')),
(Allow, 'role:admin', ALL_PERMISSIONS) ]
def __init__(self, request):
pass
class UserSettings(object):
"""The security domain for user settings"""
def __init__(self, request):
self.request = request
@property
def __acl__(sel... |
rebeccamorgan/easyskim | nat_proc/FrequencySummarizer.py | Python | apache-2.0 | 2,032 | 0.015256 | from nltk.tokenize import sent_tokenize,word_tokenize
from nltk.corpus import stopwords
from collections import defaultdict
from string import punctuation
from heapq import nlargest
import re
"""
Modified from http://glowingpython.blogspot.co.uk/2014/09/text-summarization-with-nltk.html
"""
class FrequencySummarizer... | y count words of length>4 as significant
ranking[i] += self._freq[w]
sentsindx = self._rank(ranking, n)
return [sents[j].encode('ascii', errors='backslashreplace') for j in sentsindx]
def _rank(self, ranking, n):
""" return the first n sentences with highest ranking """
return nlargest... | key=ranking.get)
|
xyuanmu/XX-Net | python3.8.2/Lib/site-packages/cffi/vengine_cpy.py | Python | bsd-2-clause | 43,314 | 0.00067 | #
# DEPRECATED: implementation for ffi.verify()
#
import sys, imp
from . import model
from .error import VerificationError
class VCPythonEngine(object):
_class_key = 'x'
_gen_python_module = True
def __init__(self, verifier):
self.verifier = verifier
self.ffi = verifier.ffi
self._... | dir + list(self.__dict__)
library = FFILibrary()
if module._cffi_setup(lst, VerificationError, library):
| import warnings
warnings.warn("reimporting %r might overwrite older definitions"
% (self.verifier.get_module_name()))
#
# finally, call the loaded_cpy_xxx() functions. This will perform
# the final adjustments, like copying the Python->C wrapper
... |
Udayraj123/dashboard_IITG | Binder/discussions/migrations/0001_initial.py | Python | mit | 904 | 0.002212 | # -*- coding: utf-8 -*-
# Generated by Django 1.10a1 on 2016-06-19 04:22
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 = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
opera | tions = [
migrations.CreateModel(
name='post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('timestamp', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeFi... |
home-assistant/home-assistant | homeassistant/components/repetier/sensor.py | Python | apache-2.0 | 5,911 | 0.000677 | """Support for monitoring Repetier Server Sensors."""
from datetime import datetime
import logging
import time
from homeassistant.components.sensor import SensorDeviceClass, SensorEntity
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from . import REPETIE... | remaining_secs)),
)
class RepetierJobStartSensor(RepetierSensor):
"""Class to create and populate a Repetier Job Start timestamp Sensor."""
_attr_device_class = SensorDeviceClass.TIMEST | AMP
def update(self):
"""Update the sensor."""
if (data := self._get_data()) is None:
return
job_name = data["job_name"]
start = data["start"]
from_start = data["from_start"]
self._state = datetime.utcfromtimestamp(start)
elapsed_secs = int(round(... |
vinaymayar/python-game-workshop | lesson4/exercises.py | Python | mit | 6,887 | 0.001307 | # lesson4/exercises.py
# Control flow and conditionals
#
# This file contains exercises about Python conditionals.
# Last lesson, we encountered the boolean type.
# Python uses booleans to evaluate conditions.
# Last time, we directly assigned boolean values True and False, but booleans are
# also returned by compari... | ter :)")
elif age < 18:
print("You are underage, and | you're not Maria! Sorry.")
how_many_potatoes = 4
if how_many_potatoes > 20:
print("lots of potatoes")
elif how_many_potatoes > 5:
print("some potatoes, but not more than 20!")
elif how_many_potatoes > 10:
print("the program will never get here " + \
"because the previous case will be " + \
... |
evereux/flicket | setup.py | Python | mit | 10,056 | 0.002088 | #! usr/bin/python3
# -*- coding: utf8 -*-
import datetime
from getpass import getpass
from flask_script import Command
from scripts.create_json import WriteConfigJson
from application import db, app
from application.flicket_admin.models.flicket_config import FlicketConfig
from application.flicket.models.flicket_mode... | pen', 'Closed', 'In Work', 'Awaiting Information']
for s in sl:
status = FlicketStatus.query.filter_by(status=s).first()
if not status:
add_status = Flic | ketStatus(status=s)
db.session.add(add_status)
if not silent:
print('Added status level {}'.format(s))
@staticmethod
def create_default_priority_levels(silent=False):
""" set up default priority levels """
pl = ['low', 'medium', 'high']
... |
QingChenmsft/azure-cli | src/azure-cli/setup.py | Python | mit | 3,406 | 0.000587 | #!/usr/bin/env python
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# ---------------------------------------------... | Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'License :: OSI Approved :: MIT License',... | zure-cli-cloud',
'azure-cli-cognitiveservices',
'azure-cli-component',
'azure-cli-container',
'azure-cli-configure',
'azure-cli-consumption',
'azure-cli-core',
'azure-cli-cosmosdb',
'azure-cli-dla',
'azure-cli-dls',
'azure-cli-eventgrid',
'azure-cli-extension',
'azure-cli... |
brenton/cobbler | cobbler/collection.py | Python | gpl-2.0 | 13,191 | 0.010992 | """
Base class for any serializable list of things...
Copyright 2006, Red Hat, Inc
Michael DeHaan <mdehaan@redhat.com>
This software may be freely redistributed under the terms of the GNU
general public license.
You should have received a copy of the GNU General Public License
along with this program; if not, write ... | t glob
import sub_process
import action_litesync
import item_system
import item_profile
import item_distro
impor | t item_repo
import item_image
from utils import _
class Collection(serializable.Serializable):
def __init__(self,config):
"""
Constructor.
"""
self.config = config
self.clear()
self.api = self.config.api
self.log_func = self.api.log
self.lite_sync =... |
krajj7/spectrogram | viewer/ui_viewer.py | Python | gpl-2.0 | 6,982 | 0.007734 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './viewer.ui'
#
# Created: Sun Aug 23 04:04:27 2009
# by: PyQt4 UI code generator 4.4.2
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_MainWindow(object):
def setupUi(self, MainWin... | ralwidget)
self.progress.setProperty("value",QtCore.QVariant(0))
self.progress.setTextVisible(False)
| self.progress.setObjectName("progress")
self.verticalLayout.addWidget(self.progress)
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.commandCheck = QtGui.QCheckBox(self.centralwidget)
self.commandCheck.setObjec... |
cigroup-ol/metaopt | metaopt/concurrent/worker/util/import_function.py | Python | bsd-3-clause | 654 | 0.001529 | # -*- coding: utf-8 -*-
"""
Utility that imports a function.
"""
# Future
from __future__ import absolute_import, division, print_function, \
unicode_litera | ls, with_statement
def import_function(function):
"""Import | s function given by qualified package name"""
function = __import__(function, globals(), locals(), ['function'], 0).f
# function = getattr(__import__(function["module"], globals(), locals(), ['function'], 0), function["name"]) TODO
# Note that the following is equivalent:
# from MyPackage.MyModule ... |
pythonprobr/notmagic | pt-br/baralho_mut.py | Python | mit | 4,149 | 0.004097 | #!/usr/bin/env python3
"""
>>> baralho = Baralho()
>>> len(baralho)
52
>>> baralho[0]
Carta(valor='2', naipe='paus')
>>> baralho[-1]
Carta(valor='A', naipe='espadas')
>>> from random import choice
>>> choice(baralho) #doctest:+SKIP
Carta(valor='4', naipe='paus')
... | color naipes: ouros (lowest), followed by paus, copas, and espadas (highest).
>>> hand = [Carta(valor='2', naipe='ouros'), Carta(valor='2', naipe='paus'),
... Carta(valor='3', naipe='ouros'), Carta(valor='3', naipe='paus'),
... Carta(valor='A', naipe='espadas')]
>>> [cores_alternadas(ca... | arta(valor='K', naipe='ouros'),
... Carta(valor='A', naipe='ouros')]
>>> for carta in sorted(hand,key=cores_alternadas):
... print(carta)
Carta(valor='K', naipe='ouros')
Carta(valor='A', naipe='ouros')
Carta(valor='A', naipe='espadas')
>>> for carta in sorted(baralho, key=cores_... |
sathnaga/virt-test | qemu/tests/floppy.py | Python | gpl-2.0 | 18,545 | 0.001887 | import logging, time, os, sys, re
from autotest.client.shared import error
from autotest.client import utils
from autotest.client.shared.syncdata import SyncData
from virttest import data_dir, env_process, utils_test, aexpect
@error.context_aware
def run_floppy(test, params, env):
"""
Test virtual floppy of g... | md5_dest = None
self.session.cmd("%s %s %s" % (params["diff_file_cmd"],
source_file, dest_file))
| def clean(self):
clean_cmd = "%s %s" % (params["clean_cmd"], dest_file)
self.session.cmd(clean_cmd)
if self.dest_dir:
self.session.cmd("umount %s" % self.dest_dir)
self.session.close()
class Multihost(MiniSubtest):
def test(self):
... |
nrwahl2/ansible | test/units/plugins/callback/test_callback.py | Python | gpl-3.0 | 11,491 | 0.000087 | # (c) 2012-2014, Chris Meyers <chris.meyers.fsu@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) an... | sible_no_log': True}
res = cb._get_item(results)
self.assertEquals(res, "(censored due to no_log)")
results = {'item': 'some_item', '_ansible_no_log': False}
res = cb._ge | t_item(results)
self.assertEquals(res, "some_item")
def test_clean_results(self):
cb = CallbackBase()
result = {'item': 'some_item',
'invocation': 'foo --bar whatever [some_json]',
'changed': True}
self.assertTrue('changed' in result)
sel... |
AmbiBox/kodi.script.ambibox | resources/lib/ambiwincon.py | Python | gpl-2.0 | 1,568 | 0.000638 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 KenV99
#
# 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 program is distributed in the hope that it will be useful,
# b... | anty 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, see <http://www.gnu.org/licenses/>.
#
WM_HOTKEY = 786
VK_SHIFT = 16
VK_CONTROL = 17
... |
xbmcmegapack/plugin.video.megapack.dev | resources/lib/menus/home_countries_togo.py | Python | gpl-3.0 | 1,105 | 0.00272 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This file is part of XBMC Mega Pack Addon.
Copyright (C) 2014 Wolverine (xbmcmegapack@gmail.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 Softwar... | "
class Countries_Togo():
'''Class that manages this specific menu context.'''
def open(self, plugin, menu):
menu.add_xplugins(plugin | .get_xplugins(dictionaries=["Channels",
"Events", "Live", "Movies", "Sports", "TVShows"],
countries=["Togo"])) |
brhoades/megaminer16-anarchy | joueur/game_manager.py | Python | mit | 3,572 | 0.006719 | from joueur.delta_mergeable import DeltaMergeable
from joueur.base_game_object import BaseGameObject
from joueur.utilities import camel_case_converter
from joueur.serializer import is_game_object_reference, is_object
# @class GameManager: managed the game and it's game objects including unserializing deltas
class Game... | self, game):
self.game = game
self._game_object_classes = game._game_object_classes
def set_constants(self, constants):
self._server_constants = constants
self._DELTA_REMOVED = constants['DELTA_REMOVED']
| self._DELTA_LIST_LENGTH = constants['DELTA_LIST_LENGTH']
## applies a delta state (change in state information) to this game
def apply_delta_state(self, delta):
if 'gameObjects' in delta:
self._init_game_objects(delta['gameObjects'])
self._merge_delta(self.game, delta)
## game... |
vurmux/gorynych | gorynych/core/edge.py | Python | apache-2.0 | 312 | 0.003205 | from .entity import Entity
class Edge(Entity):
"""Basic class for all edge objects"""
meta = {
"ontology": "gch",
"typename": "Edge",
"hierarchy": "gch/Entity.Edge"
}
def __init__(self, attributes | ={}, t | ags=set([])):
super(Edge, self).__init__(attributes, tags)
|
neopenx/Dragon | Dragon/python/dragon/vm/theano/compile/sharedvalue.py | Python | bsd-2-clause | 890 | 0.003371 | # --------------------------------------------------------
# Theano @ Dragon
# Copyright(c) 2017 SeetaTech
# Written by Ting Pan
# --------------------------------------------------------
import numpy as np
import dragon.core.workspace as ws
from dragon.core.tensor import Tensor, GetTensorN | ame
def shared(value, name=None, **kwargs):
"""Construct a Tensor initialized with ``value``.
Parameters
----------
value : basic type, list or numpy.ndarray
The numerical values.
name : str
The name of tensor.
Returns
-------
Tensor
The initialized tensor.
... | ray)):
raise TypeError("Unsupported type of value: {}".format(type(value)))
if name is None: name = GetTensorName()
tensor = Tensor(name).Variable()
ws.FeedTensor(tensor, value)
return tensor |
IljaKosynkin/OnFlyLocalizer | OnFlyLocalizer/OnFlyLocalizer/LanguageEnumGenerator.py | Python | apache-2.0 | 1,612 | 0.003102 | import os
def generate_enum(path, localizations):
full_path = path + "/" + "Language.swift"
if not os.path.isfile(full_path):
enum_file = open(full_path, 'w+')
enum_file.write("import Foundation\n\n")
enum_file.write("enum Language: String {\n")
enum_file.write("\tprivate stat... | ations:
enum_file.write("\tcase " + localization + " = \"" + localization + "\"\n")
enum_file.write("\tcase Undefined = \"\"\n\n")
enum_file.write("\tstatic func getCurrentLanguage() -> Language {\n")
enum_file.write("\t\tif let language = currentLanguage {\n")
enum_file.wri... | = array.first, let language = Language(rawValue: label) {\n")
enum_file.write("\t\t\tcurrentLanguage = language\n")
enum_file.write("\t\t\treturn language\n")
enum_file.write("\t\t}\n\n")
enum_file.write("\t\treturn .Undefined\n")
enum_file.write("\t}\n\n")
enum_file.wr... |
tgquintela/pythonUtils | pythonUtils/TUI_tools/automatic_questioner.py | Python | mit | 19,433 | 0.001029 |
"""
automatic_questioner
--------------------
Module which serves as a interactor between the possible database with the
described structure and which contains information about functions and
variables of other packages.
Scheme of the db
----------------
# {'function_name':
# {'variables':
# {'variabl... | the system with all its
functions and dependencies between them in order to ask for their
variables authomatically.
Returns
-------
check: boolean
returns the correctness of the database.
path: list
path of the possible error.
message: str
messag | e of the error if it exists.
"""
## 0. Initial preset variables needed
# Function to compare lists
def equality_elements_list(a, b):
a = a.keys() if type(a) == dict else a
b = b.keys() if type(b) == dict else b
c = a[-1::-1]
return a == b or c == b
# List of elements... |
estnltk/estnltk | estnltk/vabamorf/tests/test_disambiguate.py | Python | gpl-2.0 | 1,255 | 0.000807 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function, absolute_import
import unittest
from ..morf import analyze, disambiguate
# EINO SANTANEN. Muodon vanhimmat
# http://luulet6lgendus.blogspot.com/
sentences = '''KÕIGE VANEM MUDEL
Pimedas luusivad robotid,
originaalsed tšehhi robotid kahe... | astena kauguses,
mattudes vastuoludesse,
muutudes peaaegu julmaks oma õiglusejanus.
Robota! Kui päike pageb monoliitide kohalt,
tähistavad nad vägisi
öö salajast geomeetriat.
Õudne on inimesel vaadata
neid metsikuid mudeleid.
Kuuntele, romantiikkaa, 2002'''.split('\n')
class TestDisambiguator(unittest.TestCase):
... | inst the built in disambiguate=True function.
Both must work the same."""
def test_disambiguator(self):
for sentence in sentences:
an_with = analyze(sentence)
an_without = analyze(sentence, disambiguate=False)
disamb = disambiguate(an_without)
self.asser... |
linkfloyd/linkfloyd | linkfloyd/summaries/management/commands/send_summary_mails.py | Python | bsd-3-clause | 2,371 | 0.003374 | from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
from django.template.loader import render_to_string
from django.conf import settings
from preferences.models import UserPreferences
from summaries.models import Unseen
from django.contrib.sites.models import Site
from op... | " %settings.DEFAULT_FROM_EMAIL,
[user.email,])
email.at | tach_alternative(email_body_html, "text/html")
email.send()
self.stdout.write("Summary email for %s sent\n" % user)
if not options['dry']:
unseen_models.delete()
|
carragom/modoboa | doc/conf.py | Python | isc | 7,215 | 0.006514 | # -*- coding: utf-8 -*-
#
# Modoboa documentation build configuration file, created by
# sphinx-quickstart on Mon Jan 3 22:29:25 2011.
#
# 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... | al" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use | _parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
... |
PietPtr/FinalProject | backend/restaurant/migrations/0010_auto_20161103_1400.py | Python | gpl-3.0 | 526 | 0.001901 | # -*- coding: utf-8 | -*-
# Generated by Django 1.10.2 on 2016-11-03 14:00
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('restaurant', '0009_permission'),
]
operations = [
migrations.AlterModelOptions(
| name='permission',
options={'permissions': (('isCook', 'Can see the cooks page'), ('isWaiter', 'Can see the waiter page'), ('isCashier', 'Can see the cashier page'))},
),
]
|
AthosOrg/athos-core | setup.py | Python | mit | 491 | 0.034623 | #!/usr/bin/env python
from setuptools import setup, find_packages
# get requirements.txt
with open('requirements.txt') as f:
required = f. | read().splitlines()
setup(name='athos-core',
description = 'Athos project core',
url = 'https://github.com/AthosOrg/',
packages = find_packages(),
entry_points = {
'console_scripts': [
'athos-core=athos. | cmd:main'
]
},
install_requires = required,
package_data = {'athos': ['default.yml']}
) |
wagigi/fabtools-python | fabtools/user.py | Python | bsd-2-clause | 8,682 | 0 | """
Users
=====
"""
from pipes import quote
import posixpath
import random
import string
from fabric.api import hide, run, settings, sudo, local
from fabtools.group import (
exists as _group_exists,
create as _group_create,
)
from fabtools.files import uncommented_lines
from fabtools.utils import run_as_root... | hoice(_SALT_CHARS)
crypted_password = crypt(password, salt)
return crypted_password
def create(name, comment=None, home=None, create_home=None, skeleton_dir=None,
group=None, create_group=True, extra_groups=None, password=None,
system=False, shell=None, uid=None, ssh_public_keys=None,
... | and its home directory.
If *create_home* is ``None`` (the default), a home directory will be
created for normal users, but not for system users.
You can override the default behaviour by setting *create_home* to
``True`` or ``False``.
If *system* is ``True``, the user will be a system account. It... |
github/codeql | python/ql/test/query-tests/Imports/general/mutates_in_test.py | Python | mit | 117 | 0.008547 | import mutable_attr
import unittest
class T(unittest.TestCase):
def test_foo(self):
| mutable_attr.y | = 3
|
PennartLoettring/Poettrix | rootfs/usr/lib/python3.4/ctypes/test/test_cast.py | Python | gpl-2.0 | 3,210 | 0.002492 | from ctypes import *
import unittest
import sys
class Test(unittest.TestCase):
def test_array2pointer(self):
array = (c_int * 3)(42, 17, 2)
# casting an array to a pointer works.
ptr = cast(array, POINTER(c_int))
self.assertEqual([ptr[i] for i in range(3)], [42, 17, 2])
i... | ort) == sizeof(c_int):
ptr = cast(array, POINTER(c_short))
if sys.byteorder == "little":
self.assertEqual([ptr[i] for i in range(6)],
[42, 0, 17, 0, 2, 0])
else:
self.assertEqual([ptr[i] for i in range(6)],
... | dress = addressof(array)
ptr = cast(c_void_p(address), POINTER(c_int))
self.assertEqual([ptr[i] for i in range(3)], [42, 17, 2])
ptr = cast(address, POINTER(c_int))
self.assertEqual([ptr[i] for i in range(3)], [42, 17, 2])
def test_p2a_objects(self):
array = (c_char_p * 5)(... |
wikimedia/pywikibot-sf-export | jira.py | Python | mit | 12,518 | 0.004793 | #!/usr/bin/env python
#
# Required packages:
reqs = """
requests >= 2.0.0
python-bugzilla >= 0.8.0
html2text >= 3.200.3
"""
import sys
try:
import requests
assert(requests.__version__ >= "2.0.0")
import bugzilla
assert(bugzilla.__version__ >= "0.8.0")
import html2text
assert(html2text.__ver... | ""Usage: {argv[0]} 'bugzilla component name within Tool Labs Tools' 'JIRA JQL query' [-importdoubles]
-importdoubles can be used to double-import bugs, which is useful for
testing. Otherwise, bugs that already exist in B | ugzilla
are skipped.
Example:
{argv[0]} 'DrTrigonBot - General' 'project = DRTRIGON'"
""".format(argv=sys.argv))
sys.exit(1)
component = sys.argv[1]
jql = sys.argv[2]
# BZ config
bug_defaults = {
'product': 'Tool Labs tools', # SET THIS!
'component': component, #"Database Quer... |
OuachitaHillsMinistries/OHCFS | htbin/app.py | Python | gpl-2.0 | 447 | 0.006711 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# If this page isn't working, try executing `chmod +x app.py` in terminal.
# enable debugging
import cgitb, cgi; cgitb.enable()
from classes import Factory
fieldStorage = cgi.FieldStorage()
factory = Factory.Factory()
webApp = fact | ory.makeWebApp(fieldStorage)
def outputHeaders():
print "Content-Type: text/html"
print # signals end of headers
outputHeaders()
print webApp.getO | utput()
|
sveetch/sveedocuments | sveedocuments/utils/objects.py | Python | mit | 871 | 0.003476 | # -*- coding: utf-8 -*-
def get_instance_children(obj, depth=0, sig=0):
"""
Récupèration récursive des relations enfants d'un objet
@depth: integer limitant le niveau de recherc | he des enfants, 0=illimité
"""
children = []
# Pour toute les relations enfants de l'objet
for child in obj._meta.get_all_related_objects():
# Nom de l'attribut d'accès
cname = child.get_accessor_name()
verbose_name = child.model._meta.verbose_name
# Récupère tout les obj... | cherche récursive des enfants
if depth == 0 or sig < depth:
followed = get_instance_children(elem, depth=depth, sig=sig+1)
children.append( (verbose_name, unicode(elem), followed) )
return children
|
andela-ijubril/book-search | booker/bookstore/tests/test_models.py | Python | mit | 527 | 0.003795 | from django.test import Test | Case
from bookstore.models import Book, Category
class InventoryModelTest(TestCase):
def test_string_representation_of_categories(self):
category = Category.objects.create(name="health", description="health category")
self.assertEqual(category.name, 'health')
def test_string_representation_o... | l(str(book), 'some text')
|
angelapper/odoo | addons/mrp_repair/mrp_repair.py | Python | agpl-3.0 | 35,968 | 0.004337 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from openerp.osv import fields, osv
from datetime import datetime
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
from openerp.exceptions import UserError
class mrp_repair(osv.osv):
... | readonly=True, states={'draft': [('readonly', False)]}, copy=True),
'pricelist_id': fields.m | any2one('product.pricelist', 'Pricelist', help='Pricelist of the selected partner.'),
'partner_invoice_id': fields.many2one('res.partner', 'Invoicing Address'),
'invoice_method': fields.selection([
("none", "No Invoice"),
("b4repair", "Before Repair"),
("after_repair"... |
rpatterson/test-har | test_har/tests/test_drf.py | Python | gpl-3.0 | 563 | 0 | """
Test using HAR files in Python tests against the Django ReST framework.
"""
from django import http
from rest | _framework import response
from test_har import django_rest_har as test_har
from test_har import tests
class HARDogfoodDRFTests(tests.HARDogfoodTestCase, test_har.HARTestCase):
"""
Test using HAR files in Python tests against the Django ReST framework.
"""
RESPONSE_TYPE = (http.HttpResponse, respons... | ssertTrue(True)
|
bdcht/amoco | amoco/ui/render.py | Python | gpl-2.0 | 18,256 | 0.007066 | # -*- coding: utf-8 -*-
# This code is part of Amoco
# Copyright (C) 2006-2011 Axel Tillequin (bdcht3@gmail.com)
# published under GPLv2 license
"""
render.py
=========
This module implement | s amoco's pygments interface to allow pretty printed
outputs of tables of tokens built from amoco's expressions and instructions.
The rendered texts are used as main inputs for graphic engines to build
their own views' | objects.
A token is a tuple (t,s) where t is a Token type and s is a python string.
The highlight method uses the Token type to decorate the string s such that
the targeted renderer is able to show the string with foreground/background
colors and bold/underline/etc stroke attributes.
The API of this module is essent... |
brianwgoldman/LengthBiasCGP | stats.py | Python | bsd-2-clause | 1,633 | 0 | '''
Takes file names from the final/ folder and parses the information into
readable values and produces statistical measures. Use this module as an
executable to process all result information for a single problem, such as:
python stats.py final/multiply*.dat
Do not mix problems in a single run.
NOTE: You CANNOT u... | s.argv[1:]:
base = path.basename(filename)
try:
problem, nodes, version, seed = base.split('_')
| with open(filename, 'r') as f:
data = json.load(f)
statify[version].append(data[1]['evals'])
active[version].append(data[1]['phenotype'])
filecount += 1
except ValueError:
print filename, "FAILED"
print 'Files Successfully Loaded', filecoun... |
werbk/task-4.11 | fixture/TestBase.py | Python | apache-2.0 | 2,024 | 0.00247 | from selenium.webdriver.firefox.webdriver import WebDriver
from tests_group.group_lib import GroupBase
from tests_contract.contract_lib import ContactBase
class SessionHelper:
def __init__(self, app):
self.app = app
def login(self, user_name, password):
wd = self.app.wd
self.app.open_... | ogout")) > 0
def is_lo | gged_in_as(self, username):
wd = self.app.wd
return wd.find_element_by_xpath("//div/div[1]/form/b").text == '('+username+')'
def ensure_logout(self):
if self.is_logged_in():
self.logout()
def ensure_login(self, user_name, password):
if self.is_logged_in():
... |
farooqsheikhpk/Aspose.BarCode-for-Cloud | Examples/Python/generating-saving/cloud-storage/set-barcode-image-height-width-quality-settings.py | Python | mit | 2,140 | 0.014953 | import asposebarcodecloud
from asposebarcodecloud.BarcodeApi import BarcodeApi
from asposebarcodecloud.BarcodeApi import ApiException
import asposestoragecloud
from asposestoragecloud.StorageApi import StorageApi
from asposestoragecloud.StorageApi import ResponseMessage
import ConfigParser
config = Config... |
#invoke Aspose.BarCode Cloud SDK API to generate image with specific height, width, and quality along with auto size option
| response = barcodeApi.PutBarcodeGenerateFile(name, file= None, text=text, type=type, format=format, imageHeight=imageHeight, imageWidth=imageWidth, imageQuality=imageQuality)
if response.Status == "OK":
#download generated barcode from cloud storage
response = storageApi.GetDownload(Path... |
richard-willowit/odoo | addons/board/controllers/main.py | Python | gpl-3.0 | 1,724 | 0.00116 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from lxml import etree as ElementTree
from odoo.http import Controller, route, request
class Board(Controller):
@route('/board/add_to_dashboard', type='json', auth='user')
def add_to_dashboard(self, action_id... | ee.tostring(xml, encoding='unicode')
| request.env['ir.ui.view.custom'].create({
'user_id': request.session.uid,
'ref_id': view_id,
'arch': arch
})
return True
return False
|
Flexget/Flexget | flexget/tests/test_argparse.py | Python | mit | 2,272 | 0.00088 | from argparse import Action
from flexget.options import ArgumentParser
def test_subparser_nested_namespace():
p = ArgumentParser()
p.add_argument('--outer')
p.add_subparsers(nested_namespaces=True)
sub = p.add_subparser('sub')
sub.add_argument('--inner')
sub.add_subparsers()
subsub = sub.... | r', 'c'])
assert result.outer == 'a'
# First subpa | rser values should be nested under subparser name
assert result.sub.inner == 'b'
assert not hasattr(result, 'inner')
# The second layer did not define nested_namespaces, results should be in first subparser namespace
assert result.sub.innerinner == 'c'
assert not hasattr(result, 'innerinner')
def ... |
uw-it-cte/uw-restclients | restclients/test/myplan.py | Python | apache-2.0 | 3,193 | 0.002819 | from django.test import TestCase
from restclients.myplan import get_plan
class MyPlanTestData(TestCase):
def test_javerage(self):
plan = get_plan(regid="9136CCB8F66711D5BE060004AC494FFE", year=2013, quarter="spring", terms=4)
self.assertEquals(len(plan.terms), 4)
self.assertEquals(plan.ter... | plan.json_data()
term_data = json_data["terms"][0]
self.assertEquals(term_data["courses"][0]["sections"][1]["section_id"], "AA")
self.assertEquals(term_data["registered_courses_count"], 0)
self.assertEquals(term_data["registration_href"],
"https://uwkseval.cac.... | istration/20132")
self.assertEquals(term_data["course_search_href"],
"https://uwkseval.cac.washington.edu/student/myplan/mplogin/netid?rd=/student/myplan/course")
self.assertEquals(term_data["quarter"], "Spring")
|
styk-tv/offlineimap | offlineimap/emailutil.py | Python | gpl-2.0 | 1,573 | 0.001271 | # Some useful functions to extract data out of emails
# Copyright (C) 2002-2012 John Goerzen & contributors
#
# 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 Lic... | ne if missing or not in a valid format. Note that
| # indexes 6, 7, and 8 of the result tuple are not usable.
datetuple = email.utils.parsedate_tz(dateheader)
if datetuple is None:
return None
return email.utils.mktime_tz(datetuple)
|
imposeren/django-happenings | tests/integration_tests/event_factory.py | Python | bsd-2-clause | 3,323 | 0.000602 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from django.utils import timezone
from django.test import TestCase
from django.contrib.auth.models import User
from django.test.utils import override_settings
import six
from happenings.models import Event
@override_settings(CALENDAR_... | date and end_date:
# Set the start and end dates to local tz
| if utc:
val = timezone.utc
else:
val = timezone.get_default_timezone()
start_date = timezone.make_aware(datetime.datetime(*start_date), val)
end_date = timezone.make_aware(datetime.datetime(*end_date), val)
elif start_date and not end_date or end_date and not st... |
GoUbiq/pyexchange | pyexchange/__init__.py | Python | apache-2.0 | 853 | 0.004689 | """
(c) 2013 LinkedIn C | orp. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");?you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software?distributed ... | t logging
from .exchange2010 import Exchange2010Service # noqa
from .connection import ExchangeNTLMAuthConnection # noqa
from .connection import ExchangeHTTPBasicAuthConnection
# Silence notification of no default logging handler
log = logging.getLogger("pyexchange")
class NullHandler(logging.Handler):
def emit(s... |
obi-two/Rebelion | data/scripts/templates/object/tangible/ship/crafted/weapon/shared_shield_effectiveness_intensifier_mk4.py | Python | mit | 512 | 0.042969 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import | *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/crafted/weapon/shared_shield_effectiveness_intensifier_mk4.iff"
result.attribute_template_id = 8
result.stfName("space_crafting_n","shield_effectiveness_ | intensifier_mk4")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
KaiRo-at/socorro | alembic/versions/22e4e60e03f_bug_867387_bixie_dra.py | Python | mpl-2.0 | 9,842 | 0.015241 | """bug 867387 Bixie draft schema
Revision ID: 22e4e60e03f
Revises: 37004fc6e41e
Create Date: 2013-05-10 13:20:35.750954
"""
# revision identifiers, used by Alembic.
revision = '22e4e60e03f'
down_revision = '37004fc6e41e'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from ... | u'id'),
schema=u'bixie'
)
op.create_table(u'crashes_normalized',
sa.Column(u'crash_id', postgresql.UUID(), autoincrement=False,
nullable=False),
sa.Column(u'signature_id', sa.TEXT(), nullable=False),
sa.Column(u'error_message_id', JSON(), nullable=False),
sa.Column(u'product_id', sa.... | schema=u'bixie'
)
op.create_table(u'hosts',
sa.Column(u'id', sa.INTEGER(), nullable=False),
sa.Column(u'name', sa.TEXT(), nullable=False),
sa.PrimaryKeyConstraint(u'id'),
schema=u'bixie'
)
op.create_table(u'signatures',
sa.Column(u'id', sa.INTEGER(), nullable=False),
sa.Colum... |
cosminbasca/rdftools | rdftools/__version__.py | Python | apache-2.0 | 707 | 0.001414 | #
# author: Cosmin Basca
#
# Copyright 2010 University of Zurich
#
# 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 a... | r agreed to in writing, softw | are
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
__author__ = 'basca'
version = (0, 9, 5)
str_version = '.'.join([st... |
vsemionov/wordbase | src/wordbase/pyparsing.py | Python | bsd-3-clause | 146,612 | 0.015408 | # module pyparsing.py
#
# Copyright (c) 2003-2011 Paul T. McGuire
#
# 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, cop... | all parsing runtime exceptions"""
# Performance tuning: we construct a *lot* of these, so keep this
# constructor as small and fast as possible
def __init__( self, p | str, loc=0, msg=None, elem=None ):
self.loc = loc
if msg is None:
self.msg = pstr
self.pstr = ""
else:
self.msg = msg
self.pstr = pstr
self.parserElement = elem
def __getattr__( self, aname ):
"""supported attributes by name ar... |
jlmdegoede/Invoicegen | hour_registration/views.py | Python | gpl-3.0 | 5,189 | 0.000964 | from .models import HourRegistration
from orders.models import Product
from django.utils import timezone
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from datetime import datetime
import pytz
from django.con | trib.auth.decorators import permission_required
@login_required
@permission_required('hour_registration.add_hourregistration', 'hour_registration.change_hourregistration')
def start_time_tracking(request, product_id):
produc | t = Product.objects.get(id=product_id)
existing_time = HourRegistration.objects.filter(end=None)
if existing_time.count() == 0:
time = HourRegistration(product=product, start=timezone.now())
time.save()
return JsonResponse({'success': True, 'start': format_time_to_local(time.start)})
... |
skg-net/ansible | lib/ansible/modules/notification/say.py | Python | gpl-3.0 | 2,275 | 0.002198 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2013, Michael DeHaan <michael@ansible.com>
# 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_M | ETADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: say
version_added: "1.2"
short_description: Makes a computer to speak.
description:
- makes a computer speak! Amuse your friends, annoy your cowo... | tes:
- In 2.5, this module has been renamed from C(osx_say) to M(say).
- If you like this module, you may also be interested in the osx_say callback plugin.
options:
msg:
description:
What to say
required: true
voice:
description:
What voice to use
required: false
requirements: [ s... |
guigovedovato/python | api/clienteApi.py | Python | gpl-3.0 | 1,042 | 0.002879 | from flask import request
from flask_restful import Resource
import json
from core.bo.clienteBo import ClienteBo
class Cliente(Resource):
def __init__(self):
self.cliente = ClienteBo()
def get(self, parameter=""):
if parameter == "":
| return self.cliente.get_all(), 201
else:
param | eter = json.loads(parameter)
if parameter.get('id'):
return self.cliente.get_by_id(parameter["id"]), 201
elif parameter.get('document'):
return self.cliente.get_document(parameter["document"], parameter["cliente"]), 201
elif parameter.get('board'):
... |
gordenbrown51/damnvid | dLoader.py | Python | gpl-3.0 | 3,966 | 0.037317 | # -*- coding: utf-8 -*-
from dCore import *
from dConstants import *
from dLog import *
from dThread import *
from dModules import *
class DamnVideoLoader(DamnThread):
def __init__(self, parent, uris, thengo=False, feedback=True, allownonmodules=True):
DamnThread.__init__(self)
self.uris = []
if type(uris) not i... | llow non-modules?',allownonmodules)
def go(self):
if self.feedback:
self.parent.toggleLoading(True)
self.vidLoop(self.uris)
self.done = True
if self.feedback:
self.parent.toggleLoading(False)
else:
while self.done:
time.sleep(.1)
def postEvent(self, info):
if self.feedback:
DV.postEvent(se... | ef addValid(self, meta):
meta['original'] = self.originaluri
self.result = meta
self.postEvent({'meta':meta, 'go':self.thengo})
def SetStatusText(self, status):
self.postEvent({'status':status})
def showDialog(self, title, content, icon):
self.postEvent({'dialog':(title, content, icon)})
def vidLoop(self, ... |
flacjacket/sympy | examples/intermediate/vandermonde.py | Python | bsd-3-clause | 4,652 | 0.006449 | #!/usr/bin/env python
"""Vandermonde matrix example
Demonstrates matrix computations using the Vandermonde matrix.
* http://en.wikipedia.org/wiki/Vandermonde_matrix
"""
from sympy import Matrix, pprint, Rational, sqrt, symbols, Symbol, zeros
def symbol_gen(sym_str):
"""Symbol generator
Generates sym_str_... | polynomials.
"""
syms = syms.split()
if len(syms) < dim:
new_syms = []
for i in range(dim - len(syms)):
| new_syms.append(syms[i%len(syms)] + str(i/len(syms)))
syms.extend(new_syms)
terms = []
for i in range(order + 1):
terms.extend(comb_w_rep(dim, i))
rank = len(terms)
V = zeros(rank)
generators = [symbol_gen(syms[i]) for i in range(dim)]
all_syms = []
for i in range(rank):
... |
victorshch/axiomatic | test_axiom_system.py | Python | gpl-3.0 | 402 | 0 | # -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
from axiomatic.base import AxiomSystem
from axiomatic.elementary_conditions import MinMaxAxiom
# l, r, pmin, pmax
params = [1, 1, -0.8, 0.8]
a | xiom_list = [MinMaxAxiom(params)]
ts = pd.DataFrame(np.random.random((10, 2)))
print(ts)
print(MinMaxAxiom(params) | .run(ts, dict()))
now = AxiomSystem(axiom_list)
print(now.perform_marking(ts))
|
mikaelboman/home-assistant | homeassistant/components/proximity.py | Python | mit | 8,866 | 0 | """
Support for tracking the proximity of a device.
Component to monitor the proximity of devices to a particular zone and the
direction of travel.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/proximity/
"""
import logging
from homeassistant.helpers... | dly_name, dist_to, dir_of_travel,
nearest, ignored_zones, proximity_devices, tolerance,
proximity_zone):
"""Initialize the proximity."""
self.hass = hass
self.friendly_name = zone_friendly_name
self.dist_to = dist_to
self.dir_of_travel = dir_of_t... | e
self.proximity_zone = proximity_zone
@property
def name(self):
"""Return the name of the entity."""
return self.friendly_name
@property
def state(self):
"""Return the state."""
return self.dist_to
@property
def unit_of_measurement(self):
"""Re... |
BishopFox/SpoofcheckSelfTest | handlers/HomePageHandler.py | Python | apache-2.0 | 154 | 0 | from | handlers.BaseHandlers import BaseHandler
class HomePageHandler(BaseHandler):
def get(self, *args, **kwargs):
self.render('home. | html')
|
mgaitan/moin2git | wikiconfig.py | Python | bsd-3-clause | 2,368 | 0.00549 | # -*- coding: iso-8859-1 -*-
"""MoinMoin Desktop Edition (MMDE) - Configuration
ONLY to be used for MMDE - if you run a personal wiki on your notebook or PC.
This is NOT intended for internet or server or multiuser use due to relaxed security settings!
"""
import sys, os
from MoinMoin.config imp | ort multiconfig, url_prefix_static
class LocalConfig(multiconfig.DefaultConfig):
# vvv DON'T TOUCH THIS EXCEPT IF YOU KNOW WHAT YOU DO vvv
# Directory containing THIS wikiconfig:
wikiconfig_dir = os.path.abspath(os.path.dirname(__file__))
# We assume this structure for a simple "unpack and run" scena... | o the real path
# where data/ and underlay/ is located:
#instance_dir = '/where/ever/your/instance/is'
instance_dir = os.path.join(wikiconfig_dir, 'wiki')
# Where your own wiki pages are (make regular backups of this directory):
data_dir = os.path.join(instance_dir, 'data', '') # path with trailing... |
kartikp1995/gr-bokehgui | python/qa_waterfall_sink_f.py | Python | gpl-3.0 | 1,883 | 0.001062 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2011-2013,2015 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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 v... | :
self.tb = None
def test_001_t(self):
| original = (1,) * 100 + (-1,) * 100 + (0,) * 50 + (10,) + (0,) * 49
expected_result = [(-200,) * 50 + (0,) + (-200,) * 49, (-20,) * 100]
src = blocks.vector_source_f(original, False, 1, [])
dst = waterfall_sink_f_proc(100, filter.firdes.WIN_RECTANGULAR, 0,
... |
artofai/neural-network | layer.py | Python | mit | 4,245 | 0.008009 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
The Art of an Artificial Intelligence
http://art-of-ai.com
https://github.com/artofai
"""
__author__ = 'xevaquor'
__license__ = 'MIT'
import numpy as np
import util
class LayerBase(object):
def __init__(self):
self.size = None
self.W = np.zeros((0,0))... | self.layers]
return util.unwrap_matrix(all_wages)
def random_init(self):
for layer in self.layers:
layer.random_init()
def forward(self, X):
# hiden layer
m, n = X.shape
# examples, features
assert n == self.layers[0].size
self.layers[0].a ... | .a.shape[0], 1))
source_layer.a = np.hstack((bias, source_layer.a))
dest_layer.v = np.dot(source_layer.a, dest_layer.W)
dest_layer.a = dest_layer.phi(dest_layer.v)
self.y_hat = self.layers[-1].a
return self.y_hat
def cost(self, X, y):
self.y_hat = self.... |
devops-alpha-s17/customers | customers/__init__.py | Python | apache-2.0 | 184 | 0.005435 | '''
@author: Tea | m Alpha, <aa5186@nyu.edu>
Name: Customer Model
Purpose: This library is part of the customer REST API for the ecommerce website
'''
from customer import Cus | tomer
|
concentricsky/badgr-server | apps/composition/__init__.py | Python | agpl-3.0 | 77 | 0 | # this app has been depr | ecated but sticks around for m | igrations dependencies
|
thrisp/flarf | setup.py | Python | mit | 1,046 | 0 | """
Flarf: Flask Request Filter
-------------
Configurable request filters
"""
from setuptools import setup
setup(
name='Flask-Flarf',
version='0.0.5',
url='https://github.com/thrisp/flarf',
license='MIT',
author='Thrisp/Hurrata',
author_email='blueblank@gmail.com',
description='Flask requ... | SI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Progr | amming Language :: Python :: 3',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
|
jarrodmcc/OpenFermion | src/openfermion/utils/__init__.py | Python | apache-2.0 | 5,551 | 0 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distribu... | ne_pdm_to_one_hole_dm,
map_one_hole_dm_to_one_pdm,
| map_two_pdm_to_particle_hole_dm,
map_two_hole_dm_to_two_pdm,
map_two_hole_dm_to_one_hole_dm,
map_particle_hole_dm_to_one_pdm,
map_particle_hole_dm_to_two_pd... |
pauljxtan/pystuff | pycompvis/compvis/feature/detectors.py | Python | mit | 6,800 | 0.003676 | """
Feature detection (Szeliski 4.1.1)
"""
import numpy as np
import scipy.signal as sig
import scipy.ndimage as ndi
from compvis.utils import get_patch
def sum_sq_diff(img_0, img_1, u, x, y, x_len, y_len):
"""
Returns the summed square difference between two image patches, using even
weighting across the... |
continue
# Skip the highest score (infinite suppression radius)
if (i, j) == coord_max:
continue
# Find suppression radius
r = 0
r_found = False
while | not r_found:
r += 1
# Keep the candidate "window" within the image
x0 = i-r if i-r >= 0 else 0
x1 = i+r+1 if i+r+1 < scores.shape[0] else scores.shape[0]-1
y0 = j-r if j-r >= 0 else 0
y1 = ... |
jriehl/numba | numba/targets/dictimpl.py | Python | bsd-2-clause | 504 | 0 | """
This file implements the lowering for `dict()`
"""
from numba.targets.imputils import lower_builtin
@lower_builtin(dict)
def impl_dict(con | text, builder, sig, args):
"""
The `dict()` implementation simply forwards the work to `Dict.empty()`.
"""
from numba.typed import Dict
dicttype = sig.return_type
kt, vt = dicttype.key_type, dicttype.value_type
def call_ctor():
return Dict.empty(kt, vt) |
return context.compile_internal(builder, call_ctor, sig, args)
|
pattarapol-iamngamsup/projecteuler_python | problem_006.py | Python | gpl-3.0 | 1,747 | 0.034345 | """ Copyright 2012, July 31
Written by Pattarapol (Cheer) Iamngamsup
E-mail: IAM.PATTARAPOL@GMAIL.COM
Sum square difference
Problem 6
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + ... | e square of the sum.
"""
#################################################
# Importing libraries & modules
import datetime
#################################################
# Global variables
#################################################
# Functions
###########################################... |
#################################################
# Main function
def main():
squareOfSum = ( ( ( 1+100 ) * 100 ) / 2)**2
sumOfSquare = 0
for i in range( 1, 101 ):
sumOfSquare += i*i
print( 'answer = {0}'.format( squareOfSum - sumOfSquare ) )
#################################################
# ... |
kevinpdavies/pycsw | pycsw/plugins/profiles/apiso/apiso.py | Python | mit | 50,869 | 0.00692 | # -*- coding: iso-8859-15 -*-
# =================================================================
#
# Authors: Tom Kralidis <tomkralidis@gmail.com>
# Angelos Tzotsos <tzotsos@gmail.com>
#
# Copyright (c) 2015 Tom Kralidis
# Copyright (c) 2015 Angelos Tzotsos
#
# Permission is hereby granted, free of charge, to... | ation/gm | d:alternateTitle/gco:CharacterString', 'dbcol': self.context.md_core_model['mappings']['pycsw:AlternateTitle']},
'apiso:RevisionDate': {'xpath': 'gmd:identificationInfo/gmd:MD_DataIdentification/gmd:citation/gmd:CI_Citation/gmd:date/gmd:CI_Date[gmd:dateType/gmd:CI_DateTypeCode/@codeListValue="re... |
monodokimes/pythonmon | core/menu.py | Python | gpl-3.0 | 1,737 | 0 | import sys
from core import loop
from util import jsonmanager, debug
def make_console_menu(name):
menu_data_file_path = '_Resources/Data/MenuData/'
path = menu_data_file_path + name + '.json'
data = jsonmanager.get_data(path)
title = data['Title']
item_data = data['Items']
args = []
for... | text)
def run(self):
for index in range(0, len(self.menu_items)):
self.display_menu_item(index)
result = input('Choose an option: ')
self.get_menu_item(int(result)).invoke()
def run_loop(game_loop):
game_loop.set_scene('pallet-town')
game_loop.run()
def | run_editor():
run_loop(loop.EditorLoop())
def run_game():
run_loop(loop.DefaultGameLoop())
|
drf24/labutils | utils_gui.py | Python | gpl-3.0 | 7,383 | 0.006772 | #!/usr/bin/env python3
import idmaker
import utils
from tkinter import *
from PIL import Image, ImageTk
top = Tk()
top.wm_title("Voice Research Laboratory")
top.iconbitmap('icons/favicon.ico')
top.state('zoomed')
class MainWindow:
def __init__(self, top):
self.top = top
self.... | .radiolabel = Label(self.manipulatewindow, text='Choose sex of voices', font=('Arial', 32), justify=LEFT)
self.radiolabel.pack(anchor=W)
self.R1 = R | adiobutton(self.manipulatewindow, text="female", font=('Arial', 32), variable=self.var, value=0)
self.R1.pack(anchor=W)
self.R2 = Radiobutton(self.manipulatewindow, text="male", font=('Arial', 32), variable=self.var, value=1)
self.R2.pack(anchor=W)
self.radiosubmitbutton = Button(sel... |
frictionlessdata/tabulator-py | tabulator/parsers/xlsx.py | Python | mit | 15,006 | 0.001066 | # -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import io
import six
import shutil
import atexit
import openpyxl
import datetime
import re
from itertools import chain
from tempfile imp... | = openpyxl.utils.rows_from_range(merged_cell_range)
coordinates = list(chain.from_iterable(merged_rows))
value = self.__sheet[coordinates[0]].value
for coordinate in coordinates:
| cell = self.__sheet[coordinate]
cell.value = value
# Internal
EXCEL_CODES = {
"yyyy": "%Y",
"yy": "%y",
"dddd": "%A",
"ddd": "%a",
"dd": "%d",
"d": "%-d",
# Different from excel as there is no J-D in strftime
"mmmmmm": "%b",
"mmmm": "%B",
"mmm"... |
google/deluca-lung | deluca/lung/experimental/controllers/_pid_correction.py | Python | apache-2.0 | 874 | 0.004577 | import torch
from deluca.lung.core import Controller, LungEnv
class PIDCorrection(Controller):
def __init__(self, base_controller: Controller, sim: LungEnv, pid_K=[0.0, 0.0], decay=0.1, **kwargs):
self.base_controller = base_controller
self.sim = sim
self.I = 0.0
self.K = pid_K
... | tate, t):
u_in_base, u_out = self.base_controller(state, t)
err = self.sim.pressure - state
self.I = self.I * (1 - self.decay) + err * self.decay
pid_correction = self.K[0] * err + self.K[1] * self.I
u_in = torch.clamp(u_in_base + pid_correction, min=0.0, max=100.0)
se... | im(u_in, u_out, t)
return u_in, u_out
|
bmedx/modulestore | xmodule/modulestore/tests/test_split_copy_from_template.py | Python | apache-2.0 | 7,859 | 0.002927 | """
Tests for split's copy_from_template method.
Currently it is only used for content libraries.
However for these tests, we make sure it also works when copying from course to course.
"""
import ddt
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.exceptions import ItemNotFoundError
from xmodu... | CourseFactory,
)
def test_copy_from_template(self, source_type):
"""
Test that the behavior of copy_from_template() matches its docstring
"""
source_container = source_type.create(module | store=self.store) # Either a library or a course
course = CourseFactory.create(modulestore=self.store)
# Add a vertical with a capa child to the source library/course:
vertical_block = self.make_block("vertical", source_container)
html_library_display_name = "HTML Display Name"
... |
ema/conpaas | conpaas-services/src/conpaas/services/htc/manager/get_run_time.py | Python | bsd-3-clause | 6,391 | 0.015334 | #import os
import sys
import time
import xmltodict
import pprint
pp = pprint.PrettyPrinter(indent=4,stream=sys.stderr)
testing = False
# def poll_condor(jonbr, bagnr):
def poll_condor(filename):
# filename = "hist-%d-%d.xml" % ( jobnr, bagnr )
# command = "condor_history -constraint 'HtcJob == %d && HtcBag ... | },
{
attr1: val1,
attrn: valn,
}
]
}
}
"""
def do_test(filename):
poll_dict = poll_condor(filename)
completed_tasks = 0
for _ in poll_dict.keys():
completed_tasks += len(poll_dict[_])
| completed_task_sets = poll_dict.keys().__len__()
print >> sys.stderr, "Found %d completed tasks in %d sets" % (completed_tasks, completed_task_sets)
if False:
pp.pprint(poll_dict)
if __name__ == "__main__":
pp = pprint.PrettyPrinter(indent=4,stream=sys.stderr)
test... |
edouard-lopez/parlr | config.py | Python | apache-2.0 | 394 | 0.002538 | import sys
im | port logging
logger = logging.getLogger(__name__)
def configure_logging():
root = logging.getLogger()
root.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
formatter = logging.Format | ter('%(asctime)s %(name)12s %(levelname)7s - %(message)s')
handler.setFormatter(formatter)
root.addHandler(handler)
|
cackharot/geosnap-server | src/geosnap/service/UserService.py | Python | apache-2.0 | 2,611 | 0.000766 | from datetime import datetime
import random
import string
from bson import ObjectId
class DuplicateUserException(Exception):
def __init__(self, message='User name/email already exits'):
Exception.__init__(self, message)
pass
class UserServiceException(Exception):
def __init__(self, message=None... | string.digits
return ''.join(random.sample(s, 20))
def create(self, item):
if self.user_exists(item['email']):
raise DuplicateUserException()
item.pop('_id', None)
item['created_at'] = datetime.now()
item['status'] = True
if 'api_key' not in item:
... | y'] = self.generate_api_key()
if 'roles' not in item or item['roles'] is None or len(item['roles']) == 0:
item['roles'] = ['member']
return self.users.insert(item)
def get_by_email(self, email):
return self.users.find_one({"email": email})
def validate_user(self, username, ... |
kikocorreoso/brython | www/tests/compression/huffman.py | Python | bsd-3-clause | 8,832 | 0.001472 | class ResizeError(Exception):
pass
def codelengths_from_frequencies(freqs):
freqs = sorted(freqs.items(),
key=lambda item: (item[1], -item[0]), reverse=True)
nodes = [Node(char=key, weight=value) for (key, value) in freqs]
while len(nodes) > 1:
right, left = nodes.pop(), nodes.pop()
... | ld.is_leaf:
sel | f.make_tree(child)
def decompress(self):
source = self.compressed
if isinstance(source, (bytes, bytearray)):
return self.decompress_bytes()
pos = 0
node = self.root
res = bytearray()
while pos < len(source):
code = int(source[pos])
... |
bigoldboy/repository.bigoldboy | plugin.video.VADER/categorySelectDialog.py | Python | gpl-3.0 | 3,306 | 0.005445 | # -*- coding: utf-8 -*-
# Licence: GPL v.3 http://www.gnu.org/licenses/gpl.html
# This is an XBMC addon for demonstrating the capabilities
# and usage of PyXBMCt framework.
import os
import xbmc
import xbmcaddon
import pyxbmct
from lib import utils
import plugintools
from itertools import tee, islice, chain, izip
_a... | row = row + 1
self.close_button = pyxbmct.Button('Close')
self.placeControl(self.close_button, row, 0)
self.connect(self.close_button, self.close)
| from itertools import tee, islice, chain, izip
def set_navigation(self):
for previous, item, nextItem in previous_and_next(self.listOfRadioButtons):
if previous != None:
item.controlUp(previous)
if nextItem != None:
item.controlDown(nextItem)
... |
OddBloke/jenkins-job-linter | tests/__init__.py | Python | apache-2.0 | 612 | 0 | # Copyright (C) 2017 Daniel Watkins <daniel@daniel-watkins.co.uk>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in co | mpliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY | KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
|
flowdas/meta | tests/ex/bytes.py | Python | mpl-2.0 | 50 | 0 | class Image(me | ta.Entity):
data = meta.Bytes | ()
|
txt/evil | diapers1.py | Python | unlicense | 1,288 | 0.041149 | from __future__ import print_function,division
# duner. using numbers and sample.
"""
q +-----+ r +-----+
---->| C |---->| D |--> s
^ +-----+ +-+---+
| |
+-----------------+
C = stock of clean diapers
D = stock of dirty diapers
q = inflow of clean diapers
r = flow of clean diapers... | has().copy())
def __getitem__(i,k): return i.has()[k]
def __setitem__(i,k,v): i.has()[k] = v
def __repr__(i) : return 'o'+str(i.has())
def sim( | state0,life=100,spy=False,dt=1):
t= 0
while t < life:
t += dt
state1 = state0.copy()
yield dt, t,state0,state1
state0 = state1
for key in state1.has().keys():
if state1[key] < 0:
state1[key] = 0
if spy:
print(t,state1)
def diapers():
def saturday(x): return int(x) %... |
blckshrk/Weboob | weboob/capabilities/recipe.py | Python | agpl-3.0 | 6,695 | 0.002091 | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Julien Veyssier
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your op... | s 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along wit... | base64
import re
import urllib
__all__ = ['Recipe', 'ICapRecipe']
class Comment():
def __init__(self, author=None, rate=None, text=None):
self.author = author
self.rate = rate
self.text = text
def __str__(self):
result = u''
if self.author:
result += 'aut... |
flavour/ssf | models/00_tables.py | Python | mit | 23,677 | 0.007011 | # -*- coding: utf-8 -*-
"""
Global tables and re-usable fields
"""
# =============================================================================
# Import models
#
from s3.s3model import S3Model
import eden as models
current.models = models
current.s3db = s3db = S3Model()
# Explicit import statements to have th... | mport eden.hrm
import eden.inv
import eden.irs
import eden.msg
import eden.ocr
import eden.org
| import eden.patient
import eden.pr
import eden.sit
import eden.proc
import eden.project
import eden.req
import eden.scenario
import eden.supply
import eden.support
import eden.survey
import eden.sync
import eden.vehicle
# =============================================================================
# Import S3 meta fi... |
igor-sfdc/qt-wk | doc/src/diagrams/contentspropagation/customwidget.py | Python | lgpl-2.1 | 6,222 | 0.007232 | #!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
## Contact: Nokia Corporation (qt-info@nokia.com)
##
## This file is part of the documentation of the Qt Toolkit.
##
## $QT_... | e = False):
QWidget.__init__(self, parent)
gradient = QLinearGradient(QPointF(0, 0), QPointF(100.0, 100.0))
baseColor = QColor(0xa6, 0xce, 0x39, 0x7f)
grad | ient.setColorAt(0.0, baseColor.light(150))
gradient.setColorAt(0.75, baseColor.light(75))
self.brush = QBrush(gradient)
self.fake = fake
self.fakeBrush = QBrush(Qt.red, Qt.DiagCrossPattern)
qtPath = QPainterPath()
qtPath.setFillRule(Qt.OddEvenFill)
qtPath... |
wizzard/sdk | tests/sync_test_megacli.py | Python | bsd-2-clause | 5,819 | 0.003781 | """
Application for testing syncing algorithm
(c) 2013-2014 by Mega Limited, Wellsford, New Zealand
This file is part of the MEGA SDK - Client Access Engine.
Applications using the MEGA API must present a valid application key
and comply with the the rules set forth in the Terms of Service.
The MEGA SDK is di... | = args.test3 = args.test4 = True
logging.StreamHandler(sys.stdout)
logging.basicConfig(format='[%(asctime)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=lvl)
logging.info("")
logging.info("1) Start the first [megacli] and run the following command: sync " + args.upsync_dir + " [remote folder]")... | older]")
logging.info("3) Wait for both folders get fully synced")
logging.info("4) Run: python %s", sys.argv[0])
logging.info("")
time.sleep(5)
with SyncTestMegaCliApp(args.upsync_dir, args.downsync_dir, args.nodelete, args.large, args.check) as app:
suite = unittest.TestSuite()
i... |
anselmobd/fo2 | src/estoque/queries/grade_estoque.py | Python | mit | 7,421 | 0.000404 | from utils.functions.models import rows_to_dict_list_lower, GradeQtd
def grade_estoque(
cursor, ref=None, dep=None, data_ini=None, tipo_grade=None,
modelo=None, referencia=None):
filtro_modelo = ''
filtro_modelo_mask = ''
if modelo is not None:
filtro_modelo_mask = f'''--
... | (
id='TAMANHO',
name='Tamanho',
total='Total',
forca_total=True,
sql=sql,
)
# cores
if tipo_grade['c'] == 'm': # com movimento
filtro_ref = ''
if ref is not None:
filtro_ref = f"AND ee.GRUPO_ESTRUTURA = '{ref}'"
if modelo is not ... | lo = filtro_modelo_mask.format('ee.GRUPO_ESTRUTURA')
if referencia is not None:
filtro_referencia = filtro_referencia_mask.format('ee.GRUPO_ESTRUTURA')
sql = f'''
SELECT DISTINCT
ee.ITEM_ESTRUTURA SORTIMENTO
FROM ESTQ_300_ESTQ_310 ee -- mov. de estoque e... |
ContinuumIO/dask | dask/array/tests/test_xarray.py | Python | bsd-3-clause | 474 | 0 | import pytest
import dask.array as da
from | ..utils import assert_eq
xr = pytest.importorskip("xarray")
def test_mean():
y = da.mean(xr.DataArray([1, 2, 3.0]))
assert isinstance(y, da.Array)
assert_eq(y, y)
def test_asarray():
y = da.asarray(xr.DataArray([1, 2, 3.0]))
assert isinstance(y, da.Array)
assert_eq(y, y)
def test_asanyar... | y)
|
asnorkin/sentiment_analysis | site/lib/python2.7/site-packages/scipy/special/_precompute/expn_asy.py | Python | mit | 1,585 | 0 | """Precompute the polynomials for the asymptotic expansion of the
generalized exponential integral.
Sources
-------
[1] NIST, Digital Library of Mathematical Functions,
http://dlmf.nist.gov/8.20#ii
"""
from __future__ import division, print_function, absolute_import
import os
import warnings
try:
# Can remo... | x in Ak.coeffs()])
f.write("double A{}[] = {{{}}};\n".format(k, tmp))
tmp = ", ".join(["A{}".format(k) for k in range(K + 1)])
f.write("double *A[] = {{{}}};\n".format(tmp))
tmp = ", ".join([str(Ak.degree()) for Ak in A])
f.write("int Adegs[] = {{{}}} | ;\n".format(tmp))
os.rename(fn + '.new', fn)
if __name__ == "__main__":
main()
|
trosa/forca | applications/admin/languages/pl.py | Python | gpl-2.0 | 15,887 | 0.020455 | # coding: utf8
{
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"Uaktualnij" jest dodatkowym wyrażeniem postaci "pole1=\'nowawartość\'". Nie możesz uaktualnić lub usunąć wyników z JOIN:',
'%Y-%m-%d': '%Y-%m-%d',
'%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%... | Create new simple application': 'Utwórz nową aplikację',
'Current request': 'Aktualne żądanie',
'Current response': 'Aktualna odpowiedź',
'Current session': 'Aktualna sesja',
'DESIGN': 'PROJEKTUJ',
'Date and Time': 'Data i godzina',
'Delete': 'Usuń',
'Delete:': 'Usuń:',
'Deploy on Google App Engine': 'Umieść na Google ... | ycja aplikacji',
'Edit current record': 'Edytuj aktualny rekord',
'Editing Language file': 'Edytuj plik tłumaczeń',
'Editing file': 'Edycja pliku',
'Editing file "%s"': 'Edycja pliku "%s"',
'Enterprise Web Framework': 'Enterprise Web Framework',
'Error logs for "%(app)s"': 'Wpisy błędów dla "%(app)s"',
'Exception insta... |
Jorge-Rodriguez/ansible | lib/ansible/modules/network/f5/bigip_gtm_server.py | Python | gpl-3.0 | 61,691 | 0.001897 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2017, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | ttempt to delete the server will be mad | e.
This will only succeed if this server is not in use by a virtual server.
C(present) creates the server and enables it. If C(enabled), enable the server
if it exists. If C(disabled), create the server if needed, and set state to
C(disabled).
default: present
choices:
- pr... |
slarosa/QGIS | python/plugins/sextante/algs/ftools/ExtentFromLayer.py | Python | gpl-2.0 | 5,976 | 0.002677 | # -*- coding: utf-8 -*-
"""
***************************************************************************
ExtentFromLayer.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
***********************... | ht()
wi | dth = rect.width()
cntx = minx + (width / 2.0)
cnty = miny + (height / 2.0)
area = width * height
perim = (2 * width) + (2 * height)
rect = [QgsPoint(minx, miny),
QgsPoint(minx, maxy),
QgsPoint(maxx, maxy),
... |
pinellolab/haystack_bio | haystack/run_pipeline.py | Python | agpl-3.0 | 14,360 | 0.005292 | from __future__ import division
import os
import sys
import glob
import shutil
import argparse
import multiprocessing
import subprocess as sb
from haystack_common import check_file, HAYSTACK_VERSION
import logging
logging.basicConfig(level=logging.INFO,
format='%(levelname)-5s @ %(asctime)s:\n\t ... | ow', type=float,
help='z-score value to select the not specific regions(default: 0.25)', default=0.25)
parser.add_argument('--th_rpm', type=float,
help='Percentile on the signal intensity to consider for the hotspots (default: 99)',
default=99)... | type=str,
help='Motifs database in MEME format (default JASPAR CORE 2016)')
parser.add_argument('--motif_mapping_filename', type=str,
help='Custom motif to gene mapping file (the default is for JASPAR CORE 2016 database)')
parser.add_argument('--plot_all',
... |
tagn/plex-stack | lib/host.py | Python | gpl-3.0 | 1,728 | 0.001157 | """Module for configuring the host environment"""
import os
import json
import sys
class HostConfig():
"""Sets up the required components on the host environment"""
def __init__(self):
"""Host"""
self.path = None
self.apps = None
def get_path(self):
"""Gets... | lf.path
def get_apps(self):
"""Gets the json file containing app information"""
with open('data/apps.json', 'r') as file:
content = json.load(file)
| self.apps = [app for app in content.get('apps')]
def build(self):
"""Builds folders using the specified path and apps.json"""
print('Building folders...')
for app in self.apps:
try:
app_path = '{}{}'.format(self.path, app.get('name'))
... |
0todd0000/rft1d | rft1d/examples/random_fields_broken_1.py | Python | gpl-3.0 | 862 | 0.018561 |
'''
Broken (piecewise continuous) random field generation using rft1d.randn1d
Note:
When FWHM gets large (2FWHM>nNodes), the data should be padded
using the *pad* keyword.
'''
import numpy as np
from matplotlib import pyplot
import rft1d
#(0) Set parameters:
np.random.seed(12345)
nResponses = 5
nNodes = 1... | s[20:30] = False #this reg | ion will be masked out
nodes[60:80] = False #this region will be masked out
#(1) Generate Gaussian 1D fields:
y = rft1d.randn1d(nResponses, nodes, FWHM)
#(2) Plot:
pyplot.close('all')
pyplot.plot(y.T)
pyplot.plot([0,100], [0,0], 'k:')
pyplot.xlabel('Field position', size=16)
pyplot.ylabel('z', size=20)
p... |
yunity/foodsaving-frontend | cordova/playstoreHelper/publish_to_beta.py | Python | mit | 5,755 | 0.001911 | """Uploads apk to rollout track with user fraction."""
import sys
import socket
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import subprocess
import xml.etree.ElementTree as ET
import os
from pathlib import Path
TRACK = 'beta'
USER_FRACTION = 1
APK_FILE = '... | ACK,
packageName=package_name,
body={
| 'releases': [{
'releaseNotes': [{
'text': releaseText,
'language': 'en-US'
}],
'versionCodes': [apk_response['versionCode']],
'userFraction': USER_FRACTION,
'status': 'inProgress',
}]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.