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 |
|---|---|---|---|---|---|---|---|---|
pydcs/dcs | dcs/coalition.py | Python | lgpl-3.0 | 14,260 | 0.002805 | import sys
from typing import Dict, Union, List, TYPE_CHECKING
import dcs.countries as countries
from dcs.mapping import Point
import dcs.unitgroup as unitgroup
import dcs.planes as planes
import dcs.helicopters as helicopters
import dcs.ships as ships
from dcs.unit import Vehicle, Static, Ship, FARP, SingleHeliPad
fro... | ship = Ship(
mission.terrain,
id= | imp_unit["unitId"],
name=self.get_name(mission, imp_unit["name"]),
_type=ships.ship_map[imp_unit["type"]])
ship.load_from_dict(imp_unit)
mission.current_unit_id = max(mission.current_unit_id, ship.id)
... |
dmacvicar/spacewalk | client/solaris/smartpm/smart/backends/solaris/base.py | Python | gpl-2.0 | 3,072 | 0.003581 | #
# Copyright (c) 2005 Red Hat, Inc.
#
# Written by Joel Martin <[email protected]>
#
# This file is part of Smart Package Manager.
#
# Smart Package Manager 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; ei... | 1]),
cutoff)
ratio = max(ratio, ratio1, ratio2, ratio3)
if ratio:
searcher.addResult(self, ratio)
def coexists(self, other):
if not isinstance(other, SolarisPackage):
return True
return False
def __lt__(self, othe... | rc = vercmp(self.version, other.version)
return rc == -1
class SolarisProvides(Provides): pass
class SolarisDepends(Depends):
def matches(self, prv):
if not isinstance(prv, SolarisProvides) and type(prv) is not Provides:
return False
if not self.version or not prv.version:
... |
zedshaw/mulletdb | clients/python/tests/db_tests.py | Python | agpl-3.0 | 5,155 | 0.005044 | from nose.tools import *
from mullet import db
from unittest import TestCase
sess = db.Session("tcp://127.0.0.1:5003")
sql = db.Sql(sess)
disk = db.Disk(sess)
map = db.Mem(sess)
search = db.Search(sess)
def setup():
sql.query("drop table test")
sql.query("create table test (id INTEGER PRIMARY KEY, name TEST, ... | valid(sql.delete("test", where="name = $name$", vars={"n | ame": "Frank"}))
def test_sql_result(self):
assert_valid(sql.insert("test", values={"name": "Frank", "age": 70}))
res = sql.query("select * from test where name='Frank'")
assert_valid(res)
for row in res.rows():
print row
for row in res:
print row[... |
ToonTownInfiniteRepo/ToontownInfinite | toontown/classicchars/CharStateDatasAI.py | Python | mit | 14,539 | 0.007703 | # File: C (Python 2.4)
from otp.ai.AIBaseGlobal import *
from direct.distributed.ClockDelta import *
from direct.fsm import StateData
from direct.directnotify import DirectNotifyGlobal
import random
from direct.task import Task
from toontown.toonbase import ToontownGlobals
import CCharChatter
import CCharPaths
class ... | .chatter = CCharChatter.getChatter(self.character.ge | tName(), self.character.getCCChatter())
if self.chatter != None:
taskMgr.remove(self._CharChattyStateAI__chatTaskName)
taskMgr.add(self.blather, self._CharChattyStateAI__chatTaskName)
StateData.StateData.enter(self)
def pickMsg(self, category):
self.get... |
the-virtual-brain/tvb-hpc | phase_plane_interactive/template.py | Python | apache-2.0 | 642 | 0.035826 | class ${name}:
def __init__(self,\
%for c,val in const.items( | ):
${c}=${val}${'' if loop.last else ', '}\
%endfor
):
self.limit = ${limit}
% for c in const.keys():
self.${c} = ${c}
% endfor
def dfun(self,state_variables, *args, **kwargs):
<%
sv_csl = ", ".join(sv)
%>
${sv_csl} = state_variables
% for... | % for cvar in input:
${cvar} = 0.0
% endfor
% for i, var in enumerate(sv):
d${var} = ${drift[i]}
% endfor
return [${sv_csl}]
|
FFMG/myoddweb.piger | monitor/api/python/Python-3.7.2/Lib/test/test_tools/test_unparse.py | Python | gpl-2.0 | 8,393 | 0.000477 | """Tests for the unparse.py script in the Tools/parser directory."""
import unittest
import test.support
import io
import os
import random
import tokenize
import ast
from test.test_tools import basepath, toolsdir, skip_if_missing
skip_if_missing()
parser_path = os.path.join(toolsdir, "parser")
with test.support.Di... | self.check_roundtrip("(-1.) | **8")
self.check_roundtrip("(-1j)**6")
self.check_roundtrip("not True or False")
self.check_roundtrip("True or not False")
def test_integer_parens(self):
self.check_roundtrip("3 .__abs__()")
def test_huge_float(self):
self.check_roundtrip("1e1000")
self.check_ro... |
marineam/nagcat | python/nagcat/unittests/test_test.py | Python | apache-2.0 | 1,910 | 0.000524 | # Copyright 2009 ITA Software, 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 wr... | 'test-a': {
'type': "noop",
'data': "1",
},
| 'test-b': {
'type': "noop",
'data': "2",
},
'return': "$(test-a) + $(test-b)",
},
})
t = test.Test(simple.NagcatDummy(), config)
d = t.start()
d.addBoth(self.endCompound, t)
... |
openstack/mistral | mistral/tests/unit/api/test_resource_list.py | Python | apache-2.0 | 1,260 | 0 | # Copyright 2018 Nokia Networks. 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 a... | .controllers.v2 import resources
class TestResourceList(base.BaseTestCase):
def test_next_link_correctness(self):
task = resources.Task.sample()
result = resources.Tasks.convert_ | with_links(
resources=[task],
limit=1,
url='https://localhost:8080',
sort_keys='created_at,id',
sort_dirs='asc,asc',
fields='',
state='eq:RUNNING'
)
next_link = result.next
self.assertIn('state=eq:RUNNING', nex... |
ekansa/open-context-py | opencontext_py/apps/imports/fieldannotations/types.py | Python | gpl-3.0 | 15,913 | 0.000943 | import uuid as GenUUID
from django.conf import settings
from django.db import models
from django.utils.http import urlunquote
from opencontext_py.libs.general import LastUpdatedOrderedDict
from opencontext_py.apps.ocitems.events.models import Event
from opencontext_py.apps.entities.entity.models import Entity
from open... | _ld in ld_entities.items():
obj_uri = distinct_ld['imp_cell_obj'].record
if len(obj_uri) > 8:
| if obj_uri[:7] == 'http://'\
or obj_uri[:8] == 'https://':
# we have a valid linked data entity
#
# now get the UUID for the type
tm = TypeManag... |
ilogue/niprov | niprov/mediumfile.py | Python | bsd-3-clause | 750 | 0 | from niprov.formatxml import XmlFormat
from niprov.formatjson import JsonFormat
from niprov.pictures import PictureCache
class FileMedium(object):
def __init__(self, dependencies):
self.filesys = dependencies.getFilesystem()
self.clock = dependencies.getC | lock()
self.listener = dependencies.getListener()
def export( | self, formattedProvenance, form):
if isinstance(form, PictureCache):
fname = formattedProvenance
else:
fname = 'provenance_{0}.{1}'.format(self.clock.getNowString(),
form.fileExtension)
self.filesys.write(fname, formatte... |
invitecomm/asterisk-ivr | pigeonhole/junk.py | Python | gpl-3.0 | 1,356 | 0.00816 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set et sw=4 fenc=utf-8:
#
# Copyright 2016 INVITE Communications Co., Ltd. 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 Founda... | it will be useful,
# but WITHOUT ANY WARRANTY; without even the | implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""AGI script that renders speech to text us... |
meren/anvio | anvio/migrations/profile/v28_to_v29.py | Python | gpl-3.0 | 1,741 | 0.006318 | #!/usr/bin/env python
# -*- coding: utf-8
import sys
import argparse
import anvio.db as db
import anvio.utils as utils
import anvio.terminal as terminal
f | rom anvio.errors import ConfigError
run = terminal.Run()
progress = terminal.Progress()
current_version, next_version = [x[1:] for x in __name__.split('_to_')]
def migrate(db_ | path):
if db_path is None:
raise ConfigError("No database path is given.")
# make sure someone is not being funny
utils.is_profile_db(db_path)
# make sure the version is accurate
profile_db = db.DB(db_path, None, ignore_version = True)
if str(profile_db.get_version()) != current_versio... |
mrcrilly/Journal | journal/api.py | Python | mit | 1,370 | 0.013869 |
import json
import routing
from werkzeug.local import LocalProxy
from flask import Blueprint, request, current_app
blueprint = Blueprint('journal-api', __name__)
logging = L | ocalProxy(lambda: current_app.config['logging'])
@blueprint.errorhandler(404)
def return_404(e):
return {
'err': 'Page not found.'
}, 404
@blueprint.route("/api/journal", methods=['GET', 'POST'])
def journal():
if reques | t.method == 'POST':
results, success = routing.journal_post(json.loads(request.data))
if not success:
return json.dumps(results), 500
else:
logging.LogMessage(results)
return json.dumps(results), 201
if request.method == 'GET':
results, success = routing.journal_get_all()
if s... |
EricMuller/mynotes-backend | requirements/twisted/Twisted-17.1.0/src/twisted/conch/mixin.py | Python | mit | 1,374 | 0.002911 | # -*- test-case-name: twisted.conch.test.test | _mixin -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Experimental optimization
This module provides a single mixin class which allows protocols to
collapse | numerous small writes into a single larger one.
@author: Jp Calderone
"""
from twisted.internet import reactor
class BufferingMixin:
"""
Mixin which adds write buffering.
"""
_delayedWriteCall = None
data = None
DELAY = 0.0
def schedule(self):
return reactor.callLater(self.DELAY... |
Lekensteyn/buildbot | master/buildbot/master.py | Python | gpl-2.0 | 20,742 | 0.000482 | # This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | ildbot Team Members
from __future__ import absolute_import
from __future__ import print_function
from future.utils import iteritems
import datetime
import os
import signal
import socket
from twisted.application import internet
f | rom twisted.internet import defer
from twisted.internet import task
from twisted.internet import threads
from twisted.python import components
from twisted.python import failure
from twisted.python import log
from zope.interface import implementer
import buildbot
import buildbot.pbmanager
from buildbot import config
f... |
polymorphm/php-miniprog-shell | lib_php_miniprog_shell_2011_12_17/main.py | Python | gpl-3.0 | 4,746 | 0.007164 | # -*- mode: python; coding: utf-8 -*-
#
# Copyright 2011 Andrej A Antonov <[email protected]>.
#
# 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 Foundation, either version 3 of the License, or
# (... | add_arguments_func = getattr(cmd_module, 'add_arguments', None)
cmd_parser = subparsers.add_parser(cmd, help=help, description=description)
cmd_parser.set_defaults(cmd=cmd)
if add_arguments_func is not None:
add_arguments_func(cmd_parser)
return help
def get_config_path(args):
... | is None:
config_path = os.path.join(
os.path.dirname(sys.argv[0]),
DEFAULT_CONFIG_FILENAME)
return config_path
def program_exit(code=None):
tornado.ioloop.IOLoop.instance().stop()
if code is not None:
_local.exit_code = code
def on_finish():
pr... |
Microvellum/Fluid-Designer | win64-vc/2.78/python/lib/encodings/cp424.py | Python | gpl-3.0 | 12,055 | 0.023559 | """ Python Character Mapping Codec cp424 generated from 'MAPPINGS/VENDORS/MISC/CP424.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_table)
def decode(self,input,errors='... | N MARK
'\xbb' # 0x8B -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
'\ufffe' # 0x8C -> UNDEFINED
'\ufffe' # 0x8D -> UNDEFINED
'\u | fffe' # 0x8E -> UNDEFINED
'\xb1' # 0x8F -> PLUS-MINUS SIGN
'\xb0' # 0x90 -> DEGREE SIGN
'j' # 0x91 -> LATIN SMALL LETTER J
'k' # 0x92 -> LATIN SMALL LETTER K
'l' # 0x93 -> LATIN SMALL LETTER L
'm' # 0x94 -> LATIN SMALL LETTER M
'n' # 0x95 ... |
Karaage-Cluster/karaage-debian | karaage/legacy/applications/south_migrations/0004_auto__add_field_application_content_type__add_field_application_object.py | Python | gpl-3.0 | 17,096 | 0.007136 | # encoding: utf-8
from south.db import db
from south.v2 import SchemaMigration
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Application.content_type'
db.add_column('applications_application', 'content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=or... | ank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'max_length': '16', 'unique': 'True', 'null': 'True', 'blank': 'True' | })
},
'applications.application': {
'Meta': {'object_name': 'Application'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']", 'null': 'True', 'blank': 'True'}),
'content_type_temp': ('django.db.models.fields.r... |
urandu/mfl_api | users/tests/test_models.py | Python | mit | 3,146 | 0 | from django.utils import timezone
from model | _mommy import mommy
from common.tests.test_models import BaseTestCase
from ..models import MflUser
class TestMflUserModel(BaseTestCase):
def test_save_normal_user(self):
data = {
| "email": "[email protected]",
"username": "some",
"first_name": "jina",
"last_name": "mwisho",
"other_names": "jm",
"password": "pass",
}
user = MflUser.objects.create(**data)
# the base test case class comes with another user
... |
nnic/home-assistant | homeassistant/components/sensor/netatmo.py | Python | mit | 5,202 | 0 | """
homeassistant.components.sensor.netatmo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NetAtmo Weather Service service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.netatmo/
"""
import logging
from datetime import timedelta
from h | omeassistant.components.sensor import DOMAIN
from homeassistant.const import (
CONF_API_KEY, CONF_PASSWORD, CONF_USERNAME, TEMP_CELCIUS)
from homeassistant.helpers import validate_config
from homeassistant.helpers.entity import Entity
from homeassistant.uti | l import Throttle
REQUIREMENTS = [
'https://github.com/HydrelioxGitHub/netatmo-api-python/archive/'
'43ff238a0122b0939a0dc4e8836b6782913fb6e2.zip'
'#lnetatmo==0.4.0']
_LOGGER = logging.getLogger(__name__)
SENSOR_TYPES = {
'temperature': ['Temperature', TEMP_CELCIUS, 'mdi:thermometer'],
'co2': ... |
kupiakos/LapisMirror | plugins/drawcrowd.py | Python | mit | 4,144 | 0.000724 | # The MIT License (MIT)
# Copyright (c) 2 | 015 kupiakos
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without | restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice sha... |
jaycedowell/wxPi | polling.py | Python | gpl-2.0 | 4,492 | 0.03829 | # -*- coding: utf-8 -*
"""
Module for polling the various sensors.
"""
import time
import logging
import threading
import traceback
try:
import cStringIO as StringIO
except ImportError:
import StringIO
from datetime import datetime, timedelta
from decoder import read433
from parser import parsePacketStream
from ut... | thread = None
self.alive = threading.Event()
def start(self):
if self.thread is not None:
self.cancel()
self.thread = threading.Thread(target=self.run, name='poller')
self.thread.setDaemon(1)
self.alive.set()
self.thread.start()
pollLogger.info('Started the PollingProcessor back... | # clear alive event for thread
self.thread.join()
pollLogger.info('Stopped the PollingProcessor background thread')
def run(self):
tLastUpdate = 0.0
sensorData = self.sensorData
while self.alive.isSet():
## Begin the loop
t0 = time.time()
## Load in the current configuration
wu... |
perkinslr/pypyjs | addedLibraries/multiprocessing/__init__.py | Python | mit | 7,835 | 0.003574 | #
# Package analogous to 'threading.py' but using processes
#
# multiprocessing/__init__.py
#
# This package is intended to duplicate the functionality (and much of
# the API) of threading.py but uses processes instead of threads. A
# subpackage 'multiprocessing.dummy' has the same API but is a simple
# wrapper for 't... | rn Pool(processes, initializer, initargs, maxtasksperchild)
def RawValue(typecode_or_type, *args):
'''
Returns a shared object
'''
from multiprocessing.sharedctypes import RawValue
return RawValue(typecode_or_type, *args)
def RawArray(typecode_or_type, size_or_initializer):
'''
Returns a s... | sing.sharedctypes import RawArray
return RawArray(typecode_or_type, size_or_initializer)
def Value(typecode_or_type, *args, **kwds):
'''
Returns a synchronized shared object
'''
from multiprocessing.sharedctypes import Value
return Value(typecode_or_type, *args, **kwds)
def Array(typecode_or_t... |
flyxiao2000/myide | python_resource/myexception.py | Python | gpl-3.0 | 118 | 0.008475 | import sys
try:
import myahll
except Exception as | e:
for info in e.args:
print info
| sys.exit(1)
|
nephthys/shr_im | oauthlogin/decorators.py | Python | gpl-3.0 | 550 | 0.034545 | from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from models import Account
def wants_user(f):
def decorated(*args, **kwargs):
try: args[0].user = Account.objects.get(pk=args[0].session['user_id'])
| except: args[0].user = None
return f(*args, **kwargs)
return decorated
def needs_user(url):
def decorated1(f):
@wants_user
def decorated2(*args, **kwargs):
if not args[0].user: return HttpResponseRedirect(reverse(url))
else: return f(*args, **kwargs)
return decorated2
r | eturn decorated1
|
DBrianKimmel/PyHouse | Project/src/Modules/Computer/Web/web_rootMenu.py | Python | mit | 1,294 | 0.001546 | """
@name: PyHouse/Project/src/Modules/Computer/Web/web_rootMenu.py
@author: D. Brian Kimmel
@contact: [email protected]
@copyright: (c) 2013-2019 by D. Brian Kimmel
@license: MIT License
@note: Created on May 30, 2013
@summary: Handle the Main menu.
"""
__updated__ = '2019-10-31'
# Import s... | odules.Core import logging_pyh as Logger
LOG = Logger.getLogger('PyHouse.webRootMenu ')
class RootMenuElement(Element):
"""
"""
# docFactory | = loaders.xmlfile(os.path.join(templatepath, 'rootMenuElement.html'))
jsClass = u'rootMenu.RootMenuWidget'
def __init__(self, p_workspace_obj):
self.m_pyhouse_obj = p_workspace_obj.m_pyhouse_obj
@renderer
def XXdoRootMenuReload(self, _p_json):
""" Process a message for a XML save/reloa... |
common-workflow-language/cwltool | cwltool/provenance_constants.py | Python | apache-2.0 | 1,889 | 0 | import hashlib
import os
import uuid
from prov.identifier import Namespace
__citation__ = "https://doi.org/10.5281/zenodo.1208477"
# NOTE: Semantic versioning of the CWLProv Research Object
# **and** the cwlprov files
#
# Rough guide (major.minor.patch):
# 1. Bump major number if removing/"breaking" resources or PRO... | PROV_VERSION = "https://w3id.org/cwl/prov/0.6.0"
# Research Object folders
METADATA = " | metadata"
DATA = "data"
WORKFLOW = "workflow"
SNAPSHOT = "snapshot"
# sub-folders
MAIN = os.path.join(WORKFLOW, "main")
PROVENANCE = os.path.join(METADATA, "provenance")
LOGS = os.path.join(METADATA, "logs")
WFDESC = Namespace("wfdesc", "http://purl.org/wf4ever/wfdesc#")
WFPROV = Namespace("wfprov", "http://purl.org/wf... |
wagnerluis1982/speakerfight | deck/models.py | Python | mit | 12,918 | 0.000155 | from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import ValidationError
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django.db import models, transaction
from django.db.models import Count
from django.db.models.... | (models.QuerySet):
def cached_authors(self):
retu | rn super(DeckBaseManager, self).select_related('author')
def published_ones(self):
return self.cached_authors().filter(is_published=True)
def order_by_never_voted(self, user_id):
if self.model != Proposal:
raise AttributeError(
"%s object has no attribute %s" % (
... |
henchc/CLFL_2016 | CLFL_ngram.py | Python | mit | 7,224 | 0.000139 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import unicode_literals
# Created at UC Berkeley 2015
# Authors: Christopher Hench
# ==============================================================================
'''T... | nd discards "O" labels.
Note that it requires scikit-learn 0.15+ (or a version f | rom
github master) to calculate averages properly!
"""
lb = LabelBinarizer()
y_true_combined = lb.fit_transform(list(chain.from_iterable(y_true)))
y_pred_combined = lb.transform(list(chain.from_iterable(y_pred)))
tagset = set(lb.classes_) - {'O'}
tagset = sorted(... |
guildenstern70/fablegenerator | fablegenerator/numtoword/num2word_DE.py | Python | mit | 5,299 | 0.00585 | # coding=utf-8
'''
Module: num2word_DE.py
Requires: num2word_base.py
Version: 0.4
Author:
Taro Ogawa ([email protected])
Copyright:
Copyright (c) 2003, Taro Ogawa. All Rights Reserved.
Licence:
This module is distributed under the Lesser General Public Licence.
http://www.open... | inquagint",
"sexagint", "septuagint", "oktogint", "nonagint"]
self.high_numwords = ["zent"]+self.gen_high_numwords(units, tens, lows)
self.mid_numwords = [(1000, "tausand"), (100, "hundert"),
| (90, "neunzig"), (80, "achtzig"), (70, "siebzig"),
(60, "sechzig"), (50, "f\xFCnfzig"), (40, "vierzig"),
(30, "drei\xDFig")]
self.low_numwords = ["zwanzig", "neunzehn", "achtzen", "siebzehn",
"... |
astronomeara/xastropy-old | xastropy/galaxy/core.py | Python | bsd-3-clause | 1,859 | 0.016138 | """
#;+
#; NAME:
#; galaxy.core
#; Version 1.0
#;
#; PURPOSE:
#; Core routines for galaxy analysis
#; 29-Nov-2014 by JXP
#;-
#;------------------------------------------------------------------------------
"""
from __future__ import print_function, absolute_import, division, unicode_literals
import os, copy,... | as xdb
# Class for LLS Absorption Lines
class Galaxy(object):
"""A Galaxy Class
Attributes:
name: string
Name(s)
z: float
Adopted redshift
coord: Coordinates
mstar: float
Stellar mass (MsolMass)
"""
# Initialize with a .dat file
def __init | __(self, ra=None, dec=None, z=0.):
self.z = z
# Coord
if ra is None:
ras = '00 00 00'
else:
ras = str(ra)
if dec is None:
decs = '+00 00 00'
else:
decs = str(dec)
self.coord = SkyCoord(ras, decs, 'icrs', u... |
shamidreza/deepcca | dA_joint.py | Python | gpl-2.0 | 21,666 | 0.005169 | """
This tutorial introduces denoising auto-encoders (dA) using Theano.
Denoising autoencoders are the building blocks for SdA.
They are based on auto-encoders as the ones used in Bengio et al. 2007.
An autoencoder takes an input x and first maps it to a hidden representation
y = f_{\theta}(x) = s(Wx+b), paramete... | ith Denoising Autoencoders, ICML'08, 1096-1103,
2008
- Y. Bengio, P. Lamblin, D. Popovici, H. Larochelle: Greedy Layer-Wise
Training of Deep Networks, Advances in Neural Information Processing
Systems 1 | 9, 2007
"""
import os
import sys
import time
import numpy
import theano
import theano.tensor as T
from theano.tensor.shared_randomstreams import RandomStreams
from logistic_sgd import load_data
from utils import tile_raster_images, load_vc
try:
import PIL.Image as Image
except ImportError:
import Image
t... |
DailyActie/Surrogate-Model | 01-codes/OpenMDAO-Framework-dev/openmdao.main/src/openmdao/main/test/netperf.py | Python | mit | 3,996 | 0 | """
Run latency & thruput tests on various server configurations.
"""
import glob
import os.path
import shutil
import time
from openmdao.main.mp_util import read_server_config
from openmdao.main.objserverfactory import connect, start_server
from openmdao.util.fileutil import onerror
MESSAGE_DATA = []
def init_mess... | return results
def main():
""" Run latency & thruput tests on various server configurations. """
init_messages()
latency_results = {}
thruput_results = {}
# For each configuration...
count = 0
for authkey in ('PublicKey', 'UnEncrypted'):
for ip_port in (-1, 0):
| for hops in (1, 2):
# Start factory in unique directory.
count += 1
name = 'Echo_%d' % count
if os.path.exists(name):
shutil.rmtree(name, onerror=onerror)
os.mkdir(name)
os.chdir(name)
... |
avehtari/GPy | GPy/kern/src/stationary.py | Python | bsd-3-clause | 21,805 | 0.010961 | # Copyright (c) 2012, GPy authors (see AUTHORS.txt).
# Licensed under the BSD 3-clause license (see LICENSE.txt)
import numpy as np
from scipy import integrate
from .kern import Kern
from ...core.parameterization import Param
from ...util.linalg import tdot
from ... import util
from ...util.config import config # for... | ce, Logexp())
assert self.variance.size==1
self.link_parameters(self.variance, self.lengthscale)
def K_of_r(self, r):
raise NotImplementedError("implement the covariance function as a fn of r to use this class")
def dK_dr(self, r):
raise NotImplementedError("implement derivativ... | raise NotImplementedError("implement second derivative of covariance wrt r to use this method")
@Cache_this(limit=3, ignore_args=())
def dK2_drdr_diag(self):
"Second order derivative of K in r_{i,i}. The diagonal entries are always zero, so we do not give it here."
raise NotImplementedError(... |
iambibhas/django | tests/backends/tests.py | Python | bsd-3-clause | 49,291 | 0.001542 | # -*- coding: utf-8 -*-
# Unit and doctests for specific database backends.
from __future__ import unicode_literals
import copy
import datetime
from decimal import Decimal, Rounded
import re
import threading
import unittest
import warnings
from django.conf import settings
from django.core.exceptions import Improperly... | is rolle | d back (#17062).
"""
databases = copy.deepcopy(settings.DATABASES)
new_connections = ConnectionHandler(databases)
new_connection = new_connections[DEFAULT_DB_ALIAS]
try:
# Ensure the database default time zone is different than
# the time zone in new_conne... |
jbzdak/edx-platform | lms/djangoapps/courseware/tests/test_views.py | Python | agpl-3.0 | 50,037 | 0.00284 | # coding=UTF-8
"""
Tests courseware views.py
"""
import cgi
from urllib import urlencode
import ddt
import json
import itertools
import unittest
from datetime import datetime
from HTMLParser import HTMLParser
from nose.plugins.attrib import attr
from django.conf import settings
from django.contrib.auth.models import A... | ase
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory, check_mongo_calls
@attr('shard_1')
class TestJumpTo(ModuleStoreTestCase):
"""
Check the jumpto link for a course.
"""
MODULESTORE = | TEST_DATA_MIXED_TOY_MODULESTORE
def setUp(self):
super(TestJumpTo, self).setUp()
# Use toy course from XML
self.course_key = SlashSeparatedCourseKey('edX', 'toy', '2012_Fall')
def test_jumpto_invalid_location(self):
location = self.course_key.make_usage_key(None, 'NoSuchPlace')... |
intel-analytics/BigDL | python/ppml/src/bigdl/ppml/algorithms/hfl_nn.py | Python | apache-2.0 | 1,511 | 0 | #
# Copyright 2016 The BigDL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | f fit(self, x, y, epochs):
"""
:param x: data, could be Numpy NdArray or Pandas DataFrame
:param y: label, could be Numpy NdArray or Pandas DataFrame
:param epochs: training epochs
:return:
"""
pass
def evaluate(self, x, y):
"""
:param x: data... | e Numpy NdArray or Pandas DataFrame
:param y: label, could be Numpy NdArray or Pandas DataFrame
:return:
"""
pass
def predict(self, x):
"""
:param x: data, could be Numpy NdArray or Pandas DataFrame
:return:
"""
pass
|
dewtx29/python_ann | python/ann/pso_recurrent/recurrent_pso.py | Python | gpl-3.0 | 475 | 0.018947 | from pso import *
from recurrent import *
class Recurrent (recurrent):
def hell | o() | :
print "hello"
class Pso(ParticleSwarmOptimizer):
dimension = 304
swarmSize = 10
#def __init__(self):
# super(Pso, self).__init__()
def f(self, solution):
# 304
re = Recurrent()
fitness = re.rnn(solution)
return fitness
def main():
pso... |
ravrahn/HangoutsBot | hangupsbot/plugins/__init__.py | Python | gpl-3.0 | 11,524 | 0.004339 | import os
import sys
import logging
import inspect
from inspect import getmembers, isfunction
from commands import command
import handlers
logger = logging.getLogger(__name__)
class tracker:
def __init__(self):
self.bot = None
self.list = []
self.reset()
def set_bot(self, bot):
... | s": {
"admin": [],
"user": [],
"all": None
},
"handlers": [],
"shared": [],
"metadata": None
}
def start(self, metadata):
self.reset()
self._current["metadata"] = metadata
def current(self):... | self._current["commands"]["all"] = list(
set(self._current["commands"]["admin"] +
self._current["commands"]["user"]))
return self._current
def end(self):
self.list.append(self.current())
def register_command(self, type, command_names):
"""call during pl... |
zenoss/pywbem | examples/enumerator_generator.py | Python | lgpl-2.1 | 10,193 | 0.001177 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Example of using Iterator Operations to retrieve instances from a
WBEM Server. This example executes the IterEnumerateInstances and the
corresponding IterEnumeratePaths operations.
It:
Creates a connection
Opens an enumeration session w... | ty_arggroup.add_argument(
'-p', '--password', dest='password', metavar='password',
help='R|Passwor | d for authenticating with the WBEM server.\n'
'Default: Will be prompted for, if user name\nspecified.')
security_arggroup.add_argument(
'-nvc', '--no-verify-cert', dest='no_verify_cert',
action='store_true',
help='Client will not verify certificate returned by the WBEM'
... |
Candihub/pixel | apps/submission/tests/test_flows.py | Python | bsd-3-clause | 2,965 | 0 | from unittest import mock
from django.test import TestCase
from viewflow import lock, signals a | s vf_signals
from viewflow.activation import ST | ATUS
from viewflow.base import this
from ..flows import AsyncActivationHandler, AsyncHandler
class ProcessStub(object):
_default_manager = mock.Mock()
def __init__(self, flow_class=None):
self.flow_class = flow_class
class TaskStub(object):
_default_manager = mock.Mock()
def __init__(self... |
uvasrg/EvadeML | classifiers/pdfrate_wrapper.py | Python | mit | 5,330 | 0.006004 | import sys, os
_current_dir = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.normpath(os.path.join(_current_dir, ".."))
sys.path.append(PROJECT_ROOT)
from lib.config import config
mimicus_dir = config.get('pdfrate', 'mimicus_dir')
import_path = os.path.join(mimicus_dir, 'reproduction')
sys.path.app... | caler'
return classifier, scaler
pdfrate_classifier, pdfrate_scaler = get_cla | ssifier_scaler()
pool = multiprocessing.Pool()
def pdfrate_feature(pdf_file_paths, speed_up = True):
classifier = pdfrate_classifier
scaler = pdfrate_scaler
if not isinstance(pdf_file_paths, list):
pdf_file_paths = [pdf_file_paths]
if speed_up == True:
# The Pool has to be moved outsi... |
nwjs/chromium.src | components/policy/tools/template_writers/test_suite_all.py | Python | bsd-3-clause | 2,777 | 0.00144 | #!/usr/bin/env python3
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''Unit test suite that collects template_writer tests.'''
import os
import sys
import unittest
class TestSuiteAll(unittest.TestSuit... | import writers.json_writer_unittest
import writers.plist_strings_writer_unittest
import writers.plist_writer_unitte | st
import writers.reg_writer_unittest
import writers.template_writer_unittest
import writers.xml_writer_base_unittest
test_classes = [
policy_template_generator_unittest.PolicyTemplateGeneratorUnittest,
writers.adm_writer_unittest.AdmWriterUnittest,
writers.adml_writer_unittest.... |
roryyorke/python-control | control/xferfcn.py | Python | bsd-3-clause | 58,104 | 0.000379 | """xferfcn.py
Transfer function representation and functions.
This file contains the TransferFunction class and also functions
that operate on transfer functions. This is the primary representation
for the python-control library.
"""
# Python 3 compatibility (needs to go here)
from __future__ import print_function
... | ans that the numerator | of the transfer function from the 6th input to the
3rd output is set to s^2 + 4s + 8.
Discrete-time transfer functions are implemented by using the 'dt'
instance variable and setting it to something other than 'None'. If 'dt'
has a non-zero value, then it must match whenever two transfer functions
... |
deepmind/dm-haiku | haiku/_src/recurrent.py | Python | apache-2.0 | 27,760 | 0.003963 | # Copyright 2019 DeepMind Technologies Limited. 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 ... | for
more details.
return_all_states: If True, all intermediate states are returned rather than
only the last one in time.
Returns:
A tuple with two elements:
* **output | _sequence** - An arbitrarily nested structure of tensors
of shape ``[T, ...]`` if time-major, otherwise ``[B, T, ...]``.
* **state_sequence** - If return_all_states is True, returns the sequence
of core states. Otherwise, core state at time step ``T``.
"""
scan = hk.scan if inside_transform() ... |
mreithub/rocker | rocker/restclient.py | Python | apache-2.0 | 16,781 | 0.029021 |
import codecs
import json
import select
import socket
import sys
import time
import urllib.parse
# Slim HTTP client written directly on top of the UNIX socket API.
# Therefore it can be used with both UNIX and TCP sockets.
#
# Its intended use is limited to rocker (the restclient API should not be
# considered stabl... | he idea is to create a new Request instance for each request.
#
# The best way to instantiate the client is using a with statement. That way
# all resources will be released properly. E.g.:
#
# with Reque | st("unix:///var/run/docker.sock") as req:
# response = client.doGet('/version').send()
# # do something with the response
#
# send() will return a Response object which can then be used to act accordingly
class Request:
# Request constructor
#
# You'll have to provide either a UNIX socket path or a HTTP/HTTP... |
timstaley/voeventdb | voeventdb/server/tests/test_fixture_creation.py | Python | gpl-2.0 | 916 | 0.002183 | from __future__ import absolute_import
from unittest import TestCase
from datetime import datetime, timedelta
from voeventdb.server.tests.fixtures import fake, packetgen
class TestBasicRoutines(TestCase):
def setUp(self):
self.start = datetime(2015, 1, 1)
self.interval = timedelta(minutes=15) |
def test_timerange(self):
n_interval_added = 5
times = [t for t in
packetgen.timerange(self.start,
self.start+self.interval*n_interval_added,
self.interval)]
self.assertEqual(n_interval_added, len(ti... | fake.heartbeat_packets(self.start, self.interval,
n_interval)
self.assertEqual(n_interval, len(packets))
|
uclouvain/OSIS-Louvain | program_management/ddd/validators/_authorized_relationship_for_all_trees.py | Python | agpl-3.0 | 2,629 | 0.001522 | # ############################################################################
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core business i... | ogramTreeRepository',
link_type: Optional[LinkTypes]
) -> None:
super().__init__()
self.tree = tree
self.node_to_paste = node_to_paste
self.path = path
self.tree_repository = tree_repository
| self.link_type = link_type
def validate(self, *args, **kwargs):
node_to_paste_to = self.tree.get_node(self.path)
trees = self.tree_repository.search_from_children([node_to_paste_to.entity_id])
trees.append(self.tree)
for tree in trees:
for parent_node in tree.get_par... |
errx/django | django/utils/html.py | Python | bsd-3-clause | 10,215 | 0.002154 | """HTML utilities suitable for global use."""
from __future__ import unicode_literals
import re
from django.utils.encoding import force_text, force_str
from django.utils.functional import allow_lazy
from django.utils.safestring import SafeData, mark_safe
from django.utils import six
from django.utils.six.moves.urlli... | for z in range | (32))
def escapejs(value):
"""Hex encodes characters for use in JavaScript strings."""
return mark_safe(force_text(value).translate(_js_escapes))
escapejs = allow_lazy(escapejs, six.text_type)
def conditional_escape(text):
"""
Similar to escape(), except that it doesn't operate on pre-escaped string... |
onaio/kpi | kpi/management/commands/create_kobo_superuser.py | Python | agpl-3.0 | 1,204 | 0.000831 | # -*- coding: utf-8 -*-
import sys
import os
from django.db.utils import ProgrammingError
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Create `superuser` if user does not already exist'
def handle(self, *args, **options)... | os.getenv('KOBO_SUPERUSER_EMAIL', '[email protected]'),
os.getenv('KOBO_SUPERUSER_PASSWORD', 'kobo'))
except ProgrammingError: # Signals fail when `kc` database
pass | # doesn't exist yet.
except Exception as e:
self.stdout.write('Superuser could not be created.\n'
'Error: {}'.format(str(e)))
if User.objects.filter(username=super_username).count() > 0:
self.stdout.write('Superuser successfully created.')
... |
mganeva/mantid | qt/python/mantidqt/widgets/samplelogs/test/test_samplelogs_view.py | Python | gpl-3.0 | 939 | 0 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2019 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPD | X - License - Identifier: GPL - 3.0 +
# This file is part of the mantid workbench.
from qtpy.QtWidgets import QApplication
import matplotlib as mpl
mpl.use('Agg') # noqa
from mantid.simpleapi import CreateSampleWorkspace
from m | antidqt.utils.qt.testing import GuiTest
from mantidqt.utils.qt.testing.qt_widget_finder import QtWidgetFinder
from mantidqt.widgets.samplelogs.presenter import SampleLogs
class SampleLogsViewTest(GuiTest, QtWidgetFinder):
def test_deleted_on_close(self):
ws = CreateSampleWorkspace()
pres = SampleL... |
yozel/alskdjBlog | apps/comment/models.py | Python | gpl-3.0 | 3,341 | 0.002394 | from django.contrib.auth.models import User
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db.models.signals import post_save
from django.core.cache import cache
from django.utils.translation import ugettext_lazy as _
... | cache_this:
all_comments = cache.get('comments_for_post/%s/%s/' % (belong_content_type.id, belong_object_id))
if all_comments is None:
all_comments = Comment.objects.select_related('author').filter(
belong_content_type=belong_content_type,
| belong_object_id=belong_object_id,
is_activated=True,
is_published=True,
)
cache.set('comments_for_post/%s/%s/' % (belong_content_type.id, belong_object_id), all_comments)
else:
all_comments = Comment.objects.sel... |
thenewguy/wagtailplus | wagtailplus/wagtailrelations/models.py | Python | bsd-2-clause | 11,444 | 0.004107 | """
Contains application model definitions.
"""
import decimal
import inspect
import six
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_... | imal(
(float(delta) / float(age)) * AUTHORITATIVE_FACTOR
)
def get_categories(self):
"""
Returns queryset of assigned Category instances.
:rtype: django.db.models.query.QuerySet.
"""
return Category.objects.filter(tag__in=self.tags)
def get_ca | tegory_score(self, related):
"""
Returns category score for this instance and specified related
Entry instance.
:param related: the related Entry instance.
:rtype: decimal.Decimal.
"""
score = 0
tags = set(self.tags) & set(related.tags)
total... |
msekletar/systemd | tools/update-dbus-docs.py | Python | gpl-2.0 | 11,862 | 0.003456 | #!/usr/bin/env python3
# SPDX-License-Identifier: LGPL-2.1-or-later
import argparse
import collections
import sys
import os
import subprocess
import io
try:
from lxml import etree
except ModuleNotFoundError as e:
etree = e
try:
from shlex import join as shlex_join
except ImportError as e:
shlex_join ... | us.Introspectable',
'org.freedesktop.DBus.Properties',
]
RED = '\x1b[31m'
GREEN = '\x1b[32m'
YELLOW = '\x1b[33m'
RESET = '\x1b[39m'
def xml_parser():
return etree.XMLParser(no_network=True,
remove_comments=False,
strip_cdata=False,
... | refix, file, is_signal=False):
name = elem.get('name')
klass = 'signal' if is_signal else 'method'
declarations[klass].append(name)
# @org.freedesktop.systemd1.Privileged("true")
# SetShowStatus(in s mode);
for anno in elem.findall('./annotation'):
anno_name = anno.get('name')
... |
arantebillywilson/python-snippets | py2/htp/ch08/fig08_10.py | Python | mit | 1,448 | 0.001381 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# fig08_10.py
#
# Author: Billy Wilson Arante
# Created: 2016/10/10
from rational import Rational
def main():
"""Main"""
# Objects of class Rational
rational1 = Rational() # 1/1
rational2 = Rational(10, 30) # 10/30 reduces to 1/3
rational3 = Ration... | l3, "-", rational2, "=", rational3 - rational | 2
print rational2, "*", rational3, "-", rational1, "=", \
rational2 * rational3 - rational1
# Overloading + implicitly overloads +=
rational1 += rational2 * rational3
print "\nrational1 after adding rational2 * rational3:", rational1
print
# Test comparison operators
print rational... |
maxiimou/project_euler | exercice1.py | Python | lgpl-3.0 | 96 | 0.010417 | mult_of_3_5 = | [el for el in range(1000) if (el % 3 ==0 or el % 5 == 0)]
pr | int(sum(mult_of_3_5))
|
lento/cortex | test/IECoreHoudini/FromHoudiniPolygonsConverter.py | Python | bsd-3-clause | 38,040 | 0.057755 | ##########################################################################
#
# Copyright 2010 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios),
# its affiliates and/or its licensors.
#
# Copyright (c) 2010-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary ... | isInstanceOf( IECore.TypeId( IECoreHoudini.TypeId.FromHoudiniPolygonsConverter ) ) )
converter = IECoreHoudini.FromHoudiniGeometryConverter.createDummy( [ IECore.TypeId.MeshPrimitive ] )
self.assert_( converter.isInstanceOf( IECore | .TypeId( IECoreHoudini.TypeId.FromHoudiniPolygonsConverter ) ) )
# performs geometry conversion
def testDoConversion( self ) :
converter = self.testCreateConverter()
result = converter.convert()
self.assert_( result.isInstanceOf( IECore.TypeId.MeshPrimitive ) )
def testConvertFromHOMGeo( self ) :
geo = sel... |
gnumdk/lollypop | lollypop/controllers.py | Python | gpl-3.0 | 13,447 | 0 | # Copyright (c) 2014-2017 Cedric Bellegarde <[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 3 of the License, or
# (at your option) any later vers... | return
Lp().player.set_volume(scale.get_value())
self._update_position(scale.get_value())
def _on_title_press_button(self, widget, event):
"""
Show/Hide volume control
| @param widget as Gtk.Widget
@param event as Gdk.Event
"""
if event.button != 1:
self.show_hide_volume_control()
return True
def _on_progress_press_button(self, scale, event):
"""
On press, mark player as seeking
@param scale ... |
omaciel/robottelo | tests/foreman/ui/test_sync.py | Python | gpl-3.0 | 5,811 | 0.000172 | """Test class for Custom Sync UI
:Requirement: Sync
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: Repositories
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
from fauxfactory import gen_string
from nailgun import entities
from robottelo import manifests
from robottelo.api.util... | session:
session.repository.create(
product.name,
{'name': repo_name,
'repo_type': REPO_TYPE['docker'],
| 'repo_content.upstream_url': DOCKER_REGISTRY_HUB,
'repo_content.upstream_repo_name': DOCKER_UPSTREAM_NAME}
)
assert session.repository.search(product.name, repo_name)[0]['Name'] == repo_name
result = session.sync_status.synchronize([(product.name, repo_name)])
assert r... |
rayank77b/saveMyConfigs | smc.py | Python | gpl-2.0 | 8,718 | 0.011471 | #!/usr/bin/python
#
# Author = Andrej Frank, IT-Designers GmbH, STZ Softwaretechnik
# Version = 0.0.1 Alpha
# GNU GENERAL PUBLIC LICENSE
#
# what we do:
# - read configuration(user,pass,what to save, where to save)
# - get the config from switchs
# - log in ssh, get the configs/files/dirs
# - store it on git( clone i... | origin.pull()
log(ok=Tru | e, msg="pulled")
return repo
except git.exc.NoSuchPathError:
print "error you must clone the repo first,"
print "execute following commands:\n"
t=repopath.split('/')
print " cd %s"%('/'.join(t[:-1]))
print " git clone %s"%(ENV[C_GIT]['remote'])
print
... |
Azure/azure-linux-extensions | VMBackup/main/workloadPatch/WorkloadUtils/OracleLogBackup.py | Python | apache-2.0 | 2,709 | 0.006645 | #!/usr/bin/env python
#
# VM Backup extension
#
# Copyright 2014 Microsoft Corporation
#
# 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
#
# U... | logbackup.oracleParameter[keyParameter] = valueParameter
def setLocation():
nowTimestamp = datetime.now()
nowTimestamp = nowTimestamp.strftime("%Y%m%d%H%M%S")
fullPath = logbackup.baseLocation + nowTimestamp
os.system('mkdir -m777 '+ fullPath)
return fullPath
def t | akeBackup():
print("logbackup: Taking a backup")
backupPath = setLocation()
if 'oracle' in logbackup.name.lower():
backupOracle = logbackup.command + " -s / as sysdba @" + "/var/lib/waagent/Microsoft.Azure.RecoveryServices.VMSnapshotLinux-1.0.9164.0/main/workloadPatch/scripts/logbackup.sql " + ba... |
pmarks-net/dtella | dtella/modules/pull_gdata.py | Python | gpl-2.0 | 1,879 | 0.001064 | """
Dtella - Google Spreadsheets Puller Module
Copyright (C) 2008 Dtella Labs (http://dtella.org)
Copyright (C) 2008 Paul Marks (http://pmarks.net)
$Id$
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 Foundat... | oogle Spreadsheet..."
def query(self):
def f(url):
return urllib.urlopen(url).read()
d = deferToThread(f, PAGE_TEMPLATE % self.sheet_key)
def cb(result):
config_list = []
doc = xml.dom.minidom.parseString(result)
for c in doc.getElementsByT... | _list.append(str(c.firstChild.nodeValue))
return config_list
d.addCallback(cb)
return d
|
jhl667/galaxy_tools | tools/pindel/pindel.py | Python | apache-2.0 | 16,775 | 0.00775 | #!/usr/bin/env python
import logging
import argparse, os, shutil, subprocess, sys, tempfile, time, shlex, re
import datetime
from multiprocessing import Pool
import vcf
def execute(cmd, output=None):
import subprocess, sys, shlex
# function to execute a cmd and report if an error occur
print(cmd)
try:... | ant, apres))
def pindel2vcf(inputFastaFile, refName, pindel_file, vcf_file):
date = str(time.strftime('%d/%m/%y',time.localtime()))
cmd = "pindel2vcf -p %s -r %s -R %s -d %s -v %s -he 0.05 -ho 0.95 -G" % (pindel_file, inputFastaFile, refName, date, vcf_file)
# Added | hard-coded parameters. JHL
return cmd
def which(cmd):
cmd = ["which",cmd]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
res = p.stdout.readline().rstrip()
if len(res) == 0: return None
return res
def get_bam_seq(inputBamFile, min_size): ### Changed min_size to 40mil. JHL
samtools = ... |
sageskr/domain_mon | code/url_monitor.py | Python | apache-2.0 | 2,606 | 0.011572 | #!/usr/bin/env python
# -*- encoding:utf-8 -*-
__author__ = 'kairong'
#解决crontab中无法执行的问题
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import ConfigParser
import MySQLdb
import requests
import re
from socket import socket, SOCK_DGRAM, AF_INET
from multiprocessing import Process
###函数声明区域
def get_localIP():
... | '''检查域名和关键词,并把结果写入db'''
r = requests.get(url)
if r.status_code <=400 and re.search(unicode(keyword), r.text):
c_result = 0
else:
c_result = 1
status_2_db(id, c_result)
def status_2_db(id, status):
'''把结果写入db'''
conn = MySQLdb.connect(host=db_hostname, user=db_user, passwd=d... | ql_get_id_status = "select status_code from status_code where ID = %d and rep_point = '%s' ;" %(id, local_ip)
cur.execute(sql_get_id_status)
last_code = cur.fetchone()
if last_code:
last_code = last_code[0]
cur_code = last_code * status + status
sql_update_id_status = "update status_... |
VladimirShe/in100gram | in100gram/in100gram/urls.py | Python | apache-2.0 | 278 | 0.014388 | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = | patterns('',
# Examples:
# url(r'^$', 'in100gram.views.home', na | me='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
|
ytisf/PyExfil | pyexfil/network/ICMP/icmp_exfiltration.py | Python | mit | 6,676 | 0.028161 | #!/usr/bin/python
import os
import sys
import zlib
import time
import datetime
import base64
from socket import *
from impacket import ImpactPacket
""" Constants """
READ_BINARY = "rb"
WRITE_BINARY = "wb"
READ_FROM_SOCK = 7000
ICMP_HEADER_SIZE = 27
DATA_SEPARATOR = "::"
DATA_TERMINATOR = "\x12\x13\x... | += 1
# Iterate over the file
for i in range(1, x + 2):
str_send = IamDone[max_packetsize * (i - 1): max_packetsize * i] + DATA_TERMINATOR
icmp.contains(ImpactPacket.Data(str_send))
ip.contains(icmp)
icmp.set_icmp_id(seq_id)
icmp.set_icmp_cksum(0)
icmp.auto_checksum = 1
s.sendto(ip.get_packet(), (ip_add... | ip.contains(icmp)
seq_id += 1
icmp.set_icmp_id(seq_id)
icmp.set_icmp_cksum(0)
icmp.auto_checksum = 1
s.sendto(ip.get_packet(), (ip_addr, 0))
time.sleep(SLEEP)
# Send termination package
str_send = (tail + DATA_SEPARATOR + str(checksum) + DATA_SEPARATOR + str(seq_id) + DATA_TERMINATOR + END_PACKET)
icmp.conta... |
aarora79/sitapt | sitapt/wrangle/pcap/transport.py | Python | isc | 683 | 0.005857 | import os
import sys
import argparse
import pkg_resources # part of setuptools
import socket
from struct import *
import bina | scii
#import submodules
from pcap_globals import *
import tcp
import udp
#global varialbes for this file
#logger = sa_logger.init(globals.PACKAGE_NAME)
def get_transport_info(network_info, pkt_data):
pkt_info = {}
# check which protocol and handle accordingly
protocol = network_info['protocol']
if ... | pkt_info ['protocol'] = str(protocol)
return pkt_info
|
ccri/gensim | gensim/test/test_corpora_dictionary.py | Python | gpl-3.0 | 7,902 | 0.003043 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Unit tests for the `corpora.Dictionary` class.
"""
from collections import Mapping
import logging
import tempfile
import unittest
import os
import os.path
import scipy
import gensim
from ge... |
def testDocFreqForOneDocWithSeveralWord(self):
# two wor | ds
texts = [['human', 'cat']]
d = Dictionary(texts)
expected = {0: 1, 1: 1}
self.assertEqual(d.dfs, expected)
# three words
texts = [['human', 'cat', 'minors']]
d = Dictionary(texts)
expected = {0: 1, 1: 1, 2: 1}
self.assertEqual(d.dfs, expected)
... |
digambar15/openstack-iot | iot/conductor/handlers/driver.py | Python | apache-2.0 | 1,411 | 0.000709 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distribu... | See the License for the specific language governing permissions and
# limitations under the License.
"""IoT Docker RPC handler."""
from docker import errors
from oslo.config import cfg
from iot.common import docker_utils
from iot.openstack.common import log as logging
LOG = logging.getLogger(__name__)
CONF = ... | super(Handler, self).__init__()
self._docker = None
def _encode_utf8(self, value):
return unicode(value).encode('utf-8')
# Device operations
def device_create(self, ctxt, name, device_uuid, device):
LOG.debug('Creating device name %s'
% (name))
def devi... |
yasoob/PythonRSSReader | venv/lib/python2.7/dist-packages/samba/ndr.py | Python | mit | 1,563 | 0 | # -*- coding: utf-8 -*-
# Unix SMB/CIFS implementation.
# Copyright © Jelmer Vernooij <[email protected]> 2008
#
# 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, ... | >.
#
"""Network Data Representation (NDR) marshalling and unmarshalling."""
def ndr_pack(object):
"""Pack a NDR object.
:param object: Object to pack
:return: String object with marshalled object.
"""
ndr_pac | k = getattr(object, "__ndr_pack__", None)
if ndr_pack is None:
raise TypeError("%r is not a NDR object" % object)
return ndr_pack()
def ndr_unpack(cls, data, allow_remaining=False):
"""NDR unpack an object.
:param cls: Class of the object to unpack
:param data: Buffer to unpack
:param... |
scorpilix/Golemtest | golem/transactions/ethereum/ethereumtransactionsystem.py | Python | gpl-3.0 | 2,734 | 0 | import logging
from time import sleep
from ethereum import keys
from golem.ethereum import Client
from golem.ethereum.paymentprocessor import PaymentProcessor
from golem.transactions.transactionsystem import TransactionSystem
log = logging.getLogger('golem.pay')
class EthereumTransactionSystem(Transact... | ()
return gnt, av_gnt, eth
def pay_for_task(self, task_id, payments):
""" Pay for task using Ethereum connector
:param task_id: pay for task with given id
:param dict payments: all payments group by ethereum address
"""
pass
def sync(self):
sy... | : {}".format(e))
syncing = False
else:
sleep(0.5)
|
feeds/igraph | tools/stimulus.py | Python | gpl-2.0 | 56,559 | 0.013897 | #! /usr/bin/env python
import re
import seqdict
import sys
import getopt
import os
version="0.1"
date="Jul 29 2007"
def usage():
print "Stimulus version", version, date
print sys.argv[0], "-f <function-file> -t <type-file> -l language "
print ' ' * len(sys.argv[0]), "-i <input-file> -o <output-file>"
... | key", k) )
self.tokens.append( ("indent", "") )
keys=[]
if self.tokens:
return self.tokens.pop(0)
############# | ###################################################################
class PParser:
def parse(self, stream):
lex=PLexer(stream)
val=seqdict.seqdict()
val_stack=[val, None]
nam_stack=[None, None]
tok=lex.token()
while not tok[0]=="eof":
if tok[0]=="... |
tamentis/psutil | psutil/_compat.py | Python | bsd-3-clause | 7,623 | 0.002624 | #!/usr/bin/env python
#
# $Id$
#
# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Module which provides compatibility with older Python versions."""
__all__ = ["namedtuple", "property", "de... | s two
# purposes, generating informative error messages and preventing
# template injection attacks.
if isinstance(field_names, basestring):
# names separated by whitespace and/or commas
field_names = field_names.replace(',', ' ').split()
field_names = tuple(map(... | t min(c.isalnum() or c=='_' for c in name) or _iskeyword(name)
or not name or name[0].isdigit() or name.startswith('_')
or name in seen):
names[i] = '_%d' % i
seen.add(name)
field_names = tuple(names)
for name in (typena... |
tbhartman/eng | material/predefined.py | Python | apache-2.0 | 1,319 | 0.006065 | """ Copyright (c) 2010, Tim Hartman
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, softwa... | d 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.
Authored by: Tim Hartman"""
from eng.material import elastic
def carbon_fiber_generic():
mat = elastic.TransverselyIsotropic(155e9, 0.248, 12.1e9, 0.458, 4.4e9)
cte = elastic.CoefficientOfExpansion("t... |
niamoto/niamoto-core | niamoto/data_publishers/r_data_publisher.py | Python | gpl-3.0 | 4,420 | 0 | # coding: utf-8
from rpy2.robjects import conversion
from rpy2.robjects import r
from rpy2.robjects import pandas2ri
from rpy2.robjects import default_converter
from rpy2.robjects.conversion import localconverter
from rpy2.rinterface import rternalize, StrSexpVector
from rpy2.robjects import globalenv
import pandas as... | mport RasterDataPublisher
class RDataPublisher(BaseDataPublisher):
"""
R script data publisher.
"""
def __init__(self, r_script_path):
super(RDataPublisher, self).__init__()
self.r_script_path = r_script_path
@classmethod
def get_key(cls):
raise NotImplementedError()
... | smethod
def get_description(cls):
return "R script."
def _process(self, *args, **kwargs):
with localconverter(default_converter + pandas2ri.converter):
globalenv['get_occurrence_dataframe'] = \
self.get_occurrence_dataframe
globalenv['get_plot_dataframe']... |
opentok/Opentok-Python-SDK | sample/HelloWorld/helloworld.py | Python | mit | 660 | 0.001515 | from flask import Flask, render_template
from op | entok import Client
import os
try:
api_key = os.environ["API_KEY"]
api_secret = os.environ["API_SECRET"]
except Exception:
ra | ise Exception("You must define API_KEY and API_SECRET environment variables")
app = Flask(__name__)
opentok = Client(api_key, api_secret)
session = opentok.create_session()
@app.route("/")
def hello():
key = api_key
session_id = session.session_id
token = opentok.generate_token(session_id)
return ren... |
kermit666/posterwall | posterwall/apps/events/models.py | Python | agpl-3.0 | 294 | 0.003401 | from django.db import models
# Create your models here.
class Event(models.Model):
url = models.URLField | (null=True)
img_url = models.URLField(null=True)
title = models.Char | Field(max_length=200)
description = models.TextField()
def __str__(self):
return self.title
|
harshilasu/LinkurApp | y/google-cloud-sdk/platform/gsutil/third_party/boto/tests/unit/provider/test_provider.py | Python | gpl-3.0 | 16,358 | 0.000122 | #!/usr/bin/env python
from datetime import datetime, timedelta
from tests.unit import unittest
import mock
import os
from boto import provider
from boto.compat import expanduser
INSTANCE_CONFIG = {
'allowall': {
u'AccessKeyId': u'iam_access_key',
u'Code': u'Success',
u'Expiration': u'201... | key')
self.assertEqual(p.secret_key, 'cfg_secret_key')
self.assertEqual(p.security_token, 'cfg_security_token')
def test_keyring_is_used(self):
self.config = {
'Credentials': {
| 'aws_access_key_id': 'cfg_access_key',
'keyring': 'test',
}
}
import sys
try:
import keyring
imported = True
except ImportError:
sys.modules['keyring'] = keyring = type(mock)('keyring', '')
imported = False... |
ionutbalutoiu/ironic | ironic/conductor/manager.py | Python | apache-2.0 | 116,241 | 0.000009 | # coding=utf-8
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# Copyright 2013 International Business Machines Corporation
# 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
# ... | .')),
cfg.BoolOpt('send_sensor_data',
default=False,
help=_('Enable sending sensor data message via the '
'notification bus')),
cfg.I | ntOpt('send_sensor_data_interval',
default=600,
help=_('Seconds between conductor sending sensor data message'
' to ceilometer via the notification bus.')),
cfg.ListOpt('send_sensor_data_types',
default=['ALL'],
help=_('List of comm... |
TAMU-CPT/galaxy-tools | tools/gff3/fix_ncbi.py | Python | gpl-3.0 | 1,293 | 0.001547 | #!/usr/bin/env python
import sys
import logging
import argparse
from gff3 import feature_lambda, feature_test_type
from CPT_GFFParser import gffParse, gffWrite
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
def safe_qualifiers(quals):
unsafe_quals = ("ID", "Parent", "Name")
new_qua... | ew_quals[key] = value
return new_quals
def fix_ncbi(gff3):
for rec in gffParse(gff3):
for feature in feature_lambda(
rec.features, feature_test_type, {"type": "gene"}, subfeatures=True
):
CDSs = list(
feature_lambda(
feature.sub_feat... | == 1:
feature.qualifiers.update(safe_qualifiers(CDSs[0].qualifiers))
gffWrite([rec], sys.stdout)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="correct their terrible GFF data")
parser.add_argument("gff3", type=argparse.FileType("r"), help="GFF3 annotations"... |
eavatar/ava | src/eavatar.ava/ava/core/data.py | Python | bsd-3-clause | 8,549 | 0.000117 | # -*- coding: utf-8 -*-
"""
Data engine implementation based on lighting memory database
(http://symas.com/mdb/).
The Lmdb is initialized, the access needs to use its binding API, though.
Extension packages may provide higher-level APIs based on this.
"""
from __future__ import absolute_import, division, unicode_litera... | s revisions if required.
:return:
"""
return self._cursor.delete(True)
def remove(self, key):
"""
Delete the current element and move to the next, returning True on
success or False if the store was empty
:return:
"""
if isinstance(key, unicod... | utf-8')
if not self._cursor.set_key(key):
return False
return self._cursor.delete(True)
def seek(self, key):
"""
Finds the document with the provided ID and moves position to its first revision.
:param key:
:return: True if found; False, otherwise.
... |
dsysoev/fun-with-algorithms | string/stringsearch.py | Python | mit | 809 | 0.002472 |
"""
Naive string matcher implementation
"""
from __future__ import print_function
def naive_string_matcher(string, target):
""" returns all indices where substring target occurs in string """
snum = len(string)
tnum = len(target)
matchlist = []
for index in range(snum - tnum + 1):
if str... | chlist
if __name__ in '__main__':
for STR, TARGET in [
('abcdefabcdeab', 'ab'),
('abababcdefabcdeab', 'abab'),
('ababcdef | abcdeab', 'abc'),
('abcdefabcdeab', 'c'),
('abcdefabcdeab', 'abcde'),
]:
POS = naive_string_matcher(STR, TARGET)
print('string: {:20s} target: {:5s} positions: {}'.format(STR, TARGET, POS))
|
wikimedia/thumbor-video-loader | setup.py | Python | mit | 886 | 0 | # -*- co | ding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='wikimedia_thumbor_video_loader',
version='0.1.1',
url='https://github.com/wikimedia/thumbor-video-loader',
license='MIT',
author='Gilles Dubuc, Wikimedia Foundation',
description='Thumbor video loader',
packages=find... | platforms='any',
install_requires=[
'thumbor',
],
extras_require={
'tests': [
'pyvows',
'coverage',
],
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT Licen... |
jantman/gw2copilot | gw2copilot/utils.py | Python | agpl-3.0 | 5,105 | 0.000588 | """
gw2copilot/utils.py
The latest version of this package is available at:
<https://github.com/jantman/gw2copilot>
################################################################################
Copyright 2016 Jason Antman <[email protected]> <http://www.jasonantman.com>
This file is part of gw2copilot.
... | y contributions or improvements
either as a pull request on GitHub, or to me via email.
################################################################################
AUTHORS:
Jason Antman <[email protected]> <http://www.jasonantman.com>
###########################################################################... | me__)
def make_response(s):
"""
Return the value for a Twisted/Klein response; if running under python 3+
utf-8 encode the response, otherwise return ``s``.
:param s: response string
:type s: str
:return: response string, possibly encoded
:rtype: str
"""
if sys.version_info[0] < 3... |
tylerdave/devpi-plumber | devpi_plumber/client.py | Python | bsd-3-clause | 4,716 | 0.001696 | import re
import sys
import logging
import contextlib
from collections import OrderedDict
from six import iteritems, StringIO
from six.moves.urllib.parse import urlsplit, urlunsplit
from devpi.main import main as devpi
from twitter.common.contextutil import mutable_sys, temporary_dir
logging.getLogger("requests").se... | alse, an exception will be raised instead of making an non-volatile index volati | le.
"""
is_volatile = 'volatile=True' in client.modify_index(index)
if not is_volatile and not force_volatile:
raise DevpiClientError('Index {} is not volatile.'.format(index))
client.modify_index(index, volatile=True)
try:
yield
finally:
client.modify_index(index, vola... |
google-research/ssl_detection | third_party/tensorpack/tensorpack/models/regularize.py | Python | apache-2.0 | 6,528 | 0.002451 | # -*- coding: utf-8 -*-
# File: regularize.py
import re
import tensorflow as tf
from ..compat import tfv1
from ..tfutils.common import get_tf_version_tuple
from ..tfutils.tower import get_current_tower_context
from ..utils import logger
from ..utils.argtools import graph_memoized
from .common import layer_register
... | IABLES)
else:
params = tfv1.trainable_variables()
names = []
with tfv1.name_scope(name + '_internals'):
costs = []
for p in params:
para_name = p.op.name
if re.search(regex, para_name):
regloss = func( | p)
assert regloss.dtype.is_floating, regloss
# Some variables may not be fp32, but it should
# be fine to assume regularization in fp32
if regloss.dtype != tf.float32:
regloss = tf.cast(regloss, tf.float32)
costs.append(... |
Kami/munin_exchange | munin_exchange/apps/core/views.py | Python | bsd-3-clause | 1,990 | 0.042211 | import markdown
from django.shortcuts import render_to_response, get_object_or_404, HttpResponse, HttpResponseRedirect, Http404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.views.decorators.csrf import csrf_exempt
... | re user can update their profile.
@param request: Django request object.
@return: Rendered profile.html.
'''
if request.method == 'POST':
form = ProfileForm(request.POST)
if form.is_valid():
data = form.cleaned_data
print data
#Update user with form data
request.user.first_name = data['first_name... | lly updated profile!')
else:
#Try to pre-populate the form with user data.
form = ProfileForm(initial = {
'first_name': request.user.first_name,
'last_name': request.user.last_name,
'email': request.user.email,
})
return render_to_response('django_rpx_plus/profile.html', {
'form': form,
... |
dash-dash/AutobahnPython | examples/asyncio/wamp/overview/backend.py | Python | mit | 1,072 | 0.001866 | from os import environ
import asyncio
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner
class MyComponent(ApplicationSession):
@asyncio.coroutine
def onJoin(self, details):
# a remote procedure; see frontend.py for a Python front-end
# that calls this. Any language with WA... | tails
debug=False, # optional; log even more details
)
ru | nner.run(MyComponent)
|
iaz3/ModParser | modparser/__init__.py | Python | gpl-3.0 | 983 | 0.001017 | # !/usr/ | bin/env python3
"""
Custom Bi Directional Binary Data Parser
ModParser
"""
# ====================== GPL License and Copyright Notice ======================
# This file is part of ModParser
# Copyright (C) 2017 Diana Land
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of t... | by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General... |
mfraezz/osf.io | admin_tests/nodes/test_serializers.py | Python | apache-2.0 | 1,496 | 0.000668 | from nose.tools import * # noqa: F403
from tests.base import AdminTestCase
from osf_tests.factories import NodeFactory, UserFactory
from osf.utils.permissions import ADMIN
from admin.nodes.serializers import serialize_simple_user_and_node_permissions, serialize_node
class TestNodeSerializers(AdminTestCase):
def... | assert_equal(info['id'], node._id)
assert_equal(info['public'], node.is_public)
assert_equal(len(info['contributors']), 1)
assert_false(info['deleted'])
def test_serialize_deleted(self):
node = NodeFactory()
info = serialize_node(node)
assert_false(info['deleted'])
... | assert_false(info['deleted'])
def test_serialize_simple_user(self):
user = UserFactory()
node = NodeFactory(creator=user)
info = serialize_simple_user_and_node_permissions(node, user)
assert_is_instance(info, dict)
assert_equal(info['id'], user._id)
assert_equal(in... |
Samsung/ADBI | arch/arm64/tests/a64_blr.py | Python | apache-2.0 | 1,719 | 0.006981 | import random
from common import *
class test_a64_blr(TemplateTest):
def gen_rand(self):
while True:
yield {'reg': random.choice(GPREGS64 + ['x30']),
'label_idx': random.randint(0, self.__label_count - 1)}
def __init__(self):
self.__label_count = 8
s... | abel_idx],
| 'x1':ret_label})
yield state.restore()
def test_end(self):
for i in xrange(1, len(self.symbols), 2):
yield ' .skip %d' % random.randrange(512, 2048, 4)
yield self.symbols[i] + ':'
yield ' ldr\t\tx0, ={0}'.format(hex(self.randvals[i]))
y... |
Azure/azure-sdk-for-python | sdk/sql/azure-mgmt-sql/tests/test_cli_mgmt_sql_vulnerability_assessment.py | Python | mit | 18,092 | 0.006356 | # 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.
#----------------------------------------------------------------------... | }
result = self.mgmt_client.managed_dat | abase_vulnerability_assessments.create_or_update(resource_group_name=RESOURCE_GROUP, managed_instance_name=MANAGED_INSTANCE_NAME, database_name=DATABASE_NAME, vulnerability_assessment_name=VULNERABILITY_ASSESSMENT_NAME, parameters=BODY)
#--------------------------------------------------------------------------
... |
DevHugo/zds-site | zds/tutorialv2/models/models_versioned.py | Python | gpl-3.0 | 45,439 | 0.002665 | # coding: utf-8
import json as json_writer
from git import Repo
import os
import shutil
import codecs
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from zds.settings import ZDS_A... | stance(self.children[0], Extract):
return 2
else:
return 1 + max([i.get_tree_level() for i in self.children])
def has_child | _with_path(self, child_path):
"""Check that the given path represent the full path
of a child of this container.
:param child_path: the full path (/maincontainer/subc1/subc2/childslug) we want to check
:return: ``True`` if child is found, ``False`` otherwise
:rtype: bool
... |
google/timesketch | timesketch/lib/analyzers/ssh_sessionizer.py | Python | apache-2.0 | 3,925 | 0.003567 | """SSH sessionizing sketch analyzer plugin."""
from __future__ import unicode_literals
import re
from timesketch.lib.analyzers import manager
from timesketch.lib.analyzers import sessionizer
# Pattern for SSH events message:
# '[sshd] [{process_id}]: {message}'
SSH_PATTERN = re.compile(r'^\[sshd\] \[(?P<process_id>... | s created.
"""
NAME = 'ssh_ | sessionizer'
DISPLAY_NAME = 'SSH sessions'
DESCRIPTION = 'SSH sessions based on client IP address and port number'
query = 'reporter:"sshd"'
session_num = 0
session_type = 'ssh_session'
def run(self):
"""Entry point for the analyzer.
Allocates events from a SSH connection with... |
camradal/ansible | lib/ansible/utils/display.py | Python | gpl-3.0 | 11,938 | 0.002429 | # (c) 2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any lat... | should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import fcntl
import textwrap
import os
import random
import subprocess
import sys
import time
import ... | s C
from ansible.errors import AnsibleError
from ansible.utils.color import stringc
from ansible.module_utils._text import to_bytes, to_text
try:
# Python 2
input = raw_input
except NameError:
# Python 3, we already have raw_input
pass
logger = None
#TODO: make this a logging callback instead
if C.D... |
bhdn/jurt | jurtlib/command.py | Python | gpl-2.0 | 14,645 | 0.004575 | #
# Copyright (c) 2011,2012 Bogdano Arendartchuk <[email protected]>
#
# Written by Bogdano Arendartchuk <[email protected]>
#
# This file is part of Jurt Build Bot.
#
# Jurt Build Bot is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published... | afterwards.
To list the targets, use jurt-list-targets.
To see the configuration used by jurt, use jurt-showrc.
Also, jurt-root-command should be able to use sudo for running commands as
root. Run jurt-test-sudo for checking whether it is properly configured.
"""
def init_parser(self, parser | ):
JurtCommand.init_parser(self, parser)
parser.add_option("-t", "--target", type="string",
help="Target packages are built for")
parser.add_option("-b", "--stop", default=None, metavar="STAGE",
help="Stop at build stage STAGE and drops into a shell")
pars... |
google/google-ctf | third_party/edk2/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Eiffel.py | Python | apache-2.0 | 3,581 | 0.002234 | """Support Eiffel-style preconditions and postconditions.
For example,
class C:
def m1(self, arg):
require arg > 0
return whatever
ensure Result > arg
can be written (clumsily, I agree) as:
class C(Eiffel):
def m1(self, arg):
return whatever
def m1_pre(self... | lookup must be done
# using the class.
try:
self.pre = getattr(inst, self.__name__ + "_pre")
except AttributeError:
self.pre = None
try:
self.post = getattr(inst, self.__name__ + "_post")
except AttributeError:
self.post =... | apply(self.pre, args, kw)
Result = apply(self.func, (self.inst,) + args, kw)
if self.post:
apply(self.post, (Result,) + args, kw)
return Result
class EiffelHelper(MetaHelper):
__methodwrapper__ = EiffelMethodWrapper
class EiffelMetaClass(MetaClass):
__he... |
BostonMarcin/django_kurs | biblio/settings.py | Python | mit | 2,152 | 0.000465 | """
Django settings for biblio project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
imp... | rib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'shelf',
'contact',
'rental'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.con... | ssionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'biblio.urls'
WSGI_APPLICATION = 'biblio.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES ... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2021_02_01/aio/operations/_virtual_hub_bgp_connection_operations.py | Python | mit | 18,062 | 0.004927 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | 'virtualHubName': self._serialize.url("virtual_hub_name", virtual_hub_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parame... |
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
... |
brettchien/PyBLEWrapper | pyble/const/profile/phone_alert_status.py | Python | mit | 26 | 0.038462 | N | AME="Phone Alert Stat | us"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.