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
epage/nqaap
support/builddeb.py
Python
lgpl-2.1
4,263
0.026742
#!/usr/bin/env python import os import sys try: import py2deb except ImportError: import fake_py2deb as py2deb import constants __app_name__ = constants.__app_name__ __description__ = """Very simple Audiobook player.
Supports playing, pausing, seeking (sort of) and saving state when changing book/cl
osing. Plays books arranged as dirs under myDocs/Audiobooks . Homepage: http://wiki.maemo.org/Nqaap""" __author__ = "Soeren 'Pengman' Pedersen" __email__ = "[email protected]" __version__ = constants.__version__ __build__ = constants.__build__ __changelog__ = """ * More unicode improvements """.strip() ...
neilLasrado/erpnext
erpnext/projects/utils.py
Python
gpl-3.0
2,678
0.020164
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt # For license information, please see license.txt from __future__ import unicode_literals import frappe @frappe.whitelist() def query_task(doctype, txt, searchfield, start, page_len, filters...
def
get_task_time_logs(task): return frappe.get_all("Timesheet Detail", filters={"task": task.name})
GunadarmaC0d3/Gilang-Aditya-Rahman
Python/Penggunaan else if.py
Python
gpl-2.0
141
0
kunci = "Python" password = raw_input("Masukan password : ") if password == kunci: print"Passwor
d Benar" else: print"Password Salah"
tehmaze/natural
natural/data.py
Python
mit
3,460
0.000291
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import print_function import datetime import fcntl import os import struct import sys import termios try: from io import BytesIO except ImportError: from cStringIO import StringIO as BytesIO import six from natural.constant import...
r x in range(0x10, 0x20, 2)), canonical, ))
row += 1 def printable(sequence): ''' Return a printable string from the input ``sequence`` :param sequence: byte or string sequence >>> print(printable('\\x1b[1;34mtest\\x1b[0m')) .[1;34mtest.[0m >>> printable('\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x06') == '........' True >>> p...
andreasf/django-notify
notify/migrations/0002_add_honeypot.py
Python
mit
553
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def add_honeypot(apps, schema_editor): Destination = apps.get_model("notify", "Destination") try: obj = Destination.objects.get(name="honeypot") except Destination.DoesNotExist: obj = Destinat...
operations = [ migrations.RunPython(add_honeypot), ]
stefanseefeld/synopsis
Synopsis/Formatters/HTML/Views/RawFile.py
Python
lgpl-2.1
3,392
0.003243
# # Copyright (C) 2000 Stephen Davies # Copyright (C) 2000 Stefan Seefeld # All rights reserved. # Licensed to the public under the terms of the GNU LGPL (>= 2), # see the file COPYING for details. # from Synopsis.Processor import Parameter from Synopsis.Formatters.HTML.View import View from Synopsis.Formatters.HTML.T...
n self._get_files(): self.process_file(path, filename) def register_filenames(self): for path, filename in self._get_files(): self.processor.register_filename(filename, self, path) def process_file(self, original, filename): """Creates a view for the given filename."""...
processor.filename_info(filename) if reg_view is not self: return self.__filename = filename self.__title = original[len(self.base_path):] self.start_file() self.write_navigation_bar() self.write('File: '+element('b', self.__title)) try: lines = open(...
isb-cgc/ISB-CGC-data-proc
tcga_etl_pipeline/maf/part1/extract2.py
Python
apache-2.0
3,767
0.005575
#!/usr/bin/env python # Copyright 2015, Institute for Systems Biology. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
missions and # limitations under the License. """Script to parse MAF file """ from bigquery_etl.utils.gcutils import read_mysql_query import sys import json import r
e from pandas import ExcelWriter writer = ExcelWriter('maf.xlsx') def identify_data(config): """Gets the metadata info from database """ # cloudSql connection params host = config['cloudsql']['host'] database = config['cloudsql']['db'] user = config['cloudsql']['user'] passwd = config['clo...
Chittr/Chittr
chittr/api.py
Python
mit
1,106
0.012658
from . import auth, users, rooms from .config import config import time from flask import session from pprint import pprint import emoji import re escape_chars = ( ("&", "&amp;"), ("<", "&lt;"), (">", "&gt;"), ) def parse_markdown(message): message = re.sub('\*{1}([^\*]+)\*{1}', '<b>\\1</b>', messag...
.sub('\`{1}([^\`]+)\`{1}', '<code>\\1</code>', message) return message def escape_message(message): for a, b in escape_chars: message = message.replace(a, b) return message def parse_message(user, room, message): user_data = users.safe_user(user) user_data["tag"] =
rooms.get_tag(room, user) user_data["rank"] = None # not implemented message = escape_message(message) message = emoji.emojize(message, use_aliases=True) # Markdown message = parse_markdown(message) return { "user": user_data, "text": message, "timestamp": time.time(...
dnr2/fml-twitter
tweepy-master/tests/test_streaming.py
Python
mit
4,635
0.002589
from time import sleep import unittest2 as unittest from tweepy.api import API from tweepy.auth import OAuthHandler from tweepy.models import Status from tweepy.streaming import Stream, StreamListener from config import create_auth from test_utils import mock_tweet from mock import MagicMock, patch class MockStreamL...
sponse: %s" % code) return True def on_status(self, status): self.status_count += 1 self.test_case.assertIsInstance(status, Status) if self.status_stop_count == self.status_count: return False class TweepyStreamTests(
unittest.TestCase): def setUp(self): self.auth = create_auth() self.listener = MockStreamListener(self) self.stream = Stream(self.auth, self.listener, timeout=3.0) def tearDown(self): self.stream.disconnect() def test_userstream(self): # Generate random tweet which ...
arunhotra/tensorflow
tensorflow/g3doc/how_tos/adding_an_op/zero_out_3_test.py
Python
apache-2.0
1,175
0.011064
"""Test for version 3 of the zero_out op.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.python.platform import tensorflow as tf from tensorflow.g3doc.how_tos.adding_an_op import gen_zero_out_op_3 class ZeroOut3Test(tf.test.TestCase...
esult = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1], preserve_index=3) self.assertAllEqual(result.eval(), [0, 0, 0
, 2, 0]) def testNegative(self): with self.test_session(): result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1], preserve_index=-1) with self.assertRaisesOpError("Need preserve_index >= 0, got -1"): result.eval() def testLarge(self): with self.test_session(): result = gen_zero_out...
mzdaniel/oh-mainline
vendor/packages/scrapy/scrapy/tests/test_downloadermiddleware_redirect.py
Python
agpl-3.0
7,244
0.002761
import unittest from scrapy.contrib.downloadermiddleware.redirect import RedirectMiddleware from scrapy.spider import BaseSpider from scrapy.exceptions import IgnoreRequest from scrapy.http import Request, Response, HtmlResponse, Headers class RedirectMiddlewareTest(unittest.TestCase): def setUp(self): s...
n redirected request" assert not req2.body, \ "Redirected body must be empty, not '%s'" % req2.body def test_max_redirect_times(self): self.mw.max_redirect_times = 1 req = Request('http://scrapytest.org/302') rsp = Response('http://scrapytest.org/302', headers={'Location...
self.assertEqual(req.meta['redirect_times'], 1) self.assertRaises(IgnoreRequest, self.mw.process_response, req, rsp, self.spider) def test_ttl(self): self.mw.max_redirect_times = 100 req = Request('http://scrapytest.org/302', meta={'redirect_ttl': 1}) rsp = Response('http://www....
rohitranjan1991/home-assistant
homeassistant/components/blockchain/sensor.py
Python
mit
1,990
0
"""Support for Blockchain.com sensors.""" from __future__ import annotations from datetime import timedelta import logging from pyblockchain import get_balance, validate_address import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ATTR_ATT...
homeassistant.helpers.typing import ConfigType, DiscoveryInfoType _LOGGER = logging.getLogger(__name__) ATTRIBUTION = "Data provided by blockchain.com" CONF_ADDRESSES = "addresses" DEFAULT_NAME = "Bitcoin Balance" ICON = "mdi:currency-btc" SCAN_INTERVAL = timedelta(minutes=5) PLATFORM_SCHEMA = PLATFORM_SCHEMA.e...
_NAME, default=DEFAULT_NAME): cv.string, } ) def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Blockchain.com sensors.""" addresses = config[CONF_ADDRESSES] name = c...
barak/autograd
examples/hmm_em.py
Python
mit
2,862
0.003494
from __future__ import division, print_function import autograd.numpy as np import autograd.numpy.random as npr from autograd.scipy.misc import logsumexp from autograd.convenience_wrappers import value_and_grad as vgrad from functools import partial from os.path import join, dirname import string import sys def EM(in...
n__': np.random.seed(0) np.seterr(divide='ignore') # callback to print log likelihoods during training print_loglike = lambda loglike, params: print(loglike) # load training data lstm_filename = join(dirname(__file__), 'lstm.py') train_inputs, num_outputs = build_dataset(lstm_filename, max...
init_params = initialize_hmm_parameters(num_states, num_outputs) pi, A, B = EM(init_params, train_inputs, print_loglike)
PyQuake/earthquakemodels
code/gaModel/gamodel_bbob.py
Python
bsd-3-clause
6,592
0.003337
import sys from deap import base, creator, tools import numpy as np from csep.loglikelihood import calcLogLikelihood # from models.mathUtil import calcNumberBins import models.model import random import array import time from operator import attrgetter # from scoop import futures import fgeneric import bbobbenchmarks a...
id_ind, fitnesses): ind.fitness.values = fit # The population is entirely replaced by the offspring, but the last ind replaced by best_pop # Elitism best_pop = tools.selBest(pop, 1)[0] offspring = sorted(offspring, key=attrgetter("fitness"), reverse=True)
offspring[0] = best_pop random.shuffle(offspring) pop[:] = offspring record = stats.compile(pop) # logbook.record(gen=g, **record) if (abs(record["min"]) - abs(ftarget)) < 10e-8: return best_pop if record["std"] < 10e-12: sortedPop = sorted(pop...
seap-udea/tQuakes
util/Legacy/allprd.py
Python
gpl-2.0
391
0.038363
from rutinas im
port * inputdir="ETERNA-INI/" outputdir="ETERNA-OUT/" in
putdb=argv[1] f=open(inputdir+"%s-INI/numeracionsismos.dat"%inputdb,"r") for line in f: if "#" in line:continue line=line.strip() numsismo=line.split()[0] print "Generando datos de sismo '%s'..."%numsismo cmd="python prd2dat.py %s/%s-OUT/ %s"%(outputdir,inputdb,numsismo) system(cmd) f.close()
arielrossanigo/fades
tests/test_pipmanager.py
Python
gpl-3.0
4,315
0.001391
# Copyright 2015 Facundo Batista, Nicolás Demarchi # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ...
edError("Error installing foo: Kapow!") def test_install_without_pip(self): mgr = PipManager('/usr/bin', pip_installed=False) with patch.object(helpers, 'logged_exec') as mocked_exec: with patch.object(mgr, '_brute_force_install_pip') as mocked_install_pip: mgr.install('...
self.assertEqual(mocked_install_pip.call_count, 1) mocked_exec.assert_called_with(['/usr/bin/pip', 'install', 'foo'])
tos-kamiya/pyrem_torq
src/pyrem_torq/treeseq/__init__.py
Python
mit
29
0
f
rom treeseq_funcs import *
dataxu/ansible
lib/ansible/modules/cloud/vmware/vmware_local_role_manager.py
Python
gpl-3.0
10,915
0.003207
#!/usr/bin/python # -*- coding: utf-8 -*- # Author(s): Abhijeet Kasurde <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version':...
rt_description: Manage local roles on an ESXi host description: - Manage local roles on an ESXi host version_added: "2.5" author: Abhijeet Kasurde (@akasurde) <[email protected]> notes: - Tested on ESXi 6.5 - Be sure that the ESXi user used for login, has the appropriate rights to create / delete / edit r...
_privilege_ids: description: - The list of privileges that role needs to have. - Please see U(https://docs.vmware.com/en/VMware-vSphere/6.0/com.vmware.vsphere.security.doc/GUID-ED56F3C4-77D0-49E3-88B6-B99B8B437B62.html) default: [] state: description: - In...
blassphemy/mqtt-ble-gateway
main.py
Python
apache-2.0
208
0.009615
import ble import m
qtt from config i
mport * try: ble.start() mqtt.start() finally: #notify MQTT subscribers that gateway is offline mqtt.publish(TOPIC_PREFIX, "offline") ble.stop()
3WiseMen/python
pystock/pystock_xingAPI/abstract_component.py
Python
mit
1,088
0.029412
#abstract_component.py import threading class AbstractComponent: logger = None def init(self): pass def finalize(self): pass class AbstractQueryProviderComponent(AbstractComponent): async_query_availabale = False def getAvailableQueryCodeSet(self): raise NotImplementedError('You have to overri...
ionCodeSet(self): raise NotImplementedError('You have to override AbstractSubscriptionProviderComponent.getAvailableSubscriptionSet method') def subscribe(self, subscribe_code, arg_set, queue): raise NotImplementedError('You have to override AbstractSubscriptionProviderComponent.subscribe method') def unsubsc...
ror('You have to override AbstractSubscriptionProviderComponent.unsubscribe method')
betoesquivel/PLYpractice
testingLexer.py
Python
mit
126
0
import lexer s = "program id; var beto
: int; { id = 1234; }" lexer.lexer.input(s) for token in lexer.lexer: print toke
n
henriquebastos/django-test-without-migrations
tests/nose_settings.py
Python
mit
509
0.005894
# coding: utf-8 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } INSTALLED_APPS = ( 'tests.myapp', 'test_without_migrations', 'django_nose' )
SITE_ID=1, SECRET_KEY='secret' MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', ) TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' TEST_WITHOUT_MIGRATIONS_COMMAND = '
django_nose.management.commands.test.Command'
our-city-app/oca-backend
src/shop/handlers.py
Python
apache-2.0
26,782
0.002576
# -*- coding: utf-8 -*- # Copyright 2020 Green Valley Belgium NV # # 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 appl...
stomer_location.type = ServiceProfile.ORGANIZATION_TYPE_PRO
FIT continue if field.name == 'name': customer_location.name = field.value continue if field.name == 'location': customer_location.lat = field.value.latitude customer_location.lon = field.value.longitude ...
cozy-labs/cozy-fuse
cozyfuse/dbutils.py
Python
bsd-3-clause
10,338
0.000193
import json import string import random import requests import logging import local_config from couchdb import Server, http from couchdb.http import PreconditionFailed, ResourceConflict logger = logging.getLogger(__name__) local_config.configure_logger(logger) def create_db(database): server = Server('http://...
nit_database_view('Folder', db) logger.info('[DB] Folder design document created') except ResourceConflict: logger.warn('[DB] Folder design document already exists') try: init_database_view('File', db) logger.info('[DB] File design document created') except ResourceConflict:...
"views": { "all": { "map": """function (doc) { if (doc.docType === \"Device\") { emit(doc.login, doc) } }""" }, "b...
mwarkentin/ansible
plugins/inventory/vmware.py
Python
gpl-3.0
6,210
0.007085
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' VMWARE external inventory script ================================= shamelessly copied from existing inventory scripts. This script and it's ini can be used more than once, i.e vmware.py/vmware_colo.ini vmware_idf.py/vmware_idf.ini (script can be link) so if you don'...
all(client) for host in hosts: if not guests_only: inv['all']['hosts'].append(host.name) inv[hw_
group].append(host.name) if host.tag: taggroup = 'vmware_' + host.tag if taggroup in inv: inv[taggroup].append(host.name) else: inv[taggroup] = [ host.name ] inv['_meta']['hostvar...
egineering-llc/egat_example_project
tests/test_helpers/selenium_helper.py
Python
mit
338
0.002959
from selenium.webdriver.support.select import Select def get_selected_option(browser, css_selector): # Takes a css selector for a <select> element and returns the value of # the selected option select = Select(browser.find_element_by_css_se
lector(css_selector)) return select.first_selected_option.get_attribute('value')
WarwickAnimeSoc/aniMango
archive/migrations/0002_auto_20181215_1934.py
Python
mit
1,365
0.003663
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2018-12-15 19:34 from __futur
e__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('archive', '0001_initial'), ] operations = [ migratio
ns.AlterField( model_name='item', name='date', field=models.DateField(help_text='Date of creation or last known time'), ), migrations.AlterField( model_name='item', name='details', field=models.TextField(blank=True, help_text='Any d...
darcyliu/storyboard
boto/emr/connection.py
Python
mit
19,314
0.002537
# Copyright (c) 2010 Spotify AB # Copyright (c) 2010-2011 Yelp # # 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, m...
https_connection_factory=None, region=None, path='/'): if not region:
region = RegionInfo(self, self.DefaultRegionName, self.DefaultRegionEndpoint) self.region = region AWSQueryConnection.__init__(self, aws_access_key_id, aws_secret_access_key, is_secure, port...
mfwarren/FreeCoding
2014/12/fc_30/app/models.py
Python
mit
596
0
from . import db class Role(db.Model): __tablename__ = 'roles' id = db.Column(db.Integer, primary_key=True) name = db.Column(
db.String(64), unique=True) users = db.relationship('User', backref='role', lazy='dynamic') def __repr__(self): return '<Role %s>' % self.name class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), unique=True, index=...
b.ForeignKey('roles.id')) def __repr__(self): return '<User %s>' % self.username
skosukhin/spack
var/spack/repos/builtin/packages/jags/package.py
Python
lgpl-2.1
1,927
0.000519
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, [email protected], All rights reserved. # LLNL
-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundat
ion) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You s...
kingosticks/mopidy
mopidy/config/types.py
Python
apache-2.0
9,146
0
import logging import re import socket from mopidy.config import validators from mopidy.internal import log, path def decode(value): if isinstance(value, bytes): value = value.decode(errors="surrogateescape") for char in ("\\", "\n", "\t"): value = value.replace( char.encode(enco...
def serialize(self, value, display=False): if value is None: return ""
return encode(value) class Secret(String): """Secret string value. Is decoded as utf-8 and \\n \\t escapes should work and be preserved. Should be used for passwords, auth tokens etc. Will mask value when being displayed. """ def __init__(self, optional=False, choices=None): se...
SVladkov/Numismatic
database/idatabase.py
Python
gpl-3.0
94
0.042553
#import coin class IDatabase: def enter_coin(coin): raise Exception
('NotImplementedError
')
davidgillies/ships
ships_proj/ships/tests/test_models.py
Python
gpl-2.0
109
0.018349
from django.test import TestCase from ships.mode
ls import *
class ShipModelTest(TestCase): pass
bikash/kaggleCompetition
microsoft malware/Malware_Say_No_To_Overfitting/kaggle_Microsoft_malware_small/find_2g.py
Python
apache-2.0
1,327
0.027882
import sys import pickle ###############################################
########### # usa
ge # pypy find_2g.py xid_train.p ../../data/train # xid_train.p is a list like ['loIP1tiwELF9YNZQjSUO',''....] to specify # the order of samples in traing data # ../../data/train is the path of original train data ########################################################## xid_name=sys.argv[1] data_path=sys.argv[2] ...
mlabru/ptracks
view/piloto/dlg_subida.py
Python
gpl-3.0
7,178
0.001123
#!/usr/bin/env python # -*- coding: utf-8 -*- """ --------------------------------------------------------------------------------------------------- dlg_subida mantém as informações sobre a dialog de subida This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Pub...
=========================== # ---------------------------------------------------------------------------------------------
@QtCore.pyqtSignature("int") def __on_cbx_currentIndexChanged(self, f_val): """ DOCUMENT ME! """ # atualiza comando self.__update_command() # < the end >--------------------------------------------------------------------------------------
dougwig/a10-neutron-lbaas
a10_neutron_lbaas/neutron_ext/extensions/a10DeviceInstance.py
Python
apache-2.0
4,037
0.000991
# Copyright 2015, A10 Networks # # 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 la...
s.A10_DEVICE_INSTANCE def get_plugin_type(self):
return constants.A10_DEVICE_INSTANCE def __init__(self): super(A10DeviceInstancePluginBase, self).__init__() @abc.abstractmethod def get_a10_device_instances(self, context, filters=None, fields=None): pass @abc.abstractmethod def create_a10_device_instance(self, conte...
AutorestCI/azure-sdk-for-python
azure-mgmt-monitor/azure/mgmt/monitor/models/diagnostic_settings_category_resource.py
Python
mit
1,650
0.000606
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
xy_only_resource import ProxyOnlyResource class DiagnosticSettingsCategoryResource(ProxyOnlyResource): """The diagnostic settings category resource. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Azure resource Id :vartype id: str :ivar name...
m category_type: The type of the diagnostic settings category. Possible values include: 'Metrics', 'Logs' :type category_type: str or ~azure.mgmt.monitor.models.CategoryType """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, ...
sghai/robottelo
tests/foreman/ui/test_satellitesync.py
Python
gpl-3.0
3,555
0
# -*- encoding: utf-8 -*- """Test class for InterSatellite Sync feature :Requirement: Satellitesync :CaseAutomation: Automated :CaseLevel: Acceptance :CaseComponent: UI :TestType: Functional :CaseImportance: High :Upstream: No """ from robottelo.decorators import ( run_only_on, stubbed, tier1, t...
test import UITestCase class InterSatelliteSyncTestCase(UITestCase): """Implements InterSatellite Sync tests in UI""" @run_only_on('sat') @stubbed() @tier3 @upgrade def test_positive_show_repo_export_history(self): """Product history shows repo export history on export. :id: ...
dresults: Repo/Product history should reflect the export history with user and time. :caseautomation: notautomated :CaseLevel: System """ @run_only_on('sat') @stubbed() @tier3 @upgrade def test_positive_show_cv_export_history(self): """CV history shows ...
djtaylor/cloudscape-DEPRECATED
python/cloudscape/common/remote.py
Python
gpl-3.0
25,284
0.009294
import os import re import copy import paramiko import StringIO import unicodedata from paramiko import SSHException, BadHostKeyException # CloudScape Libraries from cloudscape.common import config from cloudscape.common import logger from cloudscape.common.scp import SCPClient from cloudscape.common.utils import vali...
# System Defaults if not 'port' in self.sys_conn or not self.sys_conn['port']: self.sys_conn['port'] = 22 """ LOAD SSH KEY Method to load an SSH key for a Linux connection into a Parmiko object. """ def _load_ssh_key(self): if os.path.isfile(self.sys_con...
normalize('NFKD', self.sys_conn['key']).encode('ascii', 'ignore') key_fo = StringIO.StringIO(key_str) key_obj = paramiko.RSAKey.from_private_key(key_fo) return key_obj """ VALIDATE PARAMETERS Make sure the system type and connection parameters are valid. Check the conn...
mzdaniel/oh-mainline
vendor/packages/Django/tests/modeltests/order_with_respect_to/tests.py
Python
agpl-3.0
2,870
0.002787
from operator import attrgetter from django.test import TestCase from models import Post, Question, Answer class OrderWithRespectToTests(TestCase): def test_basic(self): q1 = Question.objects.create(text="Which Beatle starts with the letter 'R'?") q2 = Question.objects.create(text="What is your ...
bjects.create(text="Paul", question=q1) Answer.objects.create(text="Paulo", question=q2) Answer.objects.create(text="George", question=q1) Answer.objects.create(text="Ringo", question=q1) # The answers will always be ordered in the order they were inserted. self.assertQu...
ngo", ], attrgetter("text"), ) # We can retrieve the answers related to a particular object, in the # order they were created, once we have a particular object. a1 = Answer.objects.filter(question=q1)[0] self.assertEqual(a1.text, "John") a...
alphagov/stagecraft
stagecraft/libs/mass_update/test_data_set_mass_update.py
Python
mit
3,422
0
from stagecraft.apps.datasets.models import DataGroup, DataSet, DataType from django.test import TestCase from stagecraft.libs.mass_update import DataSetMassUpdate from nose.tools import assert_equal class TestDataSetMassUpdate(TestCase): @classmethod def setUpClass(cls): cls.data_group1 = DataGroup....
Group.objects.create(name='datagroup2') cls.data_type1 = DataType.objects.create(name='datatype1') cls.data_type2 = DataType.objects.create(name='datatype2') cls.dataset_a = DataSet.objects.create( name='foo', data_group=cls.data_group1, bearer_token="abc123"...
name='bar', data_group=cls.data_group2, bearer_token="def456", data_type=cls.data_type1) cls.dataset_c = DataSet.objects.create( name='baz', data_group=cls.data_group2, bearer_token="999999", data_type=cls.data_type2)...
jo-soft/jadfr
jadfr/feedreader/conf/my_conf.py
Python
gpl-3.0
238
0
try: from settings_local import
MyConf except ImportError: from feedreader.conf.base import Dev as MyConf try: from settings_local import MyTestConf except ImportError: from feedreader.conf.base import Test as MyTestConf
dungeonsnd/test-code
dev_examples/pyserver/src/util/pys_define.py
Python
gpl-3.0
184
0.033784
#!/bin/env python # -*-
coding: utf-8 -*- PYS_SERVICE_MOD_PRE='pys_' # 模块名称的前缀 PYS_HEAD_LEN=12 # 报文头长度 PYS_MAX_BODY_LE
N=10485760 # 最大报文长度
pycook/cmdb
cmdb-api/api/lib/decorator.py
Python
gpl-2.0
838
0
# -*- coding:utf-8 -*- from functools import wraps from flask import abort from flask import request def kwargs_required(
*required_args): def decorate(func): @wraps(func) def wrapper(*args, **kwargs): for arg in required_args: if arg not in kwargs: return abort(400, "Argument <{0}> is required".format(
arg)) return func(*args, **kwargs) return wrapper return decorate def args_required(*required_args): def decorate(func): @wraps(func) def wrapper(*args, **kwargs): for arg in required_args: if arg not in request.values: retu...
froschdesign/zf2-documentation
docs/src/conf.py
Python
bsd-3-clause
8,058
0.007322
# -*- coding: utf-8 -*- # # Zend Framework 2 documentation build configuration file, created by # sphinx-quickstart on Fri Jul 6 18:55:07 2012. # # 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...
he current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and mod
uleauthor 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 ------------...
libsh-archive/sh
test/regress/frac.cpp.py
Python
lgpl-2.1
1,097
0.003646
#!/usr/bin/python import shtest, sys, common from common import * from math import * def frac_test(p, types=[]): if is_array(p): result = [a - floor(a) for a in p] else: result = [a - floor(a)] return shtest.make_test(result, [p], types) def insert_into(test): test.add_test(frac_test(...
treamTest('frac', 1) test.add_call(shtest.Call(shtest.Call.call, 'frac', 1)) insert_into(test) test.output_header(sys.stdout) test.output(sys.stdout, False) # Test frac in immediate mode test = shtest.ImmediateTest('frac_im', 1) test.add_call(shtest.Call(shtest.Call.call, 'frac', 1)) insert_into(t
est) test.output(sys.stdout, False) test.output_footer(sys.stdout)
googleads/google-ads-python
google/ads/googleads/v9/errors/types/ad_parameter_error.py
Python
apache-2.0
1,192
0.000839
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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...
age governing permissions and # limitations under the License. # import proto # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v9.errors", marshal="google.ads.googleads.v9", manifest={"AdParameterErrorEnum",}, ) class AdParameterErrorEnum(proto.Message): r"""Container for e...
rror(proto.Enum): r"""Enum describing possible ad parameter errors.""" UNSPECIFIED = 0 UNKNOWN = 1 AD_GROUP_CRITERION_MUST_BE_KEYWORD = 2 INVALID_INSERTION_TEXT_FORMAT = 3 __all__ = tuple(sorted(__protobuf__.manifest))
klen/django-netauth
example_project/settings/test.py
Python
lgpl-3.0
347
0.005764
" Settings for tests. " from settings.project import * #
Da
tabases DATABASES= { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', 'USER': '', 'PASSWORD': '', 'TEST_CHARSET': 'utf8', } }
AndrewSallans/osf.io
framework/analytics/tasks.py
Python
apache-2.0
822
0
# -*- coding: utf-8 -*- from framework.tasks import app from framework.tasks.handlers import enqueue_task from website import settings from . import piwik @app.task(bind=True, max_retries=5, default_retry_delay=60) def _update_node(self, node_id, updated_fields=None): # Avoid circular imports from framewor...
ansactions.context import TokuTransaction from website import models node = models.Node.load(node_id) try: with TokuTransaction(): piwik._update_node_object(node, updated_fields) except Exception as error: raise self.retry(exc=error) def update_node(node_id, updated_fields)...
) enqueue_task(signature) else: _update_node(node_id, updated_fields)
mozilla/inventory
systems/migrations/0002_auto__add_field_userprofile_is_mysqldba_oncall__add_field_userprofile_.py
Python
bsd-3-clause
21,325
0.008159
# -*- 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 field 'UserProfile.is_mysqldba_oncall' db.add_column(u'user_profiles', 'is_mysqldba_oncall', ...
[], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
}, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'c...
BryanCutler/spark
python/pyspark/ml/classification.py
Python
apache-2.0
126,641
0.002953
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
from pyspark.sql.functions import udf, when from pyspark.sql.types import ArrayType, DoubleType from pyspark.storagelevel import StorageLevel __all__ = ['LinearSVC', 'LinearSVCModel', 'LinearSVCSummary', 'LinearSVCTrainingSummary',
'LogisticRegression', 'LogisticRegressionModel', 'LogisticRegressionSummary', 'LogisticRegressionTrainingSummary', 'BinaryLogisticRegressionSummary', 'BinaryLogisticRegressionTrainingSummary', 'DecisionTreeClassifier', 'DecisionTreeClassificationModel', 'GBTClassifier',...
okuta/chainer
tests/chainerx_tests/unit_tests/test_backend.py
Python
mit
1,149
0
import pytest import chainerx def test_name_native(): backend = chainerx.get_global_default_context().get_backend('native') assert 'native' == backend.name def test_get_device_native(): backend = chainerx.get_global_default_context().get_backend('native') device = backend.get_device(0) assert 0...
f test_get_device_cuda(): backend = chainerx.get_global_default_context().get_backend('cuda') device = backend.get_device(0) assert 0 == device.index assert 'cuda:0' == device.name assert device is backend.get_device(0) @pytest.mark.cuda def test_get_device_count_cuda(): backend = chainerx.get...
et_device_count() > 0
jnmclarty/pysia
docs/conf.py
Python
mit
8,373
0.005374
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pysia documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # 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 # autog...
an image file (relative to this directory) to place at # the top of the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings # are parts, not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, sh...
#latex_domain_indices = True # -- Options for manual page output ------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pysia', u'PySia Documentation', [u'Jeffrey McLarty'], 1) ] # If...
shirishagaddi/django-seo
rollyourown/seo/base.py
Python
bsd-3-clause
14,784
0.004532
# -*- coding: utf-8 -*- # TODO: # * Move/rename namespace polluting attributes # * Documentation # * Make backends optional: Meta.backends = (path, modelinstance/model, view) import hashlib from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.datastructures i...
seo.%s.%s' % (self.__metadata.__class__.__name__, hexpath) else: self.__cache_prefix = None self.__instances_original = instances self.__instances_cache = [] def __instances(self): """ Cache instances, allowing generators to be us
ed and reused. This fills a cache as the generator gets emptied, eventually reading exclusively from the cache. """ for instance in self.__instances_cache: yield instance for instance in self.__instances_original: self.__instances_cache.append(ins...
wdm0006/myflaskapp
tests/test_functional.py
Python
bsd-3-clause
3,662
0.000273
# -*- coding: utf-8 -*- """Functional tests using WebTest. See: http://webtest.readthedocs.org/ """ import pytest from flask import url_for from myflaskapp.models.user import User from .factories import UserFactory class TestLoggingIn: def test_can_log_in_returns_200(self, user, testapp): # Goes to ho...
out login form in navbar form = res.forms['loginForm'] form['username'] = user.username form['password'] = 'myprecious' # Submits res = form.submit().follow() assert res.status_code == 200 def test_sees_alert_on_log_
out(self, user, testapp): res = testapp.get("/") # Fills out login form in navbar form = res.forms['loginForm'] form['username'] = user.username form['password'] = 'myprecious' # Submits res = form.submit().follow() res = testapp.get(url_for('public.logout...
chriskiehl/Gooey
gooey/gui/events.py
Python
mit
840
0.014286
"""
App wide event registry Everything in the application is communicated via pubsub. These are the events that tie everything together. """ import wx # type: ignore WINDOW_STOP = wx.Window.NewControlId() WINDOW_CANCEL = wx.Window.NewControlId() WINDOW_CLO
SE = wx.Window.NewControlId() WINDOW_START = wx.Window.NewControlId() WINDOW_RESTART = wx.Window.NewControlId() WINDOW_EDIT = wx.Window.NewControlId() WINDOW_CHANGE = wx.Window.NewControlId() PANEL_CHANGE = wx.Window.NewControlId() LIST_BOX = wx.Window.NewControlId() CONSOLE_UPDATE = ...
andrewchambers/pixie
pixie/vm/test/test_reader.py
Python
gpl-3.0
1,607
0.001245
from pixie.vm.reader import read, StringReader from pixie.vm.object import Object from pixie.vm.cons import Cons from pixie.vm.numbers import Integer from pixie.vm.symbol import symbol, Symbol from pixie.vm.persistent_vector import PersistentVector import pixie.vm.rt as rt import unittest data = {u"(1 2)": (1, 2,), ...
mbol(u"foo"), u"1": 1, u"2": 2, u"((42))": ((42,),), u"(platform+ 1 2)": (symbol(u"platform+"), 1, 2), u"[42 43 44]": [42, 43, 44], u"(1 2 ; 7 8 9\n3)": (1, 2, 3,), u"(1 2
; 7 8 9\r\n3)": (1, 2, 3,)} class TestReader(unittest.TestCase): def _compare(self, frm, to): if isinstance(to, tuple): assert isinstance(frm, Cons) for x in to: self._compare(frm.first(), x) frm = frm.next() elif isinstance(to, int): ...
tensorflow/profiler-ui
server/server.py
Python
apache-2.0
2,149
0.011633
# Copyright 2018 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
Define routes. @app.route('/') def home(): """Responds to request for home page.""" return handle_home_page() @app.route('/profile') def profile(): """Responds to request for profile API.""" # Build options. return handle_profile_api() @app.route('/loading') def loa
ding(): """Responds to request for loading page.""" return handle_loading_page() # Define URL. host = '0.0.0.0' url = 'http://localhost:{}'.format(port) if open_browser: # Open new browser window after short delay. threading.Timer(1, lambda: webbrowser.open(url)).start() # Starting the serv...
pombredanne/django-bulbs
docs/conf.py
Python
mit
8,285
0.007483
# -*- coding: utf-8 -*- # # django-bulbs documentation build configuration file, created by # sphinx-quickstart on Wed Sep 18 16:55:34 2013. # # 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. # ...
age names to # template names. #html_additional_pages = {}
# If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # I...
dimonaks/siman
siman/set_functions.py
Python
gpl-2.0
28,264
0.022053
# -*- coding: utf-8 -*- from __future__ import division, unicode_literals, absolute_import, print_function import json import copy """ Oграничения режима sequence_set: 1) OCCMATRIX не копируется для дочерних сетов 2) Режим U-ramping выключен для дочерних сетов 3) Есть еще, режим afm_ordering, возможно neb 4) kpoints...
hen it is considered as path to external kpoints file self.path_to_potcar (str) - explicit path to potcar, can be used instead of self.potdir self.set_sequence (list) - list of InputSet() objects to make multiset runs. The current set is used as a first one. TODO Describe the difference between upd...
#super(InputSet, self).__init__() self.ise = ise self.name = ise self.des = "" # description self.potdir = {} self.units = "vasp" self.vasp_params = {} self.params = self.vasp_params # params for any code! self.mul_enaug = 1 self.history =...
Storj/metacore
metacore/tests/test_upload.py
Python
agpl-3.0
12,336
0
import sys import copy import json import os.path import unittest from hashlib import sha256 from io import BytesIO from metacore import storj from metacore.database import files from metacore.error_codes import * from metacore.tests import * if sys.version_info.major == 3: from unittest.mock import patch, Mock e...
self.patcher.start() def tearDown(self): """ Switch off some test configs. Remove new records form the 'files' table. Remove new fi
les from Upload Dir. Return initial blacklist content. """ self.patcher.stop() files.delete().where( files.c.hash not in (_[0] for _ in self.files) ).execute() added_files = set( os.listdir(self.app.config['UPLOAD_FOLDER']) ) - self.store...
netdingo/cbplayer
disk.py
Python
gpl-2.0
882
0.037415
## encoding=utf-8 #!/usr/bin/env python """ cubieboard ip module, which show ip """ __author__ = "Dingo" __copyright__ = "Copyright 2013, Cubieboard Player Project" __credits__ = ["PySUNXI project"] __license__ = "GPL" __version__ = "0.0.2" __maintainer__= "Dingo" __email__ = "[email protected]" import os, s...
""" do IP playing """ def __init__(self, name): cbtask.CbPlayerTask.__init__(self, name) def main(self): ## task entry ret = 0 return ret pass def handle_enter_key(self): ## #TODO pass def handle_exit_key(self): ## #TODO ...
pass def handle_right_key(self): ## #TODO pass if __name__ == "__main__" : pass
npuichigo/ttsflow
third_party/tensorflow/tensorflow/contrib/learn/python/learn/dataframe/transforms/example_parser.py
Python
apache-2.0
2,407
0.005401
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
features=self._ordered_features) # pylint: disable=not-callable return self.return_type(**parsed_val
ues)
JeffreyBLewis/WebVoteView
model/searchMeta.py
Python
apache-2.0
568
0.03169
import pymongo import json cache = {} client = pymongo.MongoClient() try: dbConf = json.load(open("./model/db.json","r")) except: try: dbConf = json.load(open("./db.json","r")) except: dbConf = {"dbname": "voteview"} db = client[dbConf["dbname"]] def metaLookup(api = ""): if not api: ...
turnDic
t = {"nominate": 0} for m in db.voteview_metadata.find({}, returnDict).sort('time', -1).limit(1): meta = m return meta
Yhzhtk/pytool
game/aixiaochu/xiaochu.py
Python
gpl-2.0
2,786
0.013943
# encoding=utf-8 ''' Created on 2013-9-8 @author: gudh ''' start_pos = (5, 222) # 开始的位置 block_size = (67, 67) # 块大小 rel_pos = (33, 28) # 相对块头位置 colors = ( (255, 255, 255), # 白 (164, 130, 213), # 紫 (247, 214, 82), # 黄 (244, 160, 90), # 土 (90, 186, 238), # 蓝 (247, 69, 95), # 红 (173, 235, 82) # 绿 ) colornames = (u'ba', ...
ck_size[1] + rel_pos[1] return (x, y) def get_rc_pos(rc): '''获取rc的点,注意横纵是反的''' x = start_pos[0] + rc[1] * block_s
ize[0] + rel_pos[0] y = start_pos[1] + rc[0] * block_size[1] + rel_pos[1] return (x, y) def get_block(i, j): '''获取块的区域''' x = start_pos[0] + i * block_size[0] y = start_pos[1] + j * block_size[1] w = x + block_size[0] h = y + block_size[1] return (x, y, w, h) def similar_color(p, color...
bsmedberg/socorro
webapp-django/crashstats/symbols/tests/test_views.py
Python
mpl-2.0
15,401
0
import os import shutil import tempfile from nose.tools import eq_, ok_ from django.core.urlresolvers import reverse from django.contrib.auth.models import User, Permission from django.core.files import File from crashstats.tokens.models import Token from crashstats.crashstats.tests.test_views import BaseTestViews f...
ok_(symbol_upload.size) ok_(symbol_upload.file) ok_(symbol_upload.file_exists) ok_(symbol_upload.content) def test_web_upload_tgz_file(self): url = reverse('symbols:web_upload') user = self._login() self._add_permission(user, 'upload_symbols') ...
response = self.client.post( url, {'file': file_object} ) eq_(response.status_code, 302) symbol_upload = models.SymbolsUpload.objects.get(user=user) eq_(symbol_upload.filename, os.path.basename(TGZ_FILE)) o...
zhkzyth/storm_maker
template/src/app.py
Python
mit
1,540
0
#! /usr/bin/env python # -*- coding: utf-8 -*- import signal import tornado.ioloop import tornado.web import tornado.httpserver import tornadoredis import torndb from tornado.options import options, define import log import handlers.test from settings import ( DEBUG, PORT, HOST, MYSQL_CONFIG, REDIS_CONFIG ) ...
lp="port", type=int) def
ine("host", default=HOST, help="host", type=str) define("debug", default=DEBUG, help="debug mode", type=bool) if __name__ == '__main__': main()
Shirling-VT/davitpy_sam
davitpy/gme/sat/poes.py
Python
gpl-3.0
33,273
0.033751
""" .. module:: poes :synopsis: A module for reading, writing, and storing poes Data .. moduleauthor:: AJ, 20130129 ********************* **Module**: gme.sat.poes ********************* **Classes**: * :class:`poesRec` **Functions**: * :func:`readPoes` * :func:`readPoesFtp` * :func:`mapPoesMongo` * :func:`...
used to convert a line of poes data read from the NOAA NGDC FTP site into a :class:`poesRec` object. .. note:: In general, users will not need to worry about this. **Belongs to**: :class:`poesRec` **Args**: * **line** (str): the ASCII line from the FTP server **Returns**: ...
import datetime as dt #split the line into cols cols = line.split() head = header.split() self.time = dt.datetime(int(cols[0]), int(cols[1]), int(cols[2]), int(cols[3]),int(cols[4]), \ int(float(cols[5])),int(round((float(cols[5])-int(float(cols[5])))*1e6))) fo...
BijoySingh/HomePage
homepage/admin.py
Python
gpl-2.0
1,571
0.00191
from django.contrib import admin from .models import * class CategoryAdmin(admin.ModelAdmin):
list_display = ('id', 'title') class ReviewCategoryAdmin(admin.ModelAdmin): list_display = ('id', 'title') class BlogCategoryAdmin(admin.ModelAdmin): list_display = ('id', 'title') class CardAdmin(admin.ModelAdmin): model = Card list_display = ['title', 'description', 'get_category', ] def...
egory__title' get_category.short_description = 'Category' class AccessAdmin(admin.ModelAdmin): list_display = ['ip', 'visit_count'] class ReviewsAdmin(admin.ModelAdmin): list_display = ['title', 'description', 'get_category', 'score', 'created'] def get_category(self, obj): return obj.categ...
grycap/clues
cluesplugins/nomad.py
Python
gpl-3.0
29,940
0.012792
#!/usr/bin/env pyth
on # # CLUES - Cluster Energy Saving System # Copyright (C) 2015 - GRyCAP - Universitat Po
litecnica de Valencia # # 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...
respawner/peering-manager
utils/testing/functions.py
Python
apache-2.0
1,327
0.000754
import json import logging import re from contextlib import contextmanager @contextmanager def disable_warnings(logger_name
): """ Suppresses expected warning messages to keep the test output clean. """ logger = logging.getLogger(logger_name) current_level = logger.level logger.setLevel(logging.ERROR) yield logger.setLevel(current_level) def extract_form_failures(html): """ Given raw HTML content fr...
. """ FORM_ERROR_REGEX = r"<!-- FORM-ERROR (.*) -->" return re.findall(FORM_ERROR_REGEX, str(html)) def json_file_to_python_type(filename): with open(filename, mode="r") as f: return json.load(f) def post_data(data): """ Takes a dictionary of test data and returns a dict suitable for...
haup/totoro
totoro/app/auth/views.py
Python
gpl-3.0
6,038
0
from flask import render_template, redirect, request, url_for, flash from flask_login import login_user, logout_user, login_required, current_user from . import auth from .. import db from ..models import User from ..email import send_email from .forms import LoginForm, RegistrationForm, ChangePasswordForm,\ Passwo...
th.route('/confirm/<token>') @login_required def confirm(token): if current_user.confirmed: return redir
ect(url_for('main.index')) if current_user.confirm(token): flash('You have confirmed your account. Thanks!') else: flash('The confirmation link is invalid or has expired.') return redirect(url_for('main.index')) @auth.route('/confirm') @login_required def resend_confirmation(): token =...
spezifanta/Paste-It
api/v01/views.py
Python
mit
749
0.006676
from django.shortcuts import redirect from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from paste.models import Paste, Language @csrf_exempt def add(request): print "jojo" if request.method == 'POST': language = request.POST['language'] content = r...
est.POST['content'] try: lang = Language.objects.get(pk=language) except: print "lang not avalible", language lang
= Language.objects.get(pk='txt') paste = Paste(content=content, language=lang) paste.save() paste = Paste.objects.latest() return HttpResponse(paste.pk, content_type='text/plain') else: return redirect('/api')
B-UMMI/INNUca
modules/mlst.py
Python
gpl-3.0
7,916
0.003284
import utils import os from functools import partial import sys from itertools import groupby as itertools_groupby mlst_timer = partial(utils.timer, name='MLST') def get_species_scheme_map_version(mlst_folder): species_scheme_map_version = 1 mlst_db_path = os.path.join(os.path.dirname(os.path.dirname(mlst_...
): line = line.lower().split('\t') line = [line[i].split(' ')[0] for i in range(0, len(line))] val_genus, val_species, val_scheme = set_species_scheme_map_variables(line,
species_scheme_map_version) if val_genus == species_splited[0]: if val_species == '': genus_mlst_scheme = val_scheme elif val_species == species_splited[1]: scheme = val_scheme if...
msimacek/koschei
alembic/versions/42ad047fd7ff_add_user_table.py
Python
gpl-2.0
903
0.014396
"""Add user table Revision ID: 42ad047fd7ff Revises: 5cd786f3176 Create Date: 2014-10-03 12:14:11.091123 """ # revision identifiers, used by Alembic. revision = '42ad047fd7ff' down_revision = '5cd786f3176' from alembic import op import sqlalchemy as sa
def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('user', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(), nullable=Fal
se), sa.Column('email', sa.String(), nullable=False), sa.Column('timezone', sa.String(), nullable=True), sa.Column('admin', sa.Boolean(), server_default='false', nullable=False), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name') ) ### end Alembic commands ### def downgrade(): ...
mitdbg/modeldb
client/verta/verta/_swagger/_public/uac/model/UacGetOrganizationByIdResponse.py
Python
mit
653
0.01072
# THIS FILE IS AUTO-GENERATED. DO NOT EDIT from verta._swagger.base_type import BaseType class UacGetOrganizationByIdResponse(BaseType): def __init__(self, organization=None): required = { "organization": False, }
self.organization = organization for k, v in required.items(): if self[k] is None and v: raise ValueError('attribute {} is required'.format(k)) @staticmethod def from_json(d): from .UacOrganization import UacOrganization tmp = d.get('organization', None) if tmp is not None:
d['organization'] = UacOrganization.from_json(tmp) return UacGetOrganizationByIdResponse(**d)
turnerm/podpy
podpy/__init__.py
Python
mit
271
0.01845
""" podpy is an implementatin of the pixel optical depth method as descri
bed in Turner et al. 2014, MNRAS, 445, 794, and Aguirre et al. 2002, ApJ, 576, 1. Please contact the author (Monica Turner) at [email protected] if you hav
e any questions, comment or issues. """
toobaz/pandas
pandas/plotting/_matplotlib/compat.py
Python
bsd-3-clause
554
0
#
being a bit too dynamic from distutils.version import LooseVersion import operator def _mpl_version(version, op): def inner(): try: import matplotlib as mpl except ImportError: return False return ( op(LooseVersion(mpl.__version__), LooseVersion(version)...
_mpl_ge_2_2_3 = _mpl_version("2.2.3", operator.ge) _mpl_ge_3_0_0 = _mpl_version("3.0.0", operator.ge) _mpl_ge_3_1_0 = _mpl_version("3.1.0", operator.ge)
redarmy30/Eurobot-2017
old year/RESET-master/Testing/server_small.py
Python
mit
805
0.034783
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket, time import sys import multiprocessing def readlines(sock, recv_buffer=4096, delim='\n'): buffer = '' data = True while data: data = sock.recv(recv_buffer) buffer += data while buffer.find(delim) != -1: line, buffer = buffer.split('\n', 1) yi...
ata_queue): HOST = "192.168.1.146" # Symbolic name meaning all available interf
aces PORT = 9090 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr message = readlines(conn) while 1: try: data_queue.put(eval(message.next())) except Exception as err: print 'E...
gitfred/fuel-extension-volume-manager
volume_manager/tests/test_migration_volume_manager_extension_001_add_volumes_table.py
Python
apache-2.0
3,073
0
# Copyright 2015 Mirantis, 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 ...
dule(): dropdb() # Run core migration in order to create buffer table alembic.command.upgrade(ALEMBIC_CONFIG, _core_test_revision) prepare() # Run extension migrations ext_alembic_config = make_alembic_config_from_extension( VolumeManagerExtension) alembic.command.upgrade(ext_alembic...
reflect_db_metadata() # Fill in migration table with data db.execute( meta.tables[extensions_migration_buffer_table_name].insert(), [{'extension_name': 'volume_manager', 'data': jsonutils.dumps({'node_id': 1, 'volumes': [{'volume': 1}]})}, {'extension_name': 'volume_manager',...
F-Secure/distci
src/distci/frontend/tests/test-frontend-tasks.py
Python
apache-2.0
4,501
0.004666
""" Tests for DistCI task management interfaces Copyright (c) 2012-2013 Heikki Nousiainen, F-Secure See LICENSE for details """ from nose.plugins.skip import SkipTest from webtest import TestApp, TestRequest import json import tempfile import os import shutil from distci import frontend class TestTasks: app = N...
.has_key('id'), "ID entry went missing" assert result.has_key('data'), "data entry went missing" self.test_state['id'] = st
r(result['id']) def test_03_check_single_task(self): task_id = self.test_state.get('id') if task_id is None: raise SkipTest("Skipping test for single task status, no recorded state") response = self.app.request('/tasks/%s' % task_id) result = json.loads(response.body) ...
zlorb/mitmproxy
pathod/language/generators.py
Python
mit
2,469
0.00081
import os import string import random import mmap import sys DATATYPES = dict( ascii_letters=string.ascii_letters.encode(), ascii_lowercase=string.ascii_lowercase.encode(), ascii_uppercase=string.ascii_uppercase.encode(), digits=string.digits.encode(), hexdigits=string.hexdigits.encode(), octdi...
if isinstance(x, slice): return b"".join(rand_byte(c
hars) for _ in range(*x.indices(min(self.length, sys.maxsize)))) return rand_byte(chars) def __repr__(self): return "%s random from %s" % (self.length, self.dtype) class FileGenerator: def __init__(self, path): self.path = os.path.expanduser(path) def __len__(self): retur...
EHRI/rspub-core
rspub/core/rs_enum.py
Python
apache-2.0
3,776
0.001324
#! /usr/bin/env python3 # -*- coding: utf-8 -*- import gettext from enum import Enum, unique _ = gettext.gettext strategy_descriptions = [_("New resourcelist strategy"), _("New changelist strategy"), _("Incremental changelist strategy")] @unique class Strategy(Enum...
""" :samp:`Get SelectMode names` :return: List<str> of names """ names = dir(SelectMode) ret
urn [x for x in names if not x.startswith("_")] @staticmethod def select_mode_for(mode): try: if isinstance(mode, SelectMode): return mode elif isinstance(mode, int): return SelectMode(mode) else: return SelectMode[mode...
elyezer/robottelo
robottelo/ui/architecture.py
Python
gpl-3.0
1,561
0
# -*- encoding: utf-8 -*- """Implements Architecture UI""" from robottelo.constants import FILTER from robottelo.ui.base import Base from robottelo.ui.locators import common_locators, locators from robottelo.ui.navigator import Navigator class Architecture(Base): """Manipulates architecture from UI""" def n...
_name, new_name=None, os_names=None, new_os_names=None): """Update existing arch's name and OS""" self.search_and_click(old_name) if new_name: self.assign_value(locators['arch.name'], new_name) self.configure_entity( os_names, FILTER['ar...
['submit'])
JayVora-SerpentCS/vertical-hotel
hotel/wizard/__init__.py
Python
agpl-3.0
153
0
#
-*- coding: utf-8 -*- # See LICENSE file for full copyright and licensing details. from . import hotel_wizard from . import sale_make_invoice_ad
vance
SM2015/orchid
core/migrations/0002_auto__add_field_score_created_at__add_field_score_updated_at__add_fiel.py
Python
mit
11,751
0.007404
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Score.created_at' db.add_column(u'core_score', 'created_a...
'}), u'id': ('django.db.models.field
s.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'core.image': { 'Meta': {'object_name': 'Image'}, 'changed_b...
asgeirrr/django-is-core
example/issues/cores.py
Python
lgpl-3.0
228
0.004386
f
rom django.contrib.auth.models import User from is_core.main import UIRestModelISCore from .models import Issue class IssueIsCore(UIRestModelISCore): model = Issue class UserIsCore(
UIRestModelISCore): model = User
BFriedland/TerrainGenerators
PerlinGeneratorDemo.py
Python
mit
17,655
0.020164
''' This version of the terrain generator library interpreter is set up to produce terrain maps using Perlin noise. Important settings and inits specific to the Perlin generator can be found in the code by searching for cfref:perlin-gen Additional display options may be viewed by swapping WHICH_COLOR_SCHEME constant...
pass def draw_maptile(self): ## Regardless of the color scheme, pixels with value of None type will be set to DEBUG_PINK. if type(self.z) == None: _color_of_this_pixel = DEBUG_PINK pygame.draw.rect(screen, _color_of_this_pixel, [s...
ixel_x, self.pixel_y, MAPTILE_WIDTH_IN_PIXELS, MAPTILE_HEIGHT_IN_PIXELS]) return if WHICH_COLOR_SCHEME == 'terrain': if self.z < 90: _color_of_this_pixel = DEEP_BLUE elif self.z < 120: ...
csakatoku/uamobile
uamobile/factory/ezweb.py
Python
mit
321
0.009346
# -*- coding: utf-8 -*- from uamobile.factory.base import AbstractUserAgentFactory from uamobile.ezweb import EZwebUserAgent from uamobile.parser import CachingEZwebUserAgentParser class EZwebUserAgentFactory(AbstractUserAgentFa
ctory): device_class =
EZwebUserAgent parser = CachingEZwebUserAgentParser()
ZhangXFeng/hadoop
src/hadoop-mapreduce1-project/src/contrib/cloud/src/py/hadoop/cloud/util.py
Python
apache-2.0
2,562
0.016393
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
.setdefaulttimeout(timeout) attempts = 0 while True: try: return urllib2.urlopen(url).read() except urllib2.URLError: attempts = attempts + 1 if attempts > retries: raise def xstr(string): """Sane string conversion: return an empty string if string is None.""" return ''
if string is None else str(string)
taigaio/taiga-back
taiga/webhooks/signal_handlers.py
Python
agpl-3.0
2,526
0.000396
# -*- coding: utf-8 -*- # Copyright (C) 2014-present Taiga Agile LLC # # 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 ver...
ce.key) pk = history_service.get_pk_from_key(instance.key) try: obj = model.objects.get(pk=pk) except model.DoesNotExist: # Catch simultaneous DELETE request return None webhooks = _get_project_webhooks(obj.project) if instance.type == HistoryType.create: task = tas...
a_args = [instance] elif instance.type == HistoryType.delete: task = tasks.delete_webhook extra_args = [] by = instance.owner date = timezone.now() webhooks_args = [] for webhook in webhooks: args = [webhook["id"], webhook["url"], webhook["key"], by, date, obj] + extra_args...
jccaicedo/localization-agent
learn/cnn/convertProtobinToNumpy.py
Python
mit
447
0.017897
from caffe import io as c import numpy as np import os,sys if len(sys.argv) < 3: print 'Use: convertProtobinToNumpy
protobinFile numpyOutput' sys.exit() protoData = c.caffe_pb2.BlobProto() f = open(sys.argv[1],'rb') protoData.ParseFromString(f.read()) f.close() array = c.blobproto_to_array(protoData) np.save(sys.argv[2],array[0].swapaxes(1, 0).swapaxes(2,1)[:, :, ::-1]) A =
np.load(sys.argv[2]+'.npy') print 'Final matrix shape:',A.shape
mbuesch/toprammer
libtoprammer/chips/at89c2051dip20.py
Python
gpl-2.0
6,509
0.036104
""" # TOP2049 Open Source programming suite # # Atmel AT89C2051 DIP20 Support # # Copyright (c) 2010 Guido # Copyright (c) 2010 Michael Buesch
<[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published
by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the...
victorywang80/Maintenance
saltstack/src/salt/modules/kmod.py
Python
apache-2.0
6,443
0.000466
# -*- coding: utf-8 -*- ''' Module to manage Linux kernel modules ''' # Import python libs import os import re # Import salt libs import salt.utils def __virtual__(): ''' Only runs on Linux systems ''' return 'kmod' if __grains__['kernel'] == 'Linux' else False def _new_mods(pre_mods, post_mods): ...
'module': comps[0], 'depcount': comps[2], } if len(comps) > 3: mdat['deps'] = comps[3].split(',') else: mdat['deps'] = [] ret.append(mdat) return ret def mod_list(only_persist=False): ''' Return a list of the loaded module names ...
) if only_persist: conf = _get_modules_conf() if os.path.exists(conf): with salt.utils.fopen(conf, 'r') as modules_file: for line in modules_file: line = line.strip() mod_name = _strip_module_name(line) if not li...
ethz-asl/segmatch
segmappy/segmappy/tools/hull.py
Python
bsd-3-clause
583
0.001715
import numpy as np def point_in_hull(point
, hull, tolerance=1e-12): return all((np.dot(eq[:-1], point) + eq[-1] <= tolerance) for eq in hull.equations) def n_points_in_hull(points, hull): n_points = 0 for i in range(points.shape[0]): if point_in_hull(points[i, :], hull): n_points = n_points + 1 return n_points def are_in...
[] for i in range(points.shape[0]): if point_in_hull(points[i, :], hull): ins.append(i) else: outs.append(i) return ins, outs
shinken-monitoring/mod-perfdata-service
module/module.py
Python
agpl-3.0
5,056
0.001978
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2009-2012: # Gabes Jean, [email protected] # Gerhard Lausser, [email protected] # Gregory Starck, [email protected] # Hartmut Goebel, [email protected] # # This file is part of Shinken. # # Shinken is free software: you can redis...
just arrived, we UPDATE data info with this def manage_service_check_result_brok(self, b): data = b.data # The original model # "$TIMET\t$HOSTNAME\t$SERVICEDESC\t$OUTPUT\t$SERVICESTATE\t$PERFDATA\n" current_state = self.resolve_service_state(data['state_id']) macros = { ...
'$SERVICEOUTPUT$': data['output'], '$SERVICESTATE$': current_state, '$SERVICEPERFDATA$': data['perf_data'], '$LASTSERVICESTATE$': data['last_state'], } s = self.template for m in macros: #print "Replacing in %s %s by %s" % (s, m, str(macros[m])...
project-hopkins/Westworld
hopkin/routes/items.py
Python
gpl-3.0
8,707
0.001034
import json from bson.errors import InvalidId from flask import Blueprint, jsonify, request, g item_api = Blueprint('itemApi', __name__) def get_item_as_object(item) -> dict: return_item = { "_id": str(item['_id']), "name": item['name'], "description": item['description'], "imageU...
s.items import Item items_list = [] query: str = request.args['q'] if not len(query) > 0: return jsonify({'error': 'no search results provided'}) query = query.title() items = list(Item.get_by_name_search(query.lower())) if len(query) > 3: items = items + list(Item.get_by_tag_s...
[] for item in items: if str(item['_id']) not in unique_ids: items_list.append({ "_id": str(item['_id']), "name": item['name'], "description": item['description'], "imageURL": item['imageURL'], "price": item['price'...
anhstudios/swganh
data/scripts/templates/object/mobile/shared_dressed_diplomat_zabrak_male_01.py
Python
mit
457
0.045952
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION F
OR EXAMPLES from swgpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_dressed_diplomat_zabrak_male_01.iff" re
sult.attribute_template_id = 9 result.stfName("npc_name","zabrak_base_male") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
kstaniek/pampio
pampio/version.py
Python
apache-2.0
50
0
"""Version in
formation.""" __version__
= '0.0.2'
samstav/fastfood
fastfood/book.py
Python
apache-2.0
10,125
0
# Copyright 2015 Rackspace US, 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 wri...
if not self._berksfile: if not os.path.isfile(self.berks_path): raise ValueError("No Berksfile found at %s" % self.berks_path) self._berksfile = Berksfile(open(self.berks_path, 'r+')) return self._berksfile class M
etadataRb(utils.FileWrapper): """Wrapper for a metadata.rb file.""" @classmethod def from_dict(cls, dictionary): """Create a MetadataRb instance from a dict.""" cookbooks = set() # put these in order groups = [cookbooks] for key, val in dictionary.items(): ...