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 |
|---|---|---|---|---|---|---|---|---|
rodxavier/open-pse-initiative | django_project/jobs/management/commands/update_listed_companies.py | Python | mit | 1,437 | 0.001392 | import logging
from datetime import datetime
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
import requests
from companies.models import Company
logger = logging.getLogger('jobs.management.commands')
class Command(BaseCommand):
help = 'Update currently listed... | x=False)
r = requests.get(settings.COMPANY_LIST_URL)
records = r.json()['records']
for record in records:
symbol = record['securitySymbol']
name = record['securityName']
listing_date = record['listingDate'].split()[0]
status = record['securityStatu... | ompany.id)
except Company.DoesNotExist:
company = Company(symbol=symbol)
company.name = name
company.is_currently_listed = True
company.is_suspended = True if status == 'S' else False
company.listing_date = datetime.strptime(listing_date, '%Y-%... |
qtproject/qt-creator | tests/system/tools/toolfunctions.py | Python | gpl-3.0 | 1,722 | 0.000581 | ############################################################################
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: http | s://www.qt.io/licensing/
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the commercial license agreement provided with the
# Software or, alternatively, in accordance with the terms contained in
# a written agreem... | tps://www.qt.io/contact-us.
#
# GNU General Public License Usage
# Alternatively, this file may be used under the terms of the GNU
# General Public License version 3 as published by the Free Software
# Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
# included in the packaging of this file. Plea... |
tarikgwa/nfd | newfies/dialer_campaign/models.py | Python | mpl-2.0 | 26,728 | 0.003218 | #
# Newfies-Dialer License
# http://www.newfies-dialer.org
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (C) 2011-2014 Star2Billing S.L.
#
# The primar... | delta import relativedelta
import jsonfield
import logging
import re
from .constants import SUBSCRIBER_STATUS, CAMPAIGN_STATUS, AMD_BEHAVIOR
from dialer_contact.constants import CONTACT_STATU | S
from dialer_contact.models import Phonebook, Contact
from dialer_gateway.models import Gateway
from sms.models import Gateway as SMS_Gateway
from dnc.models import DNC
#from agent.models import Agent
logger = logging.getLogger('newfies.filelog')
def build_kwargs_runnning_campaign():
"""Return kwargs configured... |
mitsuhiko/flask | src/flask/config.py | Python | bsd-3-clause | 11,068 | 0.000542 | import errno
import os
import types
import typing as t
from werkzeug.utils import import_string
class ConfigAttribute:
"""Makes an attribute forward to the config"""
def __init__(self, name: str, get_converter: t.Optional[t.Callable] = None) -> None:
self.__name__ = name
self.get_converter =... | :
"""Update the values in the config from a file that is loaded
using the ``load`` parameter. The loaded data is passed to the
:m | eth:`from_mapping` method.
.. code-block:: python
import toml
app.config.from_file("config.toml", load=toml.load)
:param filename: The path to the data file. This can be an
absolute path or relative to the config root path.
:param load: A callable that take... |
gitmill/gitmill | django/repository/models.py | Python | mit | 2,579 | 0.002326 | from django.db import models
from django.contrib.auth.models import User, Group
from django.utils.translation import ugettext_lazy as _
from django.core.validators import RegexValidator
from django.conf import settings
class Repository(models.Model):
"""
Git repository
"""
# basic info
name = mode... | on_delete=models.SET_NULL,
verbose_name=_('user'),
help_text=_('Owner of the repository. Repository path will be prefixed by owner\'s username.'),
)
# access control
users = models.ManyToManyField(
User,
blank=True,
verbose_name=_('users'),
help_text=_(... | =_('Users in these groups have right access to the repository.'),
)
is_private = models.BooleanField(
default=True,
verbose_name=_('is private'),
help_text=_('Restrict read access to specified users and groups.'),
)
# meta
created = models.DateTimeField(auto_now_add=True, v... |
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/cherrypy/cherrypy/lib/xmlrpcutil.py | Python | bsd-3-clause | 1,606 | 0.002491 | import sys
import cherrypy
fro | m cherrypy._cpcompat import ntob
def get_xmlrpclib():
try:
import xmlrpc.client as x
except ImportError:
import xmlrpclib as x
return x
def process_body():
"""Retu | rn (params, method) from request body."""
try:
return get_xmlrpclib().loads(cherrypy.request.body.read())
except Exception:
return ('ERROR PARAMS', ), 'ERRORMETHOD'
def patched_path(path):
"""Return 'path', doctored for RPC."""
if not path.endswith('/'):
path += '/'
if path... |
goodfeli/pylearn2 | pylearn2/models/mlp.py | Python | bsd-3-clause | 166,284 | 0 | """
Multilayer Perceptron
"""
__authors__ = "Ian Goodfellow"
__copyright__ = "Copyright 2012-2013, Universite de Montreal"
__credits__ = ["Ian Goodfellow", "David Warde-Farley"]
__license__ = "3-clause BSD"
__maintainer__ = "LISA Lab"
import logging
import math
import operator
import sys
import warnings
import numpy ... | to do this. Really the
# python interpreter should provide an option to raise the error
# precisely when you're going to exceed the stack segment.
sys.setrecursionlimit(40000)
if six.PY3:
LayerBase = six.with_metaclass(RNNWrapper, Model)
else:
LayerBase = Model
cla | ss Layer(LayerBase):
"""
Abstract class. A Layer of an MLP.
May only belong to one MLP.
Parameters
----------
kwargs : dict
Passed on to the superclass.
Notes
-----
This is not currently a Block because as far as I know the Block interface
assumes every input is a sin... |
alirizakeles/tendenci | tendenci/apps/payments/payflowlink/urls.py | Python | gpl-3.0 | 243 | 0.00823 | from django.conf.ur | ls import *
urlpatterns = patterns('tendenci.apps.payments.payflowlink.views',
url(r'^thankyou/$', 'thank_you', name="payflowlink.thank_you"),
url(r'^silentpost/', 'silent_post', name="payflowlink.silent_post"),
) | |
bluecap-se/yarr.client | tests/conftest.py | Python | mit | 161 | 0 | # -*- coding: utf-8 -*-
import pytes | t
from yarr_client.app import configurate_app
@pytest.fixture
def app():
app, _, | _ = configurate_app()
return app
|
ydkhatri/mac_apt | plugins/helpers/hfs_alt.py | Python | mit | 22,333 | 0.006358 |
'''
Copyright 2011 Jean-Baptiste B'edrune, Jean Sigwald
Using New BSD License:
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditio... | , fileID)
block0 = self.r | eadBlock(0)
self.compression_type = compression_type
self.uncompressed_size = uncompressed_size
if compression_type in [8, 12]: # 8 is lzvn, 12 is lzfse
#only tested for 8
self.header = HFSPlusCmpfLZVNRsrcHead.parse(block0)
#print(self.header)
else:
... |
plotly/python-api | packages/python/plotly/plotly/validators/scatter3d/marker/line/_cmin.py | Python | mit | 533 | 0 | import _plotly_utils.basevalidators
class CminValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="cmin", parent_name="scatter3d.marker.line", **kwargs
):
supe | r(CminValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
implied_edits=kwargs.pop("implied_edits", {"cauto": False}),
role=kwargs.pop("role", "info"),
**kwar | gs
)
|
MartinHjelmare/home-assistant | homeassistant/components/deconz/gateway.py | Python | apache-2.0 | 8,357 | 0 | """Representation of a deCONZ gateway."""
import asyncio
import async_timeout
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.const import CONF_EVENT, CONF_HOST, CONF_ID
from homeassistant.core import EventOrigin, callback
from homeassistant.helpers import aiohttp_client
from homeassistant.... | for component in SUPPORTED_PLATFORMS:
await self.hass.config_entries.async_forward_entry_unload(
self.config_entry, component)
for unsub_dispatcher in self.listeners:
unsub_dispatcher()
self.listeners = []
for event in self.events:
event.as... | deconz_ids = {}
return True
async def get_gateway(hass, config, async_add_device_callback,
async_connection_status_callback):
"""Create a gateway object and verify configuration."""
from pydeconz import DeconzSession, errors
session = aiohttp_client.async_get_clientsession(h... |
mwhooker/jones | tests/__init__.py | Python | apache-2.0 | 532 | 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
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.
"""
|
blitzmann/Pyfa | gui/fitCommands/calc/fitRemoveBooster.py | Python | gpl-3.0 | 849 | 0.002356 | import wx
import eos.db
from logbook import Logger
pyfalog = Logger(__name__)
class FitRemoveBoosterCommand(wx.Command):
""""
from sFit.removeBooster
"""
def __init__(self, fitID, position):
wx.Command.__init__(self, True, "Implant remove")
self.fitID = fitID
self.position = po... | n
self.old = None
def Do(self):
pyfalog.debug("Removing booster from position ({0}) for fit ID: {1}", self.position, self.fitID)
fit = eos.db.getFit(self.fitID)
booster = fit.boosters[self.position]
self.old = booster.itemID
fit.boosters.remove(booster)
retu... | mand(self.fitID, self.old)
cmd.Do()
return True
|
mnot/redbot | redbot/message/cache.py | Python | mit | 29,383 | 0.004016 | #!/usr/bin/env python
"""
Cacheability checking function.
"""
from redbot.formatter import relative_time, f_num
from redbot.message import HttpRequest, HttpResponse
from redbot.speak import Note, categories, levels
### configuration
cacheable_methods = ["GET"]
heuristic_cacheable_status = ["200", "203", "206", "300"... | ttpResponse, request: HttpRequest = None) -> None:
"Examine HTTP caching characteristics."
# get header values
lm_hdr = response.parsed_headers.get("last-modified", None)
date_hdr = response.parsed_headers.get("date", None)
expires_hdr = response.parsed_headers.get("expires", None)
etag_hdr = r... | v) in cc_set]
cc_dict = dict(cc_set)
cc_keys = list(cc_dict.keys())
# Last-Modified
if lm_hdr:
serv_date = date_hdr or response.start_time
if lm_hdr > serv_date:
response.add_note("header-last-modified", LM_FUTURE)
else:
response.add_note(
... |
Juniper/neutron | neutron/db/loadbalancer/loadbalancer_db.py | Python | apache-2.0 | 34,064 | 0.000059 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2013 OpenStack Foundation. 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.apach... | a.Integer, nullable=False)
protocol = sa.Column(sa.Enum("HTTP", "HTTPS", "TCP", name="lb_protocols"),
nullable=False)
pool_id = sa.Column(sa.String(36), nullable=False, unique=True)
session_persistence = orm.relationship(SessionPersistence,
| uselist=False,
backref="vips",
cascade="all, delete-orphan")
admin_state_up = sa.Column(sa.Boolean(), nullable=False)
connection_limit = sa.Column(sa.Integer)
port = orm.relationship(models_v2.Port)
... |
TinyOS-Camp/DDEA-DEV | [Python]Collection/retrieve_weather.py | Python | gpl-2.0 | 6,690 | 0.009716 | #!/adsc/DDEA_PROTO/bin/python
"""
@author: NGO Quang Minh Khiem
@contact: khiem.ngo@adsc.com.sg
"""
import urllib
import urllib2
from datetime import *
from pathos.multiprocessing import ProcessingPool
import pathos.multiprocessing as pmp
from toolset import dill_save_obj
airport_codes = {
'SDH' : ... | e the weather data, given the site code,
# the history view type, and the time period
# Return the data from server (text), in CSV format
# site_code: SDH, VTT, GValley, SG
# view: history view type: 'd' (day), 'w' (week), 'm' (month), 'custom'
# sy, sm, sd: start year/month/day
# view='d': retrieve hourly weather dat... | uring the month of sy/sm/sd
#
# view='custom': retrieve daily weather data from sy/sm/sd to ey/em/ed
# if view='custom': the parameters ey,em,ed should be specified
############
def retrieve_data_package(site_code, sy, sm, sd, view='d', ey=2014, em=12, ed=31):
# ## construct url based on the parameters
url, va... |
wmanley/stb-tester | tests/preconditions.py | Python | lgpl-2.1 | 276 | 0 | from stbt import press, wait_f | or_match
def checkers_via_gamut():
"""Change input video to "gamut" patterns, then "checker | s" pattern"""
wait_for_match("videotestsrc-redblue.png")
press("gamut")
wait_for_match("videotestsrc-gamut.png")
press("checkers-8")
|
tensorflow/tfx | tfx/experimental/templates/penguin/pipeline/pipeline.py | Python | apache-2.0 | 6,485 | 0.005705 | # Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | ed on statistics and data schema.
example_validator = tfx.components.ExampleValidator( # pylint: disable=unused-variable
stati | stics=statistics_gen.outputs['statistics'],
schema=schema_gen.outputs['schema'])
components.append(example_validator)
# Performs transformations and feature engineering in training and serving.
transform = tfx.components.Transform( # pylint: disable=unused-variable
examples=example_gen.outputs['... |
GeoCat/QGIS | python/plugins/processing/gui/BatchInputSelectionPanel.py | Python | gpl-2.0 | 7,904 | 0.001772 | # -*- coding: utf-8 -*-
"""
***************************************************************************
BatchInputSelectionPanel.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
**************... | _ = '(C) 2012, Victor Olaya'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
from qgis.PyQt.QtCore import pyqtSignal
from qgis.PyQt.QtWidgets import QWidget, QHBoxLayout, QMenu, QPushButton, QLineEdit, QSizePolicy, QAction, QFileDialog
from qgis.PyQt.QtGui i... | QgsProject,
QgsProcessing,
QgsProcessingUtils,
QgsProcessingParameterMultipleLayers,
QgsProcessingParameterRasterLayer,
QgsProcessingParameterDefinition,
QgsProcessingPara... |
dahool/vertaal | versioncontrol/lib/types/filesystem.py | Python | gpl-3.0 | 2,573 | 0.005441 | # -*- coding: utf-8 -*-
"""Copyright (c) 2012 Sergio Gabriel Teves
All rights reserved.
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 ... | rl, folder, branch='', auth=None):
super(FileSystemBrowser, self).__init__(location, url, fol | der, branch, auth)
if self.url.startswith('file://'):
self.url = self.url[7:]
@property
def _remote_location(self):
return os.path.join(self.url, self.branch, self.folder)
def init_repo(self):
logger.debug("init")
self._send_callback(self.cal... |
zeza/gnuradio-rc-testcode | gr-flysky/python/qa_flysky_dumpsync.py | Python | gpl-3.0 | 1,124 | 0.010676 | #!/usr/bin/env python
#
# Copyright 2012 <+YOU OR YOUR COM | PANY+>.
#
# This 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, or (at your option)
# any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ... | 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 software; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
#
from gnu... |
errantlinguist/tangrams-analysis | add_tabular_participant_metadata.py | Python | apache-2.0 | 4,239 | 0.020996 | #!/usr/bin/env python3
"""
Adds participant metadata to a given tabular data file for those sessions.
"""
__author__ = "Todd Shore <errantlinguist+github@gmail.com>"
__copyright__ = "Copyright 2018 Todd Shore"
__license__ = "Apache License, Version 2.0"
import argparse
import csv
import os
import sys
from typing imp... | ticipant metadata to a given tabular data file for those sessions.")
result.add_argument("infile", metavar="INFILE", help="The tabular file to add to.")
result.add_argument("session_dir", metavar="PATH", help="The directory under which the dyad files are to be found.")
return result
def __main(args):
infile = arg... | int("Reading tabular data from \"{}\".".format(infile), file=sys.stderr)
df = read_tabular_data(infile)
session_names = frozenset(df["session"].unique())
print("Read results for {} sessions.".format(len(session_names)), file=sys.stderr)
session_dir = args.session_dir
print("Will look for sessions underneath \"{}\"... |
eclee25/flu-SDI-exploratory-age | scripts/create_fluseverity_figs_v5/ILINet_RR_time_v5.py | Python | mit | 3,186 | 0.016949 | #!/usr/bin/python
##############################################
###Python template
###Author: Elizabeth Lee
###Date: 11/4/14
###Function: RR of incidence in adults to incidence in children vs. week number. Incidence in children and adults is normalized by the size of the child and adult populations in the second cale... | _cdc_source_data.csv','r')
incidin.readline() # remove header
incid = csv.reader(incidin, delimiter=',')
popin = open('/home/elee/Dropbox/Eliz | abeth_Bansal_Lab/Census/Import_Data/totalpop_age_Census_98-14.csv', 'r')
pop = csv.reader(popin, delimiter=',')
### called/local plotting parameters ###
ps = fxn.pseasons
fw = fxn.gp_fluweeks
sl = fxn.gp_ILINet_seasonlabels
colvec = fxn.gp_ILINet_colors
wklab = fxn.gp_weeklabels
fs = 24
fssml = 16
### program ###
# i... |
roninio/gae-boilerplate | boilerplate/routes.py | Python | lgpl-3.0 | 2,607 | 0.008055 | """
Using redirect route instead of simple routes since it supports strict_slash
Simple route: http://webapp-improved.appspot.com/guide/routing.html#simple-routes
RedirectRoute: http://webapp-improved.appspot.com/api/webapp2_extras/routes.html#webapp2_extras.routes.RedirectRoute
"""
from webapp2_extras.routes import R... |
RedirectRoute('/password-reset/', handlers.PasswordResetHandler, name='password-reset', strict_slash=True),
RedirectRoute('/password-reset/<user_id>/<token>', handlers.PasswordResetCompleteHandler, name='password-reset-check', strict_slash=True),
RedirectRoute('/change-email/<user_id>/<encoded_email>/<toke... | RedirectRoute('/', handlers.HomeRequestHandler, name='home', strict_slash=True)
]
def get_routes():
return _routes
def add_routes(app):
if app.debug:
secure_scheme = 'http'
for r in _routes:
app.router.add(r)
|
uclouvain/osis_louvain | base/migrations/0024_documentfile.py | Python | agpl-3.0 | 1,981 | 0.003029 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-03-10 16:10
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
migrations.swappabl... | eld(blank=True, null=True)),
('user', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH | _USER_MODEL)),
],
),
]
|
des-testbed/des_chan_algorithms | dga/dmp.py | Python | gpl-3.0 | 27,779 | 0.011124 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
DGA: Implementation of the Distributed Greedy Algorithm for channel assignment
The DMP class handles the control flow after the initialization of DGA.
Authors: Simon Seif <seif.simon@googlemail.com>,
Felix Juraschek <fjuraschek@gmail.com>
Copyright 2008-... | ambda x:int(x),line.split(","))
except:
log.error("cannot parse assignment string:"+line)
return list()
def parseRequest(line):
"""Parses a request message.
Returns a quadruple containing old_channel,new_channel,re | duction,assignment.
"""
tokens = line.split(DELIMITER)
old_channel = int(tokens[1])
new_channel = int(tokens[2])
reduction = int(tokens[3])
assignment = parseAssignmentString(tokens[4])
return old_channel, new_channel, reduction, assignment
def parseQuery(line):
"""Parses a q... |
eguven/mobai | mobai/engine/game.py | Python | mit | 7,171 | 0.001116 | import enum
import gzip
import pickle
from .base import Player
from .map import Map
class ActionType(enum.Enum):
target = 0
clear_target = 1
stop = 2
class Command(object):
'''a command received from a player
{'id': '<uuid>', 'action': '<action-type>.name', 'target': '<uuid>' | {'posx': X, 'pos... | feedback
dead_units = []
for tile in self.map.tiles():
| dead_units.extend([unit for unit in tile.occupants if unit.health <= 0])
tile.occupants = [unit for unit in tile.occupants if unit.health > 0]
for unit in self.all_units:
if unit.target in dead_units:
unit.clear_target()
def evaluate_turn(self):
''... |
gnowledge/ncert_nroer | demo/urls.py | Python | agpl-3.0 | 9,860 | 0.012069 | # Copyright (c) 2011, 2012 Free Software Foundation
# This program 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 option) any later vers... | rect_to_template, {'template': 'gstudio/contribute_resource.html'}),
url(r'^Ganit/', direct_to_template, {'template': 'gstudio/GanitPoster.html'}),
url(r'^FunWithGeogebra/', direct_to_template, {'template': 'gstudio/FunWithGeogebra.html'}),
url(r'^ExploringMathKits/', direc | t_to_template, {'template': 'gstudio/ExploringMathKits.html'}),
url(r'^GanitMagicSquare/', direct_to_template, {'template': 'gstudio/GanitMagicSquare.html'}),
url(r'^KnowSrinivasa/', direct_to_template, {'template': 'gstudio/KnowSrinivasa.html'}),
url(r'^MoreonMaths/', direct_to_template, {'template': 'gstudio/Moreo... |
openshift-mobile/openshift-mobile-app-demo | wsgi/osmdemo/questionnaire/views.py | Python | gpl-3.0 | 2,536 | 0.039038 | from django.template import RequestContext
from django.shortcuts import render_to_response,get_object_or_404
from django.core.mail import send_mail
from questionnaire.models import *
import re,os
body_template = """
Thank you %s for your sumbission for the %s.
We appreciate your help in improving the OpenShift Mobile... | r | esp = UserQuestionnaire(
email = email,
questionnaire = questionnaire
)
resp.save()
sections = questionnaire.section_set.all()
for section in sections:
questions = section.questions.all()
for question in questions:
if question.name in request.POST:
answer = Answer(
answer ... |
ssorgatem/pulsar | test/pulsar_objectstore_test.py | Python | apache-2.0 | 5,154 | 0.002716 | from os import makedirs
from os.path import join, dirname, exists
from string import Template
from galaxy.util.bunch import Bunch
from galaxy.objectstore import build_object_store_from_config
from .test_utils import TempDirectoryTestCase
from .test_objectstore import MockDataset
class PulsarObjectStoreTest(TempDirec... | assert object_store.exists(empty_dataset)
assert object_store.empty(empty_dataset)
# Write non-empty dataset in backend 1, test it is not emtpy & exists.
hello_world_dataset = MockDataset(3)
self.__write(b"Hello World!", "000/dataset_3.dat")
assert object_... | d_dataset)
assert data == "Hello World!"
data = object_store.get_data(hello_world_dataset, start=1, count=6)
assert data == "ello W"
# Test Size
# Test absent and empty datasets yield size of 0.
assert object_store.size(absent_dataset) == 0
... |
priscillaboyd/SPaT_Prediction | src/decision_tree/DT_Utils.py | Python | apache-2.0 | 3,533 | 0.000566 | # Copyright 2017 Priscilla Boyd. 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 ... | '/plot_' + model_name + '.png'
plt.savefig(plot_path)
print("Plot saved location:", plot_path)
def save_dt_model(model_name, model, | folder):
"""
Save model using Pickle binary format.
:param dataframe model: model reference
:param string model_name: title for the model used on the output filename
:param string folder: location of model output
"""
print("Saving model...")
model_file = folder + '/models/' + model_name... |
kevinzhou96/CascadingFailureSimulation | rescale_power.py | Python | gpl-3.0 | 2,340 | 0.00641 | import pypower.api as pp
import networkx as nx
import numpy as np
import copy
import pypower.idx_brch as idx_brch
import pypower.idx_bus as idx_bus
import pypower.idx_gen as idx_gen
def rescale_power_down(ppc):
"""Rescales power generation or load within a component uniformly among all
buses to balance genera... | n(ppc):
"""Rescales power generation only (not load) within a component uniformly
among all buses to match load. If total generation is zero, we cannot fulfill
the load and so load is set to 0.
ARGUMENTS: ppc: dict (representing a PYPOWER case file)
RETURNS: None (does in-place update of ppc)
... | = np.array(list(filter(genInComponent, ppc['gen'])))
total_gen = sum(component_generators[:, idx_gen.PG]) if len(component_generators)>0 else 0
total_load = sum(ppc['bus'][:, idx_bus.PD])
if np.isclose(total_gen, 0):
# no power generated, set loads to zero
ppc['bus'][:, idx_bus.PD] = np.z... |
lawzou/shoop | shoop/admin/modules/methods/views/edit_detail.py | Python | agpl-3.0 | 1,471 | 0.00068 | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
import six
from django.utils.transl... | :
raise Problem("Module %s has no admin detail vi | ew" % module.name)
if isinstance(module.admin_detail_view_class, six.text_type):
view_class = load(module.admin_detail_view_class)
else:
view_class = module.admin_detail_view_class
kwargs["object"] = object
return view_class(model=self.model).dispatch(request, *ar... |
tmbdev/clstm | display_server.py | Python | apache-2.0 | 819 | 0.015873 | import os
import numpy
from pylab import *
import traceback
import zmq
context = zmq.Context()
socket = context.socket(zmq.REP)
addr = os.envir | on.get("PYSERVER","tcp://127.0.0.1:9876")
socket.bind(addr)
poller = zmq.Poller()
poller.register(socket, zmq.POLLIN)
def farg(index):
global args
return numpy.fromstring(args[index],dtype=float32)
def farg2(index,d0,d1):
global args
return numpy.fromstring(args[index],dtype=float32).res | hape(d0,d1)
while True:
while True:
evts = poller.poll(100)
if evts!=[]: break
ginput(1,0.01)
args = socket.recv_multipart()
print "----------------"
print args[0]
result = None
try:
exec args[0]
except Exception,e:
print "FAILED"
traceback.pr... |
OpenSeizureDetector/ESP8266_SD | monitor.py | Python | gpl-3.0 | 516 | 0.001938 | #!/usr/bin/python
#
# Simple script to echo the ttyUSB0 serial port to the console at 74880 baud.
# Based on http://www.esp8266.com/viewtopic.php?p=33650.
# I found it really really hard to do using standard tools like cu...
# By doing ./monitory. | py and resetting the esp8226 (while it is connected
# via USB) you can see the boot up messages and anything you 'printf'
# to stdout.
#
import sys
from serial import Serial
dev = Serial("/dev/ttyUSB0", 74880 | )
while True:
c = dev.read(1)
sys.stdout.write(c)
|
vileopratama/vitech | src/addons/purchase/tests/test_onchange_product_id.py | Python | mit | 3,448 | 0.00348 | from datetime import datetime
from openerp.tests.common import TransactionCase
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
class TestOnchangeProductId(TransactionCase):
"""Test that when an included tax is mapped by a fiscal position, the included tax must be
subtracted to the price of the product... | supplier_taxes_id=[(6, 0, [tax_include_id.id])]))
product_id = self.product_model.crea | te(dict(product_tmpl_id=product_tmpl_id.id))
fp_id = self.fiscal_position_model.create(dict(name="fiscal position", sequence=1))
fp_tax_id = self.fiscal_position_tax_model.create(dict(position_id=fp_id.id,
tax_src_id=tax_include_id.id,
... |
therealjumbo/python_summer | py31eg/grepword-m.py | Python | gpl-3.0 | 4,049 | 0.00247 | #!/usr/bin/env python3
# Copyright (c) 2008-11 Qtrac Ltd. All rights reserved.
# This program or module 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... | help=("the number of processes to use (1..20) "
"[default %default]"))
parser.add_option("-r", "--recurse", dest="recurse",
default=False, action="store_true",
help="recurse into subdirectories")
parser.add_option("-d", "--debug", dest="debug", default=False,
... | gs) == 1:
parser.error("at least one path must be specified")
if (not opts.recurse and
not any([os.path.isfile(arg) for arg in args])):
parser.error("at least one file must be specified; or use -r")
if not (1 <= opts.count <= 20):
parser.error("process count must be 1..20")
r... |
Snaipe/Tequila | tequila/server/group/exception.py | Python | gpl-3.0 | 1,272 | 0.000786 | """
Tequila: a command-line Minecraft server manager written in python
Copyr | ight (C) 2014 Snaipe
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 b | e 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, see <http://www.gnu.org/licenses/>.
"""... |
citrix-openstack-build/cliff | cliff/tests/test_commandmanager.py | Python | apache-2.0 | 3,511 | 0 |
import mock
from cliff.commandmanager import CommandManager
class TestCommand(object):
@classmethod
def load(cls):
return cls
def __init__(self):
return
class TestCommandManager(CommandManager):
def _load_commands(self):
self.commands = {
'one': TestCommand,
... | expected a failure'
def test_add_command():
mgr = TestCommandManager('test')
mock_cmd = mock.Mock()
mgr.add_command('mock', mock_cmd)
found_cmd, name, args = mgr.find_command(['mock'])
assert found_cmd is mock_cmd
def test_load_commands():
testcm | d = mock.Mock(name='testcmd')
testcmd.name.replace.return_value = 'test'
mock_pkg_resources = mock.Mock(return_value=[testcmd])
with mock.patch('pkg_resources.iter_entry_points',
mock_pkg_resources) as iter_entry_points:
mgr = CommandManager('test')
assert iter_entry_poin... |
AndersenLab/cegwas-web | base/views/api/api_docs.py | Python | mit | 370 | 0.002703 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Author: Daniel E. Cook
Handles redirecting the user to the API Documentation.
"""
from base | .application import app
from flask import send_from_directory
@app.route("/data/api/docs/")
@app.route("/data/api/docs/<path:path>")
def docs(path="index.html"):
return send_ | from_directory('../cendr-api-docs/docs/', path)
|
Comunitea/CMNT_004_15 | project-addons/purchase_picking/models/stock.py | Python | agpl-3.0 | 14,639 | 0.002528 | ##############################################################################
#
# Copyright (C) 2014 Pexego Sistemas Informáticos All Rights Reserved
# $Jesús Ventosinos Mayor <jesus@pexego.es>$
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero ... | in self:
if container.eta:
container.set_eta = True
@api.multi
@api.depends('date_expected')
def _set_date_exp(self):
for container in self:
if container.date_expected:
container.set_date_exp = True
@api.multi
@api.depends('move_... | rrived = False
if container.picking_ids and all(pick_state == 'done' for pick_state in container.picking_ids.mapped('state')):
container.arrived = True
@api.multi
def _set_date_expected(self):
for container in self:
if container.move_ids:
date_exp... |
SUSE-Cloud/nova | nova/tests/api/openstack/compute/contrib/test_aggregates.py | Python | apache-2.0 | 18,885 | 0.000688 | # Copyright (c) 2012 Citrix Systems, 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 ... | stub_create_aggregate)
result = self.controller.create(self.req, {"aggregate":
{"name": "test",
"ava | ilability_zone": "nova1"}})
self.assertEqual(AGGREGATE, result["aggregate"])
def test_create_with_duplicate_aggregate_name(self):
def stub_create_aggregate(context, name, availability_zone):
raise exception.AggregateNameExists(aggregate_name=name)
self.stubs.Set(self.controller.... |
brad999/nikita | client/modules/Gmail.py | Python | mit | 3,834 | 0 | # -*- coding: utf-8-*-
import imaplib
import email
import re
from dateutil import parser
WORDS = ["EMAIL", "INBOX"]
def getSender(email):
"""
Returns the best-guess sender of an email.
Arguments:
email -- the email whose sender is desired
Returns:
Sender of the email.
... | the user (for both input and output)
profile -- contains information related to the user (e.g., Gmail
address)
"""
try:
msgs = fetchUnreadEmails(profile, limit=5)
if isinstance(msgs, int):
response = "You have %d unread emails." % msgs
mic.say(... | ers = [getSender(e) for e in msgs]
except imaplib.IMAP4.error:
mic.say('A', "I'm sorry. I'm not authenticated " +
"to work with your Gmail.")
return
if not senders:
mic.say('A', "You have no unread emails.")
elif len(senders) == 1:
mic.say('I', "You have one ... |
ESultanik/ZoningMaps | intersect_maps.py | Python | gpl-3.0 | 10,096 | 0.00733 | import bisect
import json
import progress
import zoning
def calculate_stream_size(stream):
old_pos = stream.tell()
stream.seek(0, 2)
size = f.tell()
stream.seek(old_pos, 0)
return size
class NullFeatures(object):
def __init__(self, map1_len, map2_len):
self._mapping = map1_len * map2_l... | map2[i] = state[0]
if state | [1] is not None:
map2.append(state[1])
map1[n] = state[2]
estimator.increment()
if map1[n].geometry.is_empty:
estimator.increment(len(map2) - i)
break
continue
... |
mlowen/Pyke | pyke/meta.py | Python | mit | 2,310 | 0.040693 | import json
import os.path
from hashlib import md5
class TargetFile:
def __init__(self, p | ath, data = None):
self.path = path
self.hash = None
self.dependencies = {}
if data is not None:
self.hash = data['hash']
self.dependencies = data['dependencies']
def raw(self):
return {
'hash': self.hash,
'dependencies': self.dependencies
}
def clean(self):
self.hash = None
for depend... | md5(open(self.path, 'rb').read()).hexdigest()
if self.hash is None or self.hash != computed_hash:
changed = True
self.hash = computed_hash
# File Dependencies
for dependency in self.dependencies:
stored_hash = self.dependencies[dependency]
computed_hash = md5(open(dependency, 'rb').read()).hexd... |
dieseldev/diesel | examples/newwait.py | Python | bsd-3-clause | 530 | 0.00566 | import random
from diesel import quickstart, first, sleep, fork
from diesel.util.queue import Queue
def fire_random(queues):
while True:
sleep(1)
random.choice(queues).put(None)
def m | ake_and_wait():
q1 = Queue()
q2 = Queue()
both = [q1, q2]
fork(fire_random, both)
while True:
q, v = first(waits=both)
assert v is None
if q == q1:
print 'q1'
elif q == q2:
print 'q2'
else:
ass | ert 0
quickstart(make_and_wait)
|
kbarbary/sncosmo | sncosmo/tests/test_magsystems.py | Python | bsd-3-clause | 2,223 | 0 | # Licensed under a 3-clause BSD style license - see LICENSES
import math
import numpy as np
import pytest
from astropy import units as u
from numpy.testing import assert_allclose, assert_almost_equal
import sncosmo
def test_abmagsystem():
magsys = sncosmo.ABMagSystem()
m = magsys.band_flux_to_mag(1.0, 'bes... | phd": 13.502}
# The "zero point bandflux" should be the flux that corresponds to
# magnitude zero. So, 0 = zp - 2.5 log(F)
for band, zp in zps.items():
assert abs(2.5 * math.l | og10(csp.zpbandflux(band)) - zp) < 0.015
@pytest.mark.might_download
def test_compositemagsystem_band_error():
"""Test that CompositeMagSystem raises an error when band is
not in system."""
csp = sncosmo.get_magsystem('csp')
with pytest.raises(ValueError):
csp.zpbandflux('desi')
|
mecforlove/oj-web | app/utils/__init__.py | Python | apache-2.0 | 61 | 0 | #!/usr/bin/env | python
# -*- coding: utf-8 -*-
# @Author: mec
| |
ArtemBernatskyy/FundExpert.NET | mutual_funds/registration/forms.py | Python | gpl-3.0 | 4,680 | 0.001709 | """
Forms and validation code for user registration.
Note that all of these forms assume Django's bundle default ``User``
model; since it's not possible for a form to anticipate in advance the
needs of custom user models, you will need to write your own forms if
you're using a custom model.
"""
from __future__ import... | erately
useful for preventing automated spam registrati | ons.
To change the list of banned domains, subclass this form and
override the attribute ``bad_domains``.
"""
bad_domains = ['aim.com', 'aol.com', 'email.com', 'gmail.com',
'googlemail.com', 'hotmail.com', 'hushmail.com',
'msn.com', 'mail.ru', 'mailinator.com', 'l... |
ESS-LLP/erpnext | erpnext/healthcare/doctype/healthcare_service_order_priority/test_healthcare_service_order_priority.py | Python | gpl-3.0 | 232 | 0.008621 | # -*- coding: | utf-8 -*-
# Copyright (c) 20 | 20, earthians and Contributors
# See license.txt
from __future__ import unicode_literals
# import frappe
import unittest
class TestHealthcareServiceOrderPriority(unittest.TestCase):
pass
|
nielsole/ycombinator_newsletter | code/crawl.py | Python | mit | 916 | 0.004367 | #!/usr/bin/env python3
import requests
from database import is_in_db
import database
__author__ = 'flshrmb'
def handle(some_story, conn):
cursor = conn.cursor()
database.insert(some_story, cursor)
cursor.close()
conn.commit()
def main():
top_list = requests.get('https://hacker-news.firebaseio.co... | dd exception?
top_json = top_list.json()
conn = database.get | _con()
cur = conn.cursor()
database.create_table(cur)
cur.close()
for i, id in enumerate(top_json):
story_request = requests.get('https://hacker-news.firebaseio.com/v0/item/{0}.json'.format(id))
if story_request.status_code != 200:
continue
handle(story_request.json()... |
suutari-ai/shoop | shuup_tests/default_reports/test_default_reports.py | Python | agpl-3.0 | 36,452 | 0.002826 | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
import json
import random... | fo.product_count
assert int(return_data.get("product_count", 0)) == test_info.product_count
assert int(totals.get("order_count", 0)) == 1
assert int(return_data.get("order_count", 0)) == 1
assert str(test_info.expected_taxless_total) in totals.get("taxless_total", "0")
assert str(test_info.expected_... | ("taxful_total", "0")
@pytest.mark.django_db
def test_total_sales_report(rf):
test_info = initialize_simple_report(TotalSales)
assert force_text(TotalSales.title) in test_info.json_data.get("heading")
return_data = test_info.json_data.get("tables")[0].get("data")[0]
assert return_data.get("currency") ... |
zde/librepo | tests/python/tests/test_yum_repo_downloading.py | Python | gpl-2.0 | 58,125 | 0.003802 | from tests.base import TestCaseWithFlask, MOCKURL, TEST_DATA
from tests.servermock.server import app
import tests.servermock.yum_mock.config as config
import os.path
import unittest
import tempfile
import shutil
import gpgme
import librepo
PUB_KEY = TEST_DATA+"/key.pub"
class TestCaseYumRepoDownloading(TestCaseWithFl... | 9c6b7b605b2bc66852630c841a5003603ca5b2',
'checksum_open_type': 'sha1',
'checksum_type': 'sha1',
'db_version': 10,
'location_href': 'repodata/4034dcea76c94d3f7a9616779539a4ea8cac288f-filelists.sqlite.b | z2',
'size': 22575,
'size_open': 201728,
'timestamp': 1347459931},
#'group': None,
#'group_gz': None,
#'origin': None,
'other': {
'checksum': 'a8977cdaa0b14321d9acfab81ce8a85e8... |
SciTools/iris | lib/iris/tests/unit/fileformats/pp/test__interpret_field.py | Python | lgpl-3.0 | 5,255 | 0 | # Copyright Iris contributors
#
# This file is part of Iris and is released under the LGPL license.
# See COPYING and COPYING.LESSER in the root of the repository for full
# licensing details.
"""Unit tests for the `iris.fileformats.pp._interpret_field` function."""
# Import iris.tests first so that some things can be... | .format(warn_msg),
)
def test_deferred_mask_field(self):
# Check that the order of the load is yielded last if the mask
# hasn't yet been seen.
result = list(
pp._interpret_fields([self.pp_field, self | .land_mask_field])
)
self.assertEqual(result, [self.land_mask_field, self.pp_field])
def test_not_deferred_mask_field(self):
# Check that the order of the load is unchanged if a land mask
# has already been seen.
f1, mask = self.pp_field, self.land_mask_field
mask2 =... |
GoelDeepak/dcos | packages/dcos-integration-test/extra/test_meta.py | Python | apache-2.0 | 3,623 | 0.000552 | """
Tests for the integration test suite itself.
"""
import logging
import os
import subprocess
from collections import defaultdict
from pathlib import Path
from typing import Set
import yaml
from get_test_group import patterns_from_group
__maintainer__ = 'adam'
__contact__ = 'tools-infra-team@mesosphere.io'
log =... | assert len(patterns) != 1, message
errs.append(message)
if errs:
for message in errs:
log.error(message)
| raise Exception("Some tests are not collected exactly once, see errors.")
all_tests = _tests_from_pattern(ci_pattern='')
assert tests_to_patterns.keys() - all_tests == set()
assert all_tests - tests_to_patterns.keys() == set()
|
anhstudios/swganh | data/scripts/templates/object/draft_schematic/armor/component/shared_heavy_armor_layer_environmental.py | Python | mit | 476 | 0.046218 | #### 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 = Intangib | le()
result.template = "object/draft_schemat | ic/armor/component/shared_heavy_armor_layer_environmental.iff"
result.attribute_template_id = -1
result.stfName("string_id_table","")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
kashifiqb/Aspose.Email-for-Java | Plugins/Aspose.Email Java for Python/tests/ProgrammingOutlook/AddMapiJournalToPST/AddMapiJournalToPST.py | Python | mit | 672 | 0.00744 | # To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the | template in the editor.
#if __name__ == "__main__":
# print "Hello World"
from ProgrammingOutlook import AddMapiJournalToPST
import jpype
import os.path
asposeapispath = os.path.join(os.path.abspath("./../../../"), "lib/")
dataDir = os.path.join(os.path.abspath("./"), "data/")
print "You need to put your Aspose.... | PST(dataDir)
hw.main() |
nejucomo/preconditions | tests.py | Python | mit | 7,012 | 0.000143 | from unittest import TestCase, main
from preconditions import PreconditionError, preconditions
class PreconditionTestBase (TestCase):
def assertPreconditionFails(self, target, *args, **kw):
self.assertRaises(PreconditionError, target, *args, **kw)
def assertPreconditionFailsRegexp(self, rgx, target,... | ndition failed in call ' +
r'<function f at 0x[0-9a-fA-F]+>\(x=7\):\n' +
r' @preconditions\(lambda x: x != 7\)\n$'),
f,
7)
def test_multiple_line_multiple_predicates_includes_specific_source(self):
@preconditions(
lambda x: x > 0,
l... | )
def f(x):
return x
self.assertPreconditionFailsRegexp(
(r'Precondition failed in call ' +
r'<function f at 0x[0-9a-fA-F]+>\(x=6\.5\):\n' +
r' lambda x: isinstance\(x, int\),\n$'),
f,
6.5)
if __name__ == '__main__':
... |
wbond/certvalidator | certvalidator/path.py | Python | mit | 6,777 | 0.000738 | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
from asn1crypto import pem, x509
from ._errors import pretty_message
from ._types import byte_cls, type_name
from .errors import DuplicateCertificateError
class ValidationPath():
"""
Represents a path going to... | must be a byte string or an
asn1crypto.x509.Certificate object, not %s
''',
type_name(cert)
))
if pem.detect(cert):
_, | _, cert = pem.unarmor(cert)
cert = x509.Certificate.load(cert)
if cert.issuer_serial in self._cert_hashes:
raise DuplicateCertificateError()
self._cert_hashes.add(cert.issuer_serial)
self._certs.insert(0, cert)
return self
def __len__(self):
retur... |
paradisessssspee/nlptools | tests/context.py | Python | gpl-3.0 | 174 | 0.017241 | """use __file__ to determine library path
"""
impor | t sys
import o | s
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import language_model |
jessicalucci/NovaOrc | nova/openstack/common/processutils.py | Python | apache-2.0 | 5,488 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack Foundation
# 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.apach... | tError(_('Got unknown keyword args '
'to utils.execute: %r') % kwargs)
if run_as_root:
cmd = shlex.split(root_helper) + list(cmd)
cmd = map(str, cmd)
while attempts > 0:
attempts -= 1
try:
LOG.debug(_('Running cmd (subprocess): %s'), ... | ess.Popen(cmd,
stdin=_PIPE,
stdout=_PIPE,
stderr=_PIPE,
close_fds=True)
result = None
if process_input is not None:
result = obj.communicate... |
esenti/ld-poznan | ldpoznan/core/urls.py | Python | mit | 160 | 0.0125 | from django.conf.urls import patterns, url
from d | jango.conf import settings
import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
| )
|
yamrock/confcentral | settings.py | Python | apache-2.0 | 495 | 0.00202 | #!/usr/bin/env python
"""settings.py
Udacity conference server-side Pytho | n App Engine app user settings
$Id$
created/forked f | rom conference.py by wesc on 2014 may 24
"""
# Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = '942213791788-amreps3i4mdhv6d646ufm82t1jhqgn8j.apps.googleusercontent.com'
ANDROID_CLIENT_ID = 'replace with Android client ID'
IOS_CLIENT_ID = 'replace with iO... |
LLNL/spack | var/spack/repos/builtin/packages/vpic/package.py | Python | lgpl-2.1 | 1,121 | 0.000892 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Vpic(CMakePackage):
"""VPIC is a general purpose particle-in-cell simulation code for mod... | leapfrog algorithm to update charged particle
positions and velocities in order to solve the relativistic kinetic
equation for each species in the plasma, along with a full Maxwell
description f | or the electric and magnetic fields evolved via a second-
order finite-difference-time-domain (FDTD) solve.
"""
homepage = "https://github.com/lanl/vpic"
git = "https://github.com/lanl/vpic.git"
version('develop', branch='master', submodules=True)
depends_on("cmake@3.1:", type='build')... |
Ins1ne/smyt | manage.py | Python | mit | 253 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "smyt.settings.local")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) | ||
mncoon/odoo-addons | syscoon_finance_export/wizard/move_export.py | Python | lgpl-3.0 | 748 | 0.004011 | from openerp import models, api, _
from openerp.exceptions import UserError
class ExportMoveExport(models.TransientModel):
_name = 'export.move.export'
_description = 'Export Moves'
@api.multi
def create_export_file(self):
context = dict(self._context or {})
moves = self.env['export.mo... | ate_export_file()
return {'type': 'ir.actions.act_window_cl | ose'}
|
andresgz/zshoes | zshoes/articles/views.py | Python | bsd-3-clause | 1,444 | 0 | from django.contrib import messages
from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from django.views.generic import ListView, CreateView, UpdateView
from .models import Article
class ArticleListView(ListView):
"""
View to list all the articles
""... | orm.cleaned_data['name'])))
return super(ArticleCreateView, self).form_valid(form)
class ArticleUpdateView(UpdateView):
"""
View to update a Article
"""
model = Article
fields = ['name', 'store', 'description', 'price',
'total_in_shelf', 'total_in_vault']
template_name = ... | messages.success(
self.request,
_('Article {0} updated'.format(form.cleaned_data['name'])))
return super(ArticleUpdateView, self).form_valid(form)
|
tellproject/helper_scripts | hive.py | Python | apache-2.0 | 3,067 | 0.013694 | #!/usr/bin/env python
import os
import sys
import time
from ServerConfig import General
from ServerConfig import Hadoop
from ServerConfig import Hive
xmlProp = lambda key, value: "<property><name>" + key +"</name><value>" + value + "</value></property>\n"
concatStr = lambda servers, sep: sep.join(servers)
def copy... | top_hivems_cmd, Hive.master)
os.system('ssh -A root@{0} {1}'.format(Hive.master, stop_hivems_cmd))
# hiveserver
stop_hiveserver_cmd = "ps -a | grep HiverServer2 | grep -v grep | awk '{print $2}' | xargs kill -9"
os.system('ssh -A root@{0} {1}'.format(Hive.master, stop_hiveserver_cmd))
print "{1} : {... | (argv[0] == 'start')):
confMaster()
startHive()
elif ((len(argv) == 1) and (argv[0] == 'stop')):
stopHive()
else:
print "Usage: <start|stop> Default: start"
if __name__ == "__main__":
main(sys.argv[1:])
|
KevinHock/rtdpyt | profiling/test_projects/flaskbb_lite_3/flaskbb/utils/fields.py | Python | gpl-2.0 | 1,093 | 0 | # -*- coding: utf-8 -*-
"""
flaskbb.utils.fields
~~~~~~~~~~~~~~~~~~~~
Additional fields for wtforms
:copyright: (c) 2014 by the FlaskBB Team.
:license: BSD, see LICENSE for more details.
"""
from datetime import datetime
from wtforms.fields import DateField
class Birthd | ayField(DateField):
"""Same as DateField, except it allows ``None`` values in case a user
wants to delete his birthday.
"""
def __init__(self, label=None, validators=None, format='%Y-%m-%d',
** | kwargs):
DateField.__init__(self, label, validators, format, **kwargs)
def process_formdata(self, valuelist):
if valuelist:
date_str = ' '.join(valuelist)
try:
self.data = datetime.strptime(date_str, self.format).date()
except ValueError:
... |
dougnd/matplotlib2tikz | test/testfunctions/quadmesh.py | Python | mit | 840 | 0 | # -*- coding: utf-8 -*-
#
desc = 'Plot Taylor--Green Vortex using pcolormesh'
# phash = 'ff1a8578c9847b22'
phash = '7f1a8578c9857932' |
def plot():
from matplotlib import pyplot as plt
import numpy as np
x = np.linspace(0*np.pi, 2*np.pi, 128)
y = np.linspace(0*np.pi, 2*np.pi, 128)
X, Y = np.meshgrid(x, y)
nu = 1e-5
def F(t):
retu | rn np.exp(-2*nu*t)
def u(x, y, t):
return np.sin(x)*np.cos(y)*F(t)
def v(x, y, t):
return -np.cos(x)*np.sin(y)*F(t)
fig, axs = plt.subplots(2, figsize=(8, 12))
axs[0].pcolormesh(X, Y, u(X, Y, 0))
axs[1].pcolormesh(X, Y, v(X, Y, 0))
for ax in axs:
ax.set_xlim(x[0], x[-1... |
jrbl/pygitplay | pygitplay.py | Python | gpl-3.0 | 87 | 0.011494 | #!/usr/bin/env pytho | n
# -*- coding: utf-8 -*-
"""Throwaway where I play with | pygit"""
|
aweber/test-helpers | tests/integration/test_mongo.py | Python | bsd-3-clause | 2,050 | 0.000488 | from __future__ import absolute_import
import os
from pymongo import MongoClient
from test_helpers import bases, mixins, mongo
class WhenCreatingTemporaryDatabase(bases.BaseTest):
@classmethod
def configure(cls):
super(WhenCreatingTemporaryDatabase, cls).configure()
cls.database = mongo.Te... | E'], self.database. | database_name)
|
staranjeet/fjord | vendor/packages/translate-toolkit/translate/misc/autoencode.py | Python | bsd-3-clause | 2,252 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2006 Zuza Software Foundation
#
# This file is part of translate.
#
# translate 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 t... | if not, see <http://www.gnu.org/licenses/>.
"""Supports a hybrid Unicode string that knows which encoding is preferable,
and uses this when converting to a string."""
class autoencode(unicode):
def __new__(newtype, string=u"", encoding=None, errors=None):
if isinstance(string, unicode):
if e... | else:
newstring = unicode.__new__(newtype, string, errors=errors)
if encoding is None and isinstance(string, autoencode):
newstring.encoding = string.encoding
else:
newstring.encoding = encoding
else:
if errors is None ... |
Beauhurst/django | django/utils/timezone.py | Python | bsd-3-clause | 8,544 | 0 | """
Timezone-related classes and functions.
"""
import functools
from contextlib import ContextDecorator
from datetime import datetime, timedelta, tzinfo
from threading import local
import pytz
from django.conf import settings
__all__ = [
'utc', 'get_fixed_timezone',
'get_default_timezone', 'get_default_tim... | , name=None):
if offset is not None:
self.__offset = timedelta(minutes=offset)
if name is not None:
self.__name = name
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(self, dt):
return ZERO
# ... | ith a fixed offset from UTC."""
if isinstance(offset, timedelta):
offset = offset.seconds // 60
sign = '-' if offset < 0 else '+'
hhmm = '%02d%02d' % divmod(abs(offset), 60)
name = sign + hhmm
return FixedOffset(offset, name)
# In order to avoid accessing settings at compile time,
# wrap t... |
VioletRed/script.module.urlresolver | lib/urlresolver/plugins/purevid.py | Python | gpl-2.0 | 5,907 | 0.00965 | #-*- coding: utf-8 -*-
"""
Purevid urlresolver XBMC Addon
Copyright (C) 2011 t0mm0, belese, JUL1EN094
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 Licen... | source = self.net.http_GET(url).content
common.addon.log_debug(source.encode('utf-8'))
if re.search("""<span>Welcome <strong>.*</strong></span>""", source) :
common.addon.log_debug('needLogin returning False')
r | eturn False
else :
common.addon.log_debug('needLogin returning True')
return True
def login(self):
if self.needLogin() :
common.addon.log('login to purevid')
url = 'http://www.purevid.com/?m=login'
data = {'username' : self.get_setting... |
elstupido/rpg | rooms/prolog/Room420-1.room.py | Python | mit | 1,463 | 0.006835 |
from room import Room
r = Room()
r.roomname = 'room 420'
r.exits = {'hallway': 'hallway'}
r.roomdesc = """
as the door opens smoke languidly rolls out. The lights are off and the curtain is pulled, which would normally make for a very dark room except for what appears to be a super nova sitting in the corner of the ro... | techno angel.
"""
r.looktargets = {'blinding light': '(squinting)It apears to be some kind of computer, "whats that smell? burrned retninas you say"\n\n',
'light': '(squinting)It apears to be some kind of computer, "whats that smell? burrned retninas you | say"\n\n',
'monitors': 'two of the monitors have news feeds detailing various horrors, one monitor has a few chat windows up where two people one named shifty and the other stupid seem to be conversing.\n\n',
'posters': 'various posters striking out at governments and "the new world order." one poster which seems dif... |
coreycb/charms.openstack | charms_openstack/plugins/trilio.py | Python | apache-2.0 | 24,279 | 0 | # Copyright 2019 Canonical Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | e from trilio source string.
Try and derive a trilio version from a deb string l | ike:
'deb [trusted=yes] https://apt.fury.io/triliodata-4-0/ /'
:param trilio_source: Trilio source
:type trilio_source: str
:returns: Trilio version
:rtype: str
:raises: AssertionError
"""
deb_url = trilio_source.split()[-2]
code = re.findall(r'-(\d*-\d*)', urlparse(deb_url).path)
... |
alexrudy/Cauldron | Cauldron/ext/__init__.py | Python | bsd-3-clause | 193 | 0.010363 | # -*- coding: utf- | 8 -*-
"""
Extensions to Cauldron are user-facing helpful features
which do not strictly obey the KTL API, but which a | re
compatible with the KTL API when used via Cauldron.
""" |
h5py/h5py | h5py/tests/test_h5p.py | Python | bsd-3-clause | 6,042 | 0.000662 | # This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2013 Andrew Collette and contributors
#
# License: Standard 3-clause BSD; see "license.txt" for full license terms
# and contributor agreement.
import unittest as ut
from h5py import h5p, h5f, ve... | def test_obj_track_times(self):
"""
tests if the object track times set/get
"""
# test for groups
gcid = h5p.create(h5p.GROUP_CREATE)
gcid.set_obj_track_times(False)
self.assertEqual(False, gcid.get_obj_track_times())
gcid.set_obj_track_times(True)
... | qual(True, gcid.get_obj_track_times())
# test for datasets
dcid = h5p.create(h5p.DATASET_CREATE)
dcid.set_obj_track_times(False)
self.assertEqual(False, dcid.get_obj_track_times())
dcid.set_obj_track_times(True)
self.assertEqual(True, dcid.get_obj_track_times())
... |
yzhuan/car | crawler/mycar168/mycar168/pipelines.py | Python | gpl-2.0 | 262 | 0 | # | Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class Mycar168Pipeline(object):
def process_item(self, item, spider):
| return item
|
openstack/octavia | octavia/controller/worker/v2/flows/amphora_flows.py | Python | apache-2.0 | 27,873 | 0 | # Copyright 2015 Hewlett-Packard Development Company, L.P.
# Copyright 2020 Red Hat, 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/licens... | dd(compute_tasks.CertComputeCreate(
name=sf_name + '-' + constants.CERT_COMPUTE_CREATE,
requires=(constants.AMPHORA_I | D, constants.SERVER_PEM,
constants.BUILD_TYPE_PRIORITY,
constants.SERVER_GROUP_ID,
constants.FLAVOR, constants.AVAILABILITY_ZONE),
provides=constants.COMPUTE_ID))
create_amp_for_lb_subflow.add(database_tasks.UpdateAmphoraComputeId(
... |
rs2/bokeh | bokeh/models/annotations.py | Python | bsd-3-clause | 34,179 | 0.001141 | ''' Renderers for various kinds of annotations that can be added to
Bokeh plots
'''
from __future__ import absolute_import
from six import string_types
from ..core.enums import (AngleUnits, Dimension, FontStyle, LegendClickPolicy, LegendLocation,
Orientation, RenderMode, SpatialUni | ts, VerticalAlign, TextAlign)
from ..core.has_props import abstract
from ..core.properties import (Angle, AngleSpec, Auto, Bool, ColorSpec, Datetime, Dict, DistanceSpec, Either,
Enum, Float, FontSizeSpec, Include, Instance, Int, List, NumberSpec, Overrid | e,
Seq, String, StringSpec, Tuple, value)
from ..core.property_mixins import FillProps, LineProps, TextProps
from ..core.validation import error
from ..core.validation.errors import BAD_COLUMN_NAME, NON_MATCHING_DATA_SOURCES_ON_LEGEND_ITEM_RENDERERS
from ..model import Model
from ..util.s... |
pitunti/alfaPitunti | plugin.video.alfa/platformcode/logger.py | Python | gpl-3.0 | 1,925 | 0.000519 | # -*- coding: utf-8 -*-
# --------------------------------------------------------------------------------
# Logger (kodi)
# --------------------------------------------------------------------------------
import inspect
import xbmc
from platformcode import config
loggeractive = (config.get_setting("debug") == True)... | eractive = active
def encode_log(message=""):
# Unicode to utf8
if type(message) == unicode:
message = message.encode("utf8")
# All encodings to utf8
elif type(message) == str:
message = unicode(message, "utf8", errors="replace").encode("utf8")
# Objects to string
else:
... | ame().f_back.f_back)
module = module.__name__
function = inspect.currentframe().f_back.f_back.f_code.co_name
if module == "__main__":
module = "alfa"
else:
module = "alfa." + module
if message:
if module not in message:
if function == "<module>":
... |
mvidalgarcia/indico | indico/modules/events/sessions/models/types.py | Python | mit | 1,690 | 0.000592 | # This file is part of Indico.
# Copyright (C) 2002 - 2019 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from sqlalchemy.ext.declarative import decl | ared_attr
from indico.core.db import db
from indico.util.locators import locator_property
from indico.util.string import format_repr, return_ascii
class SessionType(db.Model):
__tablename__ = 'session_types'
@declared_attr
def __table_args__(cls):
return (db.Index('ix_uq_session_types_event_id_n... | {'schema': 'events'})
id = db.Column(
db.Integer,
primary_key=True
)
event_id = db.Column(
db.Integer,
db.ForeignKey('events.events.id'),
index=True,
nullable=False
)
name = db.Column(
db.String,
nullable=False
)
... |
IlyaGusev/PersonalPage | PersonalPage/apps/entries/views.py | Python | gpl-2.0 | 252 | 0.003968 | f | rom django.views.generic import DetailView
from entries.models import Entry
class EntryView(DetailView):
model = Entry
template_name = "entry.html"
context_object_name = 'entry'
slug_field = 'sname'
slug_url_kwarg = 'entry_snam | e' |
zouyapeng/horizon-newtouch | openstack_dashboard/dashboards/project/firewalls/tabs.py | Python | apache-2.0 | 5,342 | 0 | # Copyright 2013, Big Switch Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http: | //www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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 specifi | c language governing permissions and limitations
# under the License.
#
# @author: KC Wang, Big Switch Networks
from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import tabs
from openstack_dashboard import api
from... |
hortonworks/hortonworks-sandbox | desktop/core/ext-py/Twisted/doc/core/howto/listings/pb/exc_client.py | Python | apache-2.0 | 810 | 0.007407 | #! /usr/bin/python
from twisted.spread import pb
from twisted.internet import reactor
def main():
factory = pb.PBClientFactory()
reactor.connectTCP("localhost", 8800, factory)
d = factory.getRootObject()
d.addCallbacks(got_obj)
reactor.run()
def got_obj(obj):
# change "broken" into "broken2" ... | n
print " | .__class__ =", reason.__class__
print " .getErrorMessage() =", reason.getErrorMessage()
print " .type =", reason.type
reactor.stop()
main()
|
evook/mirall | doc/ocdoc/user_manual/conf.py | Python | gpl-2.0 | 9,650 | 0.007254 | # -*- coding: utf-8 -*-
#
# ownCloud Documentation documentation build configuration file, created by
# sphinx-quickstart on Mon Oct 22 23:16:40 2012-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
# autogen... | ectionauthor and moduleauthor directives will be shown in | the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output -------------------------------------------------... |
hyperspy/hyperspy | hyperspy/tests/misc/test_utils.py | Python | gpl-3.0 | 4,362 | 0.000689 | # -*- coding: utf-8 -*-
# Copyright 2007-2022 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy 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 y... | ty("a (b)") == ("a", "b")
assert parse_quantity("a (b/(c))") == ("a", "b/(c)")
assert parse_quantity("a (c) (b/(c))") == ("a (c)", "b/(c)")
assert parse_quantity("a [ | b]") == ("a [b]", "")
assert parse_quantity("a [b]", opening="[", closing="]") == ("a", "b")
def test_is_hyperspy_signal():
s = signals.Signal1D(np.zeros((5, 5, 5)))
p = object()
assert is_hyperspy_signal(s) is True
assert is_hyperspy_signal(p) is False
def test_strlist2enumeration():
assert... |
kelsa-pi/unodit | examples/embed dialog/src/Test_embed.py | Python | gpl-3.0 | 27,471 | 0.004405 | # -*- coding: utf-8 -*-
#!/usr/bin/env python
# =============================================================================
#
# Dialog implementation generated from a XDL file.
#
# Created: Sat Jul 9 15:14:39 2016
# by: unodit 0.5
#
# WARNING! All changes made in this file will be overwritten
# if the... | om.sun.star.awt.UnoControlFixedTextModel")
self.Label8.TabIndex = 29
self.Label8.Label = "ProgressBar"
self.Label8.Name = "Label8"
self.Label8.Width = 60
self.Label8.PositionX = "83"
self.Label8.Height = 10
self.Label8.PositionY = "170"
# inserts the con... | control, set properties ---
self.Label4 = self.DialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel")
self.Label4.TabIndex = 25
self.Label4.Label = "NumericField"
self.Label4.Name = "Label4"
self.Label4.Width = 60
self.Label4.PositionX = "158"
se... |
kylon/pacman-fakeroot | test/pacman/tests/sync702.py | Python | gpl-2.0 | 504 | 0 | self.description = "incoming package rep | laces symlink with directory (order 2)"
lp = pmpkg("pkg2")
lp.files = ["usr/lib/foo",
"lib -> usr/lib"]
self.addpkg2db("local", lp)
p1 = pmpkg("pkg1")
p1.files = ["lib/bar"]
self.addpkg2db("sync", p1)
p2 = pmpkg("pkg2", "1.0-2")
p2.files = ["usr/lib/foo"]
self.addpkg2db("sync", p2)
self.args = "-S pkg1 ... | addrule("FILE_TYPE=lib|dir")
|
lildadou/Flexget | flexget/utils/imdb.py | Python | mit | 12,292 | 0.001627 | from __future__ import unicode_literals, division, absolute_import
import difflib
import logging
import re
from bs4.element import Tag
from flexget.utils.soup import get_soup
from flexget.utils.requests import Session
from flexget.utils.tools import str_to_int
from flexget.plugin import get_plugin_by_name, PluginErro... | parser.year
if name == '':
log.critical('Failed to parse name from %s' % raw_name)
return None
log.debug('smart_match name=%s year=%s' % (name, str(year)))
return self.best_match(name, year)
def best_match(self, name, year=None): |
"""Return single movie that best matches name criteria or None"""
movies = self.search(name)
if not movies:
log.debug('search did not return any movies')
return None
# remove all movies below min_match, and different year
for movie in movies[:]:
... |
anhstudios/swganh | data/scripts/templates/object/tangible/mission/quest_item/shared_sayama_edosun_q2_needed.py | Python | mit | 481 | 0.045738 | #### 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 = | "obje | ct/tangible/mission/quest_item/shared_sayama_edosun_q2_needed.iff"
result.attribute_template_id = -1
result.stfName("loot_nboo_n","sayama_edosun_q2_needed")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
wagnerand/zamboni | mkt/collections/filters.py | Python | bsd-3-clause | 6,380 | 0.000784 | from django import forms
from django.core.validators import EMPTY_VALUES
from django_filters.filters import ChoiceFilter, ModelChoiceFilter
from django_filters.filterset import FilterSet
import amo
import mkt
from addons.models import Category
from mkt.api.forms import SluggableModelChoiceField
from mkt.collections.m... | field = self.form.fields[self.order_by_field]
data = self.form[self.order_by_field].data
ordered = None
try:
ordered = order_field.clean(data)
except forms.ValidationError:
pass
if ordered in EMPTY_VALUES and self.strict:
... | elf.get_order_by(ordered))
return qs
@property
def qs(self):
if hasattr(self, '_qs'):
return self._qs
self._qs = self.get_queryset()
return self._qs
class CollectionFilterSetWithFallback(CollectionFilterSet):
"""
FilterSet with a fallback mechanism, droppi... |
pgergov/belmis | config/wsgi.py | Python | mit | 1,443 | 0 | """
WSGI config for belmis project.
This module contains the WSGI application used by Django's development server
and any produ | ction WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Djan... | example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
from django.core.wsgi import get_wsgi_application
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi... |
cnamejj/PyProc | regentest/self_sched.py | Python | gpl-2.0 | 3,267 | 0.003979 | #!/usr/bin/env python
"""Handle records from PID specific /proc/PID/sched data files"""
import regentest as RG
import ProcHandlers as PH
import ProcBaseRoutines as PBR
PFC = PH.ProcFieldConstants
# ---
# pylint: disable=R0914
def re_self_sched(inprecs):
"""Iterate through parsed records and re-generate data ... | __rule_list = inprecs.parse_rule
for __seq in __rule_list:
__rule = __rule_list[__seq][0]
try:
__key = __rule[PBR.FIELD_NAME]
__keydesc[__key] = __rule[PBR.PREFIX_VAL]
try:
__keyconv[__key] = __rule[PBR.CONVERSION]
... | for __key in inprecs.two_longs:
try:
__keyconv[__key] = str
__ff[__key] = __hilotemp.format(hi=__ff[__key] / 1000000,
low=__ff[__key] % 1000000)
except KeyError:
pass
print __headtemp.format(prog=__ff[PFC.F_PRO... |
Willyham/tchannel-python | tchannel/testing/vcr/proxy/ttypes.py | Python | mit | 6,330 | 0.012638 | # Copyright (c) 2015 Uber Technologies, Inc.
#
# 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, publ... | (1, TTy | pe.I32, 'code', None, None, ), # 1
(2, TType.STRING, 'headers', None, "", ), # 2
(3, TType.STRING, 'body', None, None, ), # 3
)
def __init__(self, code=None, headers=thrift_spec[2][4], body=None,):
self.code = code
self.headers = headers
self.body = body
def __hash__(self):
value = 17
... |
rbracken/internbot | plugins/pick/choices.py | Python | bsd-2-clause | 218 | 0.013761 | # Add y | our own choices here!
fruit = ["apples", "oranges", "pears", "grapes", "blueberries"]
lunch = ["pho", "timmies", "thai", "burgers", "buffet!", "indian", "montanas"]
situations = {"fruit":fruit, "lunch":lunch}
| |
GbalsaC/bitnamiP | edx-val/edxval/migrations/0001_initial.py | Python | agpl-3.0 | 7,559 | 0.007408 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Profile'
db.create_table('edxval_profile', (
('id', self.gf('django.db.models.fi... | lds.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'profile': ('django.db.models.fields.related.ForeignKey', [ | ], {'related_name': "'+'", 'to': "orm['edxval.Profile']"}),
'url': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
'video': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'encoded_videos'", 'to': "orm['edxval.Video']"})
},
'edxval.profile': ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.