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
ANTsX/ANTsPy
tests/test_viz.py
Python
apache-2.0
3,081
0.01915
""" Test ants.learn module nptest.assert_allclose self.assertEqual self.assertTrue """ import os import unittest from common import run_tests from tempfile import mktemp import numpy as np import numpy.testing as nptest import ants class TestModule_surface(unittest.TestCase): def setUp(self): pass ...
.threshold_image( ch2i, "Otsu", 3 ) wm = ants.threshold_image( ch2seg, 3, 3 ) kimg = ants.weingarten_image_curvature(
ch2i, 1.5 ).smooth_image( 1 ) rp = [(90,180,90), (90,180,270), (90,180,180)] filename = mktemp(suffix='.png') result = ants.vol( wm, [kimg], quantlimits=(0.01,0.99), filename=filename) class TestModule_render_surface_function(unittest.TestCase): def setUp(self): pass def te...
nashve/mythbox
resources/lib/IMDbPY/bin/get_character.py
Python
gpl-2.0
1,570
0.001274
#!/usr/bin/env python """ get_character.py Usage: get_character "characterID" Show some info about the character with the given characterID (e.g. '0000001' for "Jesse James", using 'http' or 'mobile'). Notice that characterID, using 'sql', are not the same IDs used on the web. """ import sys # Import the IMDbPY pac...
' % sys.argv[0] sys.exit(2) characterID = sys.argv[1] i = imdb.IMDb() out_encoding = sys.stdout.encoding or sys.getdefaultencoding() try: # Get a character object with the data about the character identified by # the given characterID. character = i.get_character(characterID) except imdb.IMDbError, ...
character: print 'It seems that there\'s no character with characterID "%s"' % characterID sys.exit(4) # XXX: this is the easier way to print the main info about a character; # calling the summary() method of a character object will returns a string # with the main information about the character. # Obviously ...
waynesun09/tp-libvirt
libvirt/tests/src/virsh_cmd/monitor/virsh_domblkstat.py
Python
gpl-2.0
2,304
0
from autotest.client.shared import error from virttest import virsh from virttest import libvirt_xml from virttest import utils_libvirtd def run(test, params, env): """ Test command: virsh domblkstat. The command get device block stats for a running domain. 1.Prepare test environment. 2.When the...
ip() err = result.stderr.strip() # recover libvirtd service start if libvirtd == "off": utils_libvirtd.libvirtd_start() # check status_error if status_err
or == "yes": if status == 0 or err == "": raise error.TestFail("Run successfully with wrong command!") elif status_error == "no": if status != 0 or output == "": raise error.TestFail("Run failed with right command")
vasiliykochergin/euca2ools
euca2ools/commands/autoscaling/describemetriccollectiontypes.py
Python
bsd-2-clause
1,989
0
# Copyright 2013 Eucalyptus Sys
tems, Inc. # # Redistribution and us
e of this software in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # Redistributions in binary form must ...
alexbruy/QGIS
python/plugins/processing/algs/gdal/GdalUtils.py
Python
gpl-2.0
6,616
0.001663
# -*- coding: utf-8 -*- """ *************************************************************************** GdalUtils.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com *****************************...
glines @staticmethod def getConsoleOutput(): return GdalUtils.consoleOutput @staticmethod def getSupportedRasters(): if not gdalAvailable: return {} if GdalUtils.supportedRasters is not None: return GdalUtils.support
edRasters if gdal.GetDriverCount() == 0: gdal.AllRegister() GdalUtils.supportedRasters = {} GdalUtils.supportedRasters['GTiff'] = ['tif'] for i in range(gdal.GetDriverCount()): driver = gdal.GetDriver(i) if driver is None: continue ...
rpm5/createrepo_c
acceptance_tests/tests/base.py
Python
gpl-2.0
12,537
0.001276
import os import re import time import shutil import pprint import filecmp import os.path import tempfile import unittest import threading import subprocess from .fixtures import PACKAGESDIR OUTPUTDIR = None OUTPUTDIR_LOCK = threading.Lock() def get_outputdir(): global OUTPUTDIR if OUTPUTDIR: return ...
.outdir = get_outputdir() self.tcdir = os.path.join(self.outdir, self.__class__.__name__) if not os.path.exists(self.tcdir): os.mkdir(s
elf.tcdir) if self.__class__.__doc__: description_fn = os.path.join(self.tcdir, "description") open(description_fn, "w").write(self.__class__.__doc__+'\n') unittest.TestCase.__init__(self, *args, **kwargs) self.tdir = None # Test dir for the current test ...
markokr/cc
cc/daemon/logtail.py
Python
bsd-2-clause
12,194
0.009923
#! /usr/bin/env python """ Logfile tailer for rotated log files. Supports 2 operating modes: classic, rotated. Assumes that: . All log files reside in the same directory. . We can find last log file by sorting the file list alphabetically. In classic mode: . When log is switched, the tailer continues tailing from th...
lagging %i bytes behind", lag) if lag > self.lag_maxbytes: self.log.warning
("lag too big, skipping") self.logfile = self.saved_fpos = None else: self.log.warning ("cannot determine lag, skipping") self.logfile = self.saved_fpos = None except IOError: pass self.save_file = open (sfn, "a") def coun...
eoyilmaz/anima
tests/arnold/test_base85.py
Python
mit
5,868
0.001022
# -*- coding: utf-8 -*- from anima.render.arnold import base85 import unittest import struct class Base85TestCase(unittest.TestCase): """tests the base85 module """ def setup(self): """setup the test """ pass def test_arnold_b85_encode_is_working_properly(self): """t...
"testing if arnold_b85_decode is unpacking zeros properly """ raw_data = [ struct.pack('f', 0.0), struct.pack('ffff', 0.0, 0.0, 3.484236717224121, 0.0) ] encoded_data = [ 'z', 'zz8^RH(z' ] for i in range(len(raw_d
ata)): self.assertEqual( raw_data[i], base85.arnold_b85_decode(encoded_data[i]) ) def test_arnold_b85_decode_unpacks_ones_properly(self): """testing if arnold_b85_decode is unpacking zeros properly """ raw_data = [ struct.p...
samuelpulfer/icinga-flashlight
bin/blinkdingsdo.py
Python
mit
5,168
0.033902
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys, time, socket, logging, signal import RPi.GPIO as GPIO from threading import Thread from daemon import D
aemon def blinkdingsdo():
HOST = '' # Symbolic name meaning all available interfaces PORT = 8888 # Arbitrary non-privileged port logfile = '/var/log/blinkdingdo.log' logging.basicConfig(filename=logfile,format='%(asctime)s %(name)s %(levelname)s:%(message)s' ,level=logging.DEBUG) mylog = logging.getLogger("default") mylog.info("Beginn Lo...
lmcro/webserver
admin/wizards/flcache.py
Python
gpl-2.0
7,353
0.01292
# -*- coding: utf-8 -*- # # Cherokee-admin's Common Static wizard # # Authors: # Alvaro Lopez Ortega <alvaro@alobbs.com> # # Copyright (C) 2001-2014 Alvaro Lopez Ortega # # This program is free software; you can redistribute it and/or # modify it under the terms of version 2 of the GNU General Public # License as ...
)s %(rule_pre)s!match!right = header %(rule_pre)s!match!right!complete = 0 %(rule_pre)s!match!right!header = Accept-Encoding %(rule_pre)s!match!right!type = provided %(rule_pre)s!flcache = allow %(rule_pre)s!flcache!policy = all_but_forbidden %(rule_pre)s!encoder!gzip = allow """ GLOBAL_CACHE_CONF = """ %(rule_pre)s
!match!final = 0 %(rule_pre)s!match = directory %(rule_pre)s!match!directory = / %(rule_pre)s!flcache = allow %(rule_pre)s!flcache!policy = explicitly_allowed """ PURGE_METHOD_CONF = """ %(rule_pre)s!match!final = 1 %(rule_pre)s!match = method %(rule_pre)s!match!method = purge %(rule_pre)s!handler = admin %(rule_pre)s...
zirou30/python_student
65.py
Python
gpl-3.0
191
0.010695
'''
hacking = 'Pentest' hacking.lower() == 'pentest' Out[19]: True Retornou True pq a função built-in do python lower(), converteu toda a string atribuída
em hacking para minúscula. '''
alanmcruickshank/superset-dev
superset/models/annotations.py
Python
apache-2.0
1,544
0
"""a collection of Annotation-related models""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from flask_appbuilder import Model from sqlalchemy import ( Column, DateTime, ForeignKey, Index, Integer, String, Text...
key=True) name = Column(String(250)) descr = Column(Text) def __repr__(self): return self.name class Annotation(Model, AuditMixinNullable): """Time-related annotation""" __tablename__ = 'annotation' id = Column(Integer, primary_key=True) start_dttm = Column(DateTime) end_dtt...
descr = Column(Text) layer = relationship( AnnotationLayer, backref='annotation') __table_args__ = ( Index('ti_dag_state', layer_id, start_dttm, end_dttm), ) @property def data(self): return { 'start_dttm': self.start_dttm, 'end_dttm': self.e...
prairiesariea/wsync
src/syncwrap/Helper.py
Python
gpl-3.0
1,723
0.005223
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # # Copyright 2015 Prairies Ariea # # This file is part of Files Sync. # # Files Sync 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 th...
on. # # Files Sync 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 th
e # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Files Sync. If not, see <http://www.gnu.org/licenses/>. # ## import inspect import sys import os import re class Helper: def lineno(self): return inspect.currentframe().f_...
devs1991/test_edx_docmode
venv/lib/python2.7/site-packages/scipy/spatial/kdtree.py
Python
agpl-3.0
37,132
0.005521
# Copyright Anne M. Archibald 2008 # Released under the scipy license from __future__ import division, print_function, absolute_import import sys import numpy as np from heapq import heappush, heappop import scipy.sparse __all__ = ['minkowski_distance_p', 'minkowski_distance', 'distance_matrix', ...
: (N, K) array_like Input array. p : float, 1 <= p <= infinity Which Minkowski p-norm to use. Examples -------- >>> minkowski_distance([[0,0],[0,0]], [[1,1],[0,1]]) array([ 1.41421356, 1. ]) """ x = np.asarray(x) y = np.asarray(y) if p
== np.inf or p == 1: return minkowski_distance_p(x, y, p) else: return minkowski_distance_p(x, y, p)**(1./p) class Rectangle(object): """Hyperrectangle class. Represents a Cartesian product of intervals. """ def __init__(self, maxes, mins): """Construct a hyperrectangle.""...
robbiet480/home-assistant
homeassistant/components/isy994/light.py
Python
apache-2.0
4,198
0.000238
"""Support for ISY994 lights.""" from typing import Callable, Dict from pyisy.constants import ISY_VALUE_UNKNOWN from homeassistant.components.light import ( DOMAIN as LIGHT, SUPPORT_BRIGHTNESS, LightEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.helpers.restore_state im...
ight") @property def device_state_attributes(self) -> Dict: """Return the light attributes.""" attribs = super().device_state_attributes attribs[ATTR_LAST_BRIGHTNESS] = self._last_brightness return attribs @property def supported_features(self): """Flag supporte...
"""Restore last_brightness on restart.""" await super().async_added_to_hass() self._last_brightness = self.brightness or 255 last_state = await self.async_get_last_state() if not last_state: return if ( ATTR_LAST_BRIGHTNESS in last_state.attributes ...
gnocchixyz/gnocchi
gnocchi/storage/s3.py
Python
apache-2.0
9,452
0
# -*- encoding: utf-8 -*- # # Copyright © 2016-2018 Red Hat, 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 ap...
version=3): name = '%s_%s_%s' % ( aggregation, utils.timespan_total_seconds(split_key.sampling), split_key, ) return name + '_v%s' % version if version else name @staticmethod def _prefix(metric): return
str(metric.id) + '/' def _put_object_safe(self, Bucket, Key, Body): put = self.s3.put_object(Bucket=Bucket, Key=Key, Body=Body) if self._consistency_stop: def _head(): return self.s3.head_object(Bucket=Bucket, Key=Key, IfMatch...
ezequielpereira/Time-Line
libs/wx/tools/Editra/src/syntax/_postscript.py
Python
gpl-3.0
9,149
0.002514
############################################################################### # Name: postscript.py # # Purpose: Define Postscript syntax for highlighting and other features # # Author: Cody Precord <cprecord@editra.org> # ...
##################### """ FILE: postscript.py AUTHOR: Cody Precord @summary: Lexer configuration module for PostScript. (case sensitive) @todo: l3 keywords and ghostscript """ __author__ = "Cody Precord <cprecord@editra.org>" __svnid__ = "$Id: _postscript.py 63834 2010-04-03 06:04:33Z CJP $" __revision__ = "$Revisio...
-------------------------------------------------------------# # Imports import wx.stc as stc # Local Imports import syndata #-----------------------------------------------------------------------------# #---- Keyword Specifications ----# # PS Level 1 Operators PS_L1 = (0, "$error = == FontDirectory StandardEncodi...
plotly/plotly.py
packages/python/plotly/plotly/validators/scatterpolar/marker/colorbar/_showexponent.py
Python
mit
554
0
impor
t _plotly_utils.basevalidators class ShowexponentValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="showexponent", parent_name="scatterpolar.marker.colorbar", **kwargs ): super(ShowexponentValidator, self).__init__( ...
st", "none"]), **kwargs )
nuclear-wizard/moose
tutorials/darcy_thermo_mech/step07_adaptivity/problems/step7abc.py
Python
lgpl-2.1
3,210
0.011838
#!/usr/bin/env python3 #* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICENSE for details #* https://www.gnu.org/licenses/lgp...
range=[300, 350], cmap='viridis') cbar = chigger.exodus.ExodusColorBar(temp_a, viewport=[0.9,0,1,1], length=0.8, width=0.3, colorbar_origin=[0....
cbar.setOptions('primary', title='Temperature (K)', font_size=28, font_color=[0,0,0]) time = chigger.annotations.TextAnnotation(position=[0.45,0.3], font_size=48, text_color=[0,0,0], viewport=[0,0,1,1], justification='ce...
BigEgg/LeetCode
Python/LeetCode/_051_100/_058_LengthOfLastWord.py
Python
mit
190
0.005263
class Solution:
def lengthOfLastWord(self, s: str) -> int: if not s: retur
n 0 l = s.split() if not l: return 0 return len(l[-1])
joshbohde/scikit-learn
sklearn/linear_model/logistic.py
Python
bsd-3-clause
4,271
0.001639
import numpy as np from ..base import ClassifierMixin from ..linear_model.base import CoefSelectTransformerMixin from ..svm.base import BaseLibLinear from ..svm import liblinear class LogisticRegression(BaseLibLinear, ClassifierMixin, CoefSelectTransformerMixin): """ Logistic Regress...
self._get_bias()) return probas[:, np.argsort(self.label_)] def predict_log_proba(self, X): """ Log of Probability estimates. The returned estimates for all classes are ordered by the label of classes. Parameters ---------- X : array-like, shape = [...
e log-probabilities of the sample for each class in the model, where classes are ordered by arithmetical order. """ return np.log(self.predict_proba(X))
OxPython/Python_bytes_to_string
src/bytes_to_string.py
Python
epl-1.0
545
0.009208
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on Jul 16, 2014 @author: anroco In Python, how to convert bytes to string? En Python,
¿Cómo convertir bytes a string? ''' #create a bytes object b = b'El ni\xc3\xb1o come camar\xc3\xb3n' print(b) #return an encoded version of 'b' as a string object. Default encoding #is 'utf-8'. s = b.decode() print(type(s)) print(s) #create a bytes object encoded using 'cp855
' b = b'\xd8\xe1\xb7\xeb\xa8\xe5 \xd2\xb7\xe1' #return a string using decode 'cp855' s = b.decode('cp855') print(s)
cloudevents/sdk-python
cloudevents/sdk/event/v03.py
Python
apache-2.0
4,218
0
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
nt: self.Set("extensions", extensions) return self def SetContentType(self, contentType: str) -> base.BaseEven
t: self.Set("datacontenttype", contentType) return self def SetContentEncoding(self, contentEncoding: str) -> base.BaseEvent: self.Set("datacontentencoding", contentEncoding) return self @property def datacontentencoding(self): return self.ContentEncoding() @da...
yakxxx/memek
crawler/api_client.py
Python
mit
2,755
0.013067
#coding: utf-8 import requests as req from conf import * import logging import re from datetime import datetime class Api(object): def get_promoted(self, page=1): promoted = self._get('links/promoted', api_params = self._build_api_params({'page': page})) self._clear_promoted(promoted) retu...
m-%d %H:%M:%S') p['article_id'] = p['id'] del p['id'] return promoted def _clear_comments(self, comments): for c in comments: c['date'] = datetime.strptime(c['date'], '%Y-%m-%d %H:%M:%S') c['comment_id'] = c['id'] del c['id'] retur...
s ApiError(Exception): pass class WrongData(Exception): pass
vasylbo/aiohttp
tests/test_streams.py
Python
apache-2.0
21,126
0
"""Tests for streams.py""" import asyncio import unittest from unittest import mock from aiohttp import streams from aiohttp import test_utils class TestStreamReader(unittest.TestCase): DATA = b'line1\nline2\nline3\n' def setUp(self): self.loop = asyncio.new_event_loop() asyncio.set_event_...
self.assertEqual(b'', data) stream.feed_eof() data = self.loop.run_until_complete(stream.read()) self.assertEqual(self.DATA, data) def test_read(self): # Read bytes. stream = self._make_one() read_task = asyncio.Task(stream.read(30), loop=self.loop) ...
): stream.feed_data(self.DATA) self.loop.call_soon(cb) data = self.loop.run_until_complete(read_task) self.assertEqual(self.DATA, data) stream.feed_eof() data = self.loop.run_until_complete(stream.read()) self.assertEqual(b'', data) def test_read_line_b...
climberwb/video-api
src/comments/serializers.py
Python
mit
2,962
0.01418
from django.contrib.auth import get_user_model from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework import routers, serializers, viewsets, permissions from rest_framework_jwt.authe
ntication import JSONWebTokenAuthentication from rest_framework.reverse import reverse from .models import Comment # from accounts.models import MyUser User = get_user_model() class CommentVideoUrlHyperlinkedIdentityField(serializers.HyperlinkedIdentityField): def get_url(self, obj,view_name,request,format): ...
d_slug":obj.video.slug } # print(reverse(view_name,kwargs=kwargs)) return reverse(view_name,kwargs=kwargs,request=request,format=format) class CommentUpdateSerializer(serializers.ModelSerializer): user = serializers.CharField(source='user.username',read_only=True) class Meta: ...
credativ/pulp
server/test/unit/server/managers/repo/test_sync.py
Python
gpl-2.0
28,058
0.002281
import datetime import signal import mock from .... import base from pulp.common import dateutils, constants from pulp.common.tags import resource_tag, RESOURCE_REPOSITORY_TYPE, action_tag from pulp.devel import mock_plugins from pulp.plugins.model import SyncReport from pulp.server.async import tasks from pulp.serve...
ockRepoPublishManager.raise_error: raise repo_publish_manager.PulpExecutionException(repo_i
d) @classmethod def reset(cls): MockRepoPublishManager.repo_id = None MockRepoPublishManager.raise_error = False class RepoSyncManagerTests(base.PulpServerTests): def setUp(self): super(RepoSyncManagerTests, self).setUp() mock_plugins.install() # Create the manag...
ubc/compair
compair/models/lti_models/lti_user.py
Python
gpl-3.0
9,485
0.004323
# sqlalchemy import re from sqlalchemy import func, select, and_, or_ from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy_enum34 import EnumType from flask import current_app from . import * from compair.core import db, display_name_generator...
# overwrite email if student not allowed to change it if not current_app.config.get('ALLOW_STUDENT_CHANGE_EMAIL'): self.compair_user.email = self.lis_person_contact_email_primary # overwrite student number if student not allowed to change it and lti_consumer has a student_nu...
student_number_param: self.compair_user.student_number = self.student_number def upgrade_system_role(self): # upgrade system role is needed if self.compair_user: if self.compair_user.system_role == SystemRole.student and self.system_role in [SystemRole.instructor, System...
m00nlight/hackerrank
algorithm/contests/Ad-Infinitum-10/A.py
Python
gpl-2.0
357
0.014006
from __future__ import division from
math import sqrt def solve(s1, s2, q, L): side = L * sqrt(2) - sqrt(2.0 * q) return side / abs(s2 - s1) if __name__ == '__main__': L, s1, s2 = map(int, raw_input().strip().split())
Q = int(raw_input()) for _ in range(Q): q = int(raw_input()) print '%.4lf' % solve(s1, s2, q, L)
vileopratama/vitech
src/addons/auth_crypt/auth_crypt.py
Python
mit
3,959
0.002273
import logging from passlib.context import CryptContext import openerp from openerp.osv import fields, osv from openerp.addons.base.res import res_users res_users.USER_PRIVATE_FIELDS.append('password_crypt') _logger = logging.getLogger(__name__) default_crypt_context = CryptContext( # kdf which can be verified...
sword_crypt=%s WHERE id=%s", (encrypted, id)) def _crypt_context(self, cr, uid, id, context=None): """ Passlib CryptConte
xt instance used to encrypt and verify passwords. Can be overridden if technical, legal or political matters require different kdfs than the provided default. Requires a CryptContext as deprecation and upgrade notices are used internally """ return default_crypt_context
piller-imre/exprail-python
exprail/token.py
Python
mit
319
0
""" Token class definition """ class Token(object): """
Represents a token with type and value""" def __init__(self, type, value): s
elf._type = type self._value = value @property def type(self): return self._type @property def value(self): return self._value
UASLab/ImageAnalysis
scripts/explore/annotations.py
Python
mit
11,987
0.004004
import csv import json import numpy as np import os import pathlib import navpy from direct.showbase.ShowBase import ShowBase from panda3d.core import CardMaker, LPoint3, NodePath, Texture, TransparencyAttrib from direct.gui.DirectGui import * from tkinter import * class Annotations(): def __init__(self, render...
[0]) w.pack(side=LEFT) f = Frame(new)
f.pack(side=TOP, f
chen0031/rekall
rekall-core/rekall/plugins/overlays/windows/windows.py
Python
gpl-2.0
5,249
0.000953
# Rekall Memory Forensics # Copyright (C) 2012 Michael Cohen <scudette@users.sourceforge.net> # Copyright (c) 2008 Volatile Systems # Copyright (c) 2008 Brendan Dolan-Gavitt <bdolangavitt@wesleyan.edu> # Copyright 2013 Google Inc. All Rights Reserved. # # This program is free software; you can redistribute it and/or mo...
but for now we # just guess the version based on structures which are known to exist in #
the profile. version = 5.2 # Windows XP did not use a BalancedRoot for VADs. if profile.get_obj_offset("_MM_AVL_TABLE", "BalancedRoot") == None: version = 5.1 # Windows 7 introduces TypeIndex into the object header. if profile.get_obj_offset("_OBJECT_HEADER", "Type...
griffinfoster/pulsar-polarization-sims
scripts/plotLineValVsTint.py
Python
mit
5,743
0.028034
#!/usr/bin/env python """ """ import os,sys import numpy as np import matplotlib #matplotlib.use('Agg') import pylab as p import cPickle as pkl from scipy import interpolate matplotlib.rc('xtick',labelsize=25) matplotlib.rc('ytick',labelsize=25) modeTitle=['Total Intensity','Invariant Interval','Matrix Template Ma...
.append(key[1]) if np.isnan(val['rms']) or np.isnan(val['avgSigma']) or val['rms']<0.: print 'Warning: some selected values are NaN',key continue #skip any simulations which returned N
aN ixrdbs.append(ixrdb) deltaJs.append(deltaJ) polLeakdbs.append(polLeakdb) if opts.mode.startswith('rms'): simVals.append(val['rms']) elif opts.mode.startswith('chi'): simVals.append(val['chi2']) elif opts.mode.startswith('sigma'): simVals.append(...
jolyonb/edx-platform
common/lib/xmodule/xmodule/modulestore/tests/test_semantics.py
Python
agpl-3.0
19,838
0.003982
""" Tests of modulestore semantics: How do the interfaces methods of ModuleStore relate to each other? """ from __future__ import absolute_import import itertools from collections import namedtuple import ddt from mock import patch from xblock.core import XBlock, XBlockAside from xblock.fields import Scope, String f...
Arguments: parent_usage_key: The xblock to check as a parent. child_usage_key: The xblock to check as a child. draft (optional): If omitted, verify both published and draft branches. If True, verify only the draft branch. If
False, verify only the published branch. """ if draft is None or not draft: with self.store.branch_setting(ModuleStoreEnum.Branch.published_only): parent_block = self.store.get_item( parent_usage_key, ) self....
rogerhu/django
django/db/models/aggregates.py
Python
bsd-3-clause
2,701
0.00037
""" Classes to represent the definitions of aggregate functions. """ from django.db.models.constants import LOOKUP_SEP __all__ = [ 'Aggregate', 'Avg', 'Count', 'Max', 'Min', 'StdDev', 'Sum', 'Variance', ] def refs_aggregate(lookup_parts, aggregates): """ A little helper method to check if the lookup_part...
ble and column name. * source is the underlying field or aggregate definition for the column reference. If the aggregate is not an ordinal or computed
type, this reference is used to determine the coerced output type of the aggregate. * is_summary is a boolean that is set True if the aggregate is a summary value rather than an annotation. """ klass = getattr(query.aggregates_module, self.name) aggregate = klass(...
iakovleva/allauth-login-page
account/urls.py
Python
mit
760
0
import importlib from django.conf.urls import url, include import allauth.socialaccount.providers as allauth_providers from . import views as accounts_views def get_provider_urls(provider): try: urls = importlib.import_module(provider.package + '.urls') except ImportError: return [] els...
urls, 'urlpatterns', []) urlpatterns = [ url(r'^login/$', accounts_views.login, name='accounts_login'), url(r'^logout/$', accounts_views.logout, na
me='accounts_logout'), url(r'^settings/$', accounts_views.settings, name='accounts_settings'), url(r'', include('allauth.socialaccount.urls')), ] for provider in allauth_providers.registry.get_list(): urlpatterns += get_provider_urls(provider)
usc-isi-i2/WEDC
spark_dependencies/python_lib/nose2/plugins/failfast.py
Python
apache-2.0
615
0
""" Stop the test run after the first error or failure. This plugin implements :func:`testOutcome` and sets ``event.result.shouldStop`` if it sees an outcome with exc_info that is not expected. """ from nose2 import events __unittest = True class FailFast(events.Plugin): """Stop the test run after error or ...
the test run after the first error or failure') def testOutcome(self, event
): """Stop on unexpected error or failure""" if event.exc_info and not event.expected: event.result.shouldStop = True
LuoZijun/solidity-sc2-replay-reader
bzip2.py
Python
gpl-3.0
17,390
0.009383
#!/usr/bin/env python # coding: utf-8 from __future__ import division import sys, os, time, platform, math from struct import unpack, pack """ 生成测试数据: rm test.txt test.txt.bz2 echo 'hello, world(世界)!!!!' > test.txt bzip2 -z test.txt 解压数据: python bzip2.py 参考资料: https://en.wikipedia.org/wiki/...
bles_by_bits(self): d = {} for x in self.table: try: d[x.bits].append(x) except: d[x.bits] = [x] pass def min_max_bits(self): self.min_bits, self.max_bits = 16, -1 fo
r x in self.table: if x.bits < self.min_bits: self.min_bits = x.bits if x.bits > self.max_bits: self.max_bits = x.bits def _find_symbol(self, bits, symbol, table): for h in table: if h.bits == bits and h.reverse_symbol == symbol: #print "found, processing...
cg31/tensorflow
tensorflow/tensorboard/scripts/generate_testdata.py
Python
apache-2.0
7,184
0.012945
# Copyright 2015 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...
ime, s
tep=step, summary=summary) writer.add_event(event) step += 1 wall_time += 10 def WriteHistogramSeries(writer, tag, mu_sigma_tuples, n=20): """Write a sequence of normally distributed histograms to writer.""" step = 0 wall_time = _start_time for [mean, stddev] in mu_sigma_tuples: data = [random...
timthelion/FreeCAD
src/Mod/Path/PathScripts/PathFromShape.py
Python
lgpl-2.1
4,466
0.015674
# -*- coding: utf-8 -*- #*************************************************************************** #* * #* Copyright (c) 2015 Dan Falck <ddfalck@gmail.com> * #* ...
ommand("obj.Shape = FreeCAD.activeDocument()."+selection[0].Na
me+".Shape") FreeCADGui.doCommand('PathScripts.PathUtils.addToProject(obj)') FreeCAD.ActiveDocument.commitTransaction() FreeCAD.ActiveDocument.recompute() if FreeCAD.GuiUp: # register the FreeCAD command FreeCADGui.addCommand('Path_FromShape',CommandFromShape())
zang-cloud/zang-python
docs/examples/sip_domains_example.py
Python
mit
2,859
0
from zang.exceptions.zang_exception import ZangException from zang.configuration.configuration import Configuration from zang.connectors.connector_factory import ConnectorFactory from zang.domain.enums.http_method import HttpMethod from docs.examples.credetnials import sid, authToken url = 'https://api.zang.io/v2' c...
except ZangException as ze: print(ze) # list mapped credentials lists try: credentialsLists = sipDomainsConnector.listMappedCredentialsLists( 'TestDomainSid') print(credentialsLists.t
otal) except ZangException as ze: print(ze) # map credentials list try: credentialsList = sipDomainsConnector.mapCredentialsLists( 'TestDomainSid', 'TestCredentialsListSid') print(credentialsList.credentialsCount) except ZangException as ze: print(ze) # delete mapped credentials list try: ...
drvinceknight/gt
test_main.py
Python
mit
1,347
0.005197
""" Tests for main.py """ import pathlib import main def test_get_id(): path = pathlib.Path("./nbs/chapters/00-Introduction-to-the-course.ipynb") assert main.get_id(path) == "00" def test_get_id_with_no_id(): path = pathlib.Path("./nbs/other/Assessment.ipynb") assert main.get_id(path) == "assessment"...
ent" def test_convert_html(): path = pathlib.Path("./nbs/other/Assessment.ipynb") html_output = main.convert_html(path) assert len(html_output) == 2 assert type(html_output) is tuple assert type(html_output[0]) is str def test_render_template(): path = pathlib.Path("./nbs/other/Assessment.ipy...
ROOT) html = main.render_template("content.html", {"nb": nb, "root": main.ROOT, "id": path_id,}) assert type(html) is str assert main.ROOT in html assert path_id in html assert nb in html
njpatel/avant-window-navigator
plugins/Rhythmbox/artdisplay-awn/AmazonCoverArtSearch.py
Python
gpl-2.0
7,998
0.038139
# -*- Mode: python; coding: utf-8; tab-width: 8; indent-tabs-mode: t; -*- # # Copyright (C) 2006 - Gareth Murphy, Martin Szulecki # # 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 versio...
best_match is None: # Check if artist appears in the Artists list hit = False for item in search_results: if type (item.Artists.Artist) <> type ([]): artists = [item.Artists.Artist] else: artists = item.Artists.Artist for artist in artists: artist = self.__tidy_up...
-1: best_match = item hit = True break if hit: break return best_match except TypeError: return None
SlicerRt/SlicerDebuggingTools
PyDevRemoteDebug/ptvsd-4.1.3/ptvsd/_vendored/pydevd/pydev_ipython/inputhooktk.py
Python
bsd-3-clause
771
0.007782
# encoding: utf-8 # Unlike what IPython does, we need to have an explicit inputhook because tkinter handles # input hook in the C Source code #----------------------------------------------------------------------------- # Imports #------------------------------------
----------------------------------------- from pydev_ipython.inputhook import stdin_ready #----------------------------------------------------------------------------- # Code #----------------------------------------------------------------------------- TCL_DONT_WAIT = 1 << 1 def create_inputhook_tk(app)...
turn inputhook_tk
CERNDocumentServer/cds-videos
cds/version.py
Python
gpl-2.0
1,027
0
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2014, 2015, 2018 CERN. # # Invenio 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 optio...
n, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immu
nities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. """CDS version.""" __version__ = "1.0.29"
tovmeod/anaf
anaf/infrastructure/tests.py
Python
bsd-3-clause
22,223
0.00171
from django.test import TestCase from django.core.urlresolvers import reverse from django.contrib.auth.models import User as DjangoUser from anaf.core.models import Group, Perspective, ModuleSetting from models import Item, ItemValue, ItemField, ItemType, ItemStatus, ItemServicing class InfrastructureModelsTest(TestC...
re/" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') response = self.client.get(reverse('infrastructure')) self.assertEquals(response.status
_code, 200) def test_index_infrastructure_login(self): "Test index page with login at /infrastructure/index/" response = self.client.post('/accounts/login', {'username': self.username, 'password': self.password}) self.assertRedirects(response, '/') ...
yeyanchao/calibre
src/calibre/gui2/preferences/saving.py
Python
gpl-3.0
1,820
0.006593
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' from calibre.gui2.preferences import ConfigWidgetBase, test_widget, \ AbortCommit from calibre.gui2.preferences.s...
_signal.emit) def initialize(self): ConfigWidgetBase.initialize(self) self.save_template.blockSignals(True) self.save_template.initialize('save_to_disk', self.proxy['template'], self.proxy.help('template')) self.save_template.blockSignals(False) def restore_def...
e.set_value(self.proxy.defaults['template']) def commit(self): if not self.save_template.validate(): raise AbortCommit('abort') self.save_template.save_settings(self.proxy, 'template') return ConfigWidgetBase.commit(self) def refresh_gui(self, gui): gui.iactions['Sa...
google/nitroml
nitroml/automl/metalearning/metalearner/component_test.py
Python
apache-2.0
2,460
0.002439
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
_tra
in_data) self.assertEqual(artifacts.KCandidateHyperParameters.TYPE_NAME, metalearner.outputs['output_hyperparameters'].type_name) self.assertEqual(standard_artifacts.Model.TYPE_NAME, metalearner.outputs['metamodel'].type_name) if __name__ == '__main__': absltest.mai...
Gebesa-Dev/Addons-gebesa
account_invoice_replace/models/account_invoice_replace.py
Python
agpl-3.0
12,245
0.000572
# -*- coding: utf-8 -*- # Copyright 2018, Esther Cisneros # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from datetime import timedelta from openerp import _, api, fields, models from openerp.exceptions import UserError class AccountInvoice(models.Model): _name = 'account.invoice' _inh...
l']), ('company_id', '=', 1), ('type', '=', 'out_invoice'), ('date_cancelled', '=', date_cancel)]) table = '' remp_date = '' remp_rep = '' for inve in inv_ids: if not inve.date_cancelled: remp_date = '---' else: ...
laced: remp_rep = '---' else: remp_rep = inve.invoice_replaced.number table += """ <tr><td style="border-bottom: 1px solid silver;">%s</td> <td style="border-bottom: 1px solid silver;">%s</td> <td style="bord...
angr/cle
cle/backends/elf/relocation/__init__.py
Python
bsd-2-clause
1,417
0.002823
import os import logging import importlib import archinfo from collections import defaultdict from ...relocation import Relocation ALL_RELOCATIONS = defaultdict(dict) complaint_log = set() path = os.path.dirname(os.path.abspath(__file__)) l = logging.getLogger(name=__name__) def load_relocations(): for filename ...
ch except AttributeError: continue for item_name in dir(module): if item_name not in archinfo.defines: continue item = getattr(module, item_name) if not isinstance(item, type) or not issubclass(item, Relocation): continue ...
if r_type == 0: return None try: return ALL_RELOCATIONS[arch][r_type] except KeyError: if (arch, r_type) not in complaint_log: complaint_log.add((arch, r_type)) l.warning("Unknown reloc %d on %s", r_type, arch) return None load_relocations()
espressif/esp-idf
tools/test_apps/build_system/ldgen_test/check_placements.py
Python
apache-2.0
2,847
0.00281
#!/usr/bin/env python # # Copyright 2020 Espressif Systems (Shanghai) PTE LTD # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless req...
ail: func1 comes before __sym1_start' assert func1 < sym1_end, 'check placement fail: func1 comes after __sym1_end' assert sym1_start % 9 == 0, '_sym1_start is not aligned as specified in linker fragment' assert sym1_end % 12 == 0, '_sym1_end is not aligned as specified in linker fragment' print('check placement pass: ...
cation('func2', '.rtc.text') # src1 (default) - only func3 in src1 remains that has not been # mapped using a different scheme check_location('func3', '.flash.text') check_location('func4', '.iram0.text')
vivsh/django-ginger
ginger/conf/urls.py
Python
mit
580
0.001724
from django.conf.urls import include, url from ginger.views import utils __all__ = ('include', 'url', 'scan', 'scan_to_include') def scan(module, predicate=None): view_classes = utils.find_views(module, predicate=predicate) urls = [] for view in view_classes: if hasattr(view, 'as_urls'): ...
urls.append(view.as_url()) pattern = urls return pattern def scan_to
_include(module, predicate=None, app_name=None, namespace=None): return scan(module, predicate), app_name, namespace
seeminglee/pyglet64
tests/test.py
Python
bsd-3-clause
18,095
0.002487
#!/usr/bin/env python '''Test framework for pyglet. Reads details of components and capabilities from a requirements document, runs the appropriate unit tests. Overview -------- First, some definitions: Test case: A single test, implemented by a Python module in the tests/ directory. Tests can be interacti...
'$Id: $' import array import logging import os import optparse import re import sys import time import unittest # So we can find test
s.regression and ensure local pyglet copy is tested. sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) import tests.regression import pyglet.image regressions_path = os.path.join(os.path.dirname(__file__), 'regression', 'images') class TestCase(object): def __init...
bunbun/ruffus
ruffus/cmdline.py
Python
mit
31,898
0.002759
################################################################################ # # # cmd_line_helper.py # # Copyright (c) 10/9/2009 Leo Goodstadt # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # ...
metavar="JOBNAME", type=str,
help="Target task(s) of pipeline.", default=[]) if "jobs" not in ignored_args: pipeline_options.add_argument("-j", "--jobs", default=1, metavar="N", type=int, help="Allow N jobs (commands) to run simultaneously.") if "use_threads" n...
bcoe/Adventures-in-Document-Thumbnailing
setup.py
Python
mit
533
0.015009
#!/usr/bin/env python #from distutils.core import setup from setuptools import setup, find_packages setup( name="tomthumb"
, version="0.0.1", description="A handy document thumbnailing
tool.", author="Benjamin Coe", author_email="bencoe@gmail.com", url="https://github.com/bcoe/Adventures-in-Document-Thumbnailing", packages = find_packages(), install_requires = [ 'PIL' ], entry_points = { 'console_scripts': [ 'tomthumb = tomthumb.__main__:main' ...
cepheidxa/python
prime.py
Python
gpl-3.0
3,162
0.007278
#!/usr/bin/python3 from ctypes import * import random import logging import log logger = logging.getLogger('test.prime') __all__ = ['isPrime', 'getRandPrime', 'inv'] libgmp = CDLL('libgmp.so.10') class _mpz_t(Structure): _fields_ = [('_mp_alloc', c_int), ('_mp_size', c_int), ('_mp_d', POINTER(c_ulong))] def _...
hile b != 1: pp, vv = vv, b a, b = divmod(pp, vv) l1 = l2 l2 = l3 l3 = list(map(lambda x: x[0] - a * x[1], zip(l1, l2))) ret = l3[1] ret = ret % p if ret < 0: ret = ret + p return ret def expmod(x, n, p): b = n t = x % p ret = 1 while b !=...
et *= t ret %= p t = t * t % p b >>= 1 return ret def isQR(a, p): """is a a quadratic residule mod p, p must be a prime if p is prime, and (a, p) = 1, then a is a a quadratic residule of p is eaual to a ** ((p-1)/2) = 1 mod p a is not a a quadratic res...
vicky2135/lucious
oscar/bin/pilprint.py
Python
bsd-3-clause
2,624
0.001524
#!/usr/local/django-oscar/oscar/bin/python2.7 # # The Python Imaging Library. # $Id$ # # print image files to postscript printer # # History: # 0.1 1996-04-20 fl Created # 0.2 1996-10-04 fl Use draft mode when converting. # 0.3 2003-05-06 fl Fixed a typo or two. # from __future__ import print_function impo...
es") print("Usage: pilprint files...") print("Options:") print(" -c colour printer (default is monochrome)") print(" -d debug (show avai
lable drivers)") print(" -p print via lpr (default is stdout)") print(" -P <printer> same as -p but use given printer") sys.exit(1) try: opt, argv = getopt.getopt(sys.argv[1:], "cdpP:") except getopt.error as v: print(v) sys.exit(1) printerArgs = [] # print to stdout monochrome ...
anhstudios/swganh
data/scripts/templates/object/building/poi/shared_tatooine_evil_nomad_small2.py
Python
mit
457
0.045952
#### NOTICE: THIS F
ILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTA
TION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Building() result.template = "object/building/poi/shared_tatooine_evil_nomad_small2.iff" result.attribute_template_id = -1 result.stfName("poi_n","base_poi_building") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### re...
simply-jos/birth-of-the-toolkit
REScripts/TSCBViewer/viewer.py
Python
mit
2,829
0.000353
import pygame import math import os import sys import struct from Util import BinaryReader, Camera from BoTWHeightmap import Heightmap, Config bgcolor = (0, 0, 0) size = [1024, 768] camera = Camera(size) camera.SetLodLevel(32.0) # Initialize pygame pygame.init() screen = pygame.display.set_mode(size) # Run a loo...
ent.get(): if ev.type == pygame.KEYDOWN: if ev.key == pygame.K_t: Config.draw_textures = not Config.draw_textures elif ev.key == pygame.K_p: Config.draw_coverage = not Config.draw_coverage elif ev.key
== pygame.K_g: Config.draw_grid = not Config.draw_grid elif ev.key == pygame.K_o: Config.draw_overdraw = not Config.draw_overdraw elif ev.key == pygame.K_b: bgcolor = (0, (0, 255)[bgcolor[1] == 0], 0) elif ev.key == pygame.K_m: ...
ProgVal/Limnoria-test
plugins/Alias/test.py
Python
bsd-3-clause
7,992
0.001878
# -*- coding: utf8 -*- ### # Copyright (c) 2002-2004, Jeremiah Fincher # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice...
self.assertError('spam|egg') def testWriteDatabase(self): self.assertNotError('alias add fooo.spam echo egg') self.assertResponse('fooo.spam', 'egg') self.failUnless(hasattr(conf.supybot.plugins.Alias.escapedaliases, 'a1a4dfooospam'))
self.assertEqual(conf.supybot.plugins.Alias.escapedaliases.a1a4dfooospam(), 'echo egg') self.assertNotError('alias add foo.spam.egg echo supybot') self.assertResponse('foo.spam.egg', 'supybot') self.failUnless(hasattr(conf.supybot.plugins.Alias.escapedaliases, 'a2a3...
GarySparrow/mFlaskWeb
app/main/views.py
Python
mit
9,886
0
from flask import render_template, redirect, url_for, abort, flash, request,\ current_app, make_response from flask_login import login_required, current_user from flask_sqlalchemy import get_debug_queries from . import main from .forms import EditProfileForm, EditProfileAdminForm, PostForm,\ CommentForm from .....
user.email = form.email.data user.username = form.username.data user.confirmed = form.confirmed.data user.role = Role.query.get(form.role.data) user.
name = form.name.data user.location = form.location.data user.about_me = form.about_me.data db.session.add(user) flash('The profile has been updated.') return redirect(url_for('.user', username=user.username)) form.email.data = user.email form.username.data = user.usernam...
YuepengGuo/backtrader
backtrader/indicators/__init__.py
Python
gpl-3.0
2,021
0
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as pub...
ww.gnu.o
rg/licenses/>. # ############################################################################### from __future__ import (absolute_import, division, print_function, unicode_literals) from backtrader import Indicator from backtrader.functions import * # The modules below should/must define __all...
arthurdarcet/aiohttp
tests/test_multipart.py
Python
apache-2.0
40,036
0
import asyncio import io import json import zlib from unittest import mock import pytest import aiohttp from aiohttp import payload from aiohttp.hdrs import ( CONTENT_DISPOSITION, CONTENT_ENCODING, CONTENT_TRANSFER_ENCODING, CONTENT_TYPE, ) from aiohttp.helpers import parse_mimetype from aiohttp.multi...
ert obj.at_eof() result = await obj.next() assert result is None async def test_read(self) -> None:
obj = aiohttp.BodyPartReader( BOUNDARY, {}, Stream(b'Hello, world!\r\n--:')) result = await obj.read() assert b'Hello, world!' == result assert obj.at_eof() async def test_read_chunk_at_eof(self) -> None: obj = aiohttp.BodyPartReader( BOUNDARY, {}, Strea...
flexiant/xen
tools/python/xen/util/xsm/acm/acm.py
Python
gpl-2.0
56,344
0.00378
#=========================================================================== # This library is free software; you can redistribute it and/or # modify it under the terms of version 2.1 of the GNU Lesser General Public # License as published by the Free Software Foundation. # # This library is distributed in the hope tha...
"/boot/grub/menu.lst" altboot_filename = "/boot/grub/grub.conf" xensec_tool = "/usr/sbin/xensec_tool" #global patterns for map file #police_reference_tagname = "POLICYREFERENCENAME" primary_entry_re = re.compile("\s*PRIMARY\s+.*", re.IGNORECASE) secondary_entry_re = re.compile("\s*SECONDARY\s+.*", re.IGNORECASE) labe...
(".*\.map", re.IGNORECASE) policy_reference_entry_re = re.compile("\s*POLICYREFERENCENAME\s+.*", re.IGNORECASE) vm_label_re = re.compile("\s*LABEL->SSID\s.+[VM|ANY]\s+.*", re.IGNORECASE) res_label_re = re.compile("\s*LABEL->SSID\s+RES\s+.*", re.IGNORECASE) all_label_re = re.compile("\s*LABEL->SSID\s+.*", re.IGNORECASE)...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractInacloudspaceWordpressCom.py
Python
bsd-3-clause
658
0.028875
def extractInacloudspaceWordpressCom(item): ''' Parser for 'inacloudspace.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['titl
e'].lower(): return None tagmap = [ ('Drunken Exquisiteness', 'Drunken Exquisiteness', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, t
l_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
DMPwerkzeug/DMPwerkzeug
rdmo/core/tests/test_mail.py
Python
apache-2.0
2,649
0.000755
from django.conf import settings from django.core import mail from rdmo.core.mail import send_mail def test_send_mail(db): send_mail('Subject', 'Message', to=['user@example.com']) assert len(mail.outbox) == 1 assert mail.outbox[0].subject == '[example.com] Subject' assert mail.outbox[0].body == 'Mes...
ail.outbox[0].body == 'Message' assert mail.outbox[0].from_email == 'user@example.com' assert mail.outbox[0].to == ['user2@example.com'] assert mail.outbox[0].cc == [] assert mail.outbox[0].bcc == [] assert mail.outbox[0].attachments == [] def test_send_mail_from_attachments(db): send_mail('Su...
plain/text') ]) assert len(mail.outbox) == 1 assert mail.outbox[0].subject == '[example.com] Subject' assert mail.outbox[0].body == 'Message' assert mail.outbox[0].from_email == settings.DEFAULT_FROM_EMAIL assert mail.outbox[0].to == ['user2@example.com'] assert mail.outbox[0].cc == [] ...
51reboot/actual_09_homework
04/guantao/list.py
Python
mit
382
0.035503
#coding:utf-8 LIST_NUM = [(1,4),(5,1),(2,3),(6,9),(7,1)] ''' 用max函数获取到元素的最大值,然后用冒泡进行排序 ''' for j in range(len(
LIST_NUM) -1): for i in range(len(LIST_NUM) -1): if max(LIST_NUM[i]) > max(LIST_NUM[i + 1]): A = LIST_NUM[i] LIST_NUM[i] = LIST_NUM[i + 1] LIST_N
UM[i + 1] = A print LIST_NUM
karolmajta/officetune
server/src/officetune/officetune/admin.py
Python
mit
175
0.005714
''' Created on 13-09-2013 @author: kamil ''' from django.contrib import
admin from officetune.models import Song, Vote admin.site.register(Vote) admin.
site.register(Song)
windskyer/k_cinder
paxes_cinder/scohack/scosample/imgupload_ostest.py
Python
apache-2.0
11,651
0.000343
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # ================================================================= # ================================================================= import httplib import json import logging import sys import requests import os import hashlib def enum(*sequential, **named): enums...
f13594702add11573ad72ed9baa42facad5ba5fe9a7194465a246a31e000' ####
# Images # copy_from = 'http://9.47.161.56:8080/cirros-0.3.0-x86_64-disk.img' # checksum = None # copy_from = 'http://9.47.161.56:8080/IBM_SCE_3.2_PPC64_App-disk3.raw' # checksum = None # copy_from = ('http://pokgsa.ibm.com/home/g/j/gjromano/web/public/' # 'ZippedImagesAndOVFs24...
jeffreywolf/pyday-2015
factorial.py
Python
mit
447
0.071588
#! /usr/bin/env python import argparse
def getArgs(): parser = argparse.ArgumentParser( description = """Factorial calculator """ ) parser.add_argument( "-n", type = int, required = True, help = "Enter n to set N!" ) return parser.parse_args() def factorial(n): if n == 0: return 1 else: r
eturn n*factorial(n-1) def main(): args = getArgs() result = factorial(args.n) print result if __name__ == "__main__": main()
alejandro-mc/trees
randNNIWalks.py
Python
mit
4,063
0.022151
#randNNIWalks.py #
writes random SPR walks to files #calls GTP on each NNI random walk file to get #the ditances between each tree and the first tree of the sequence #the results are written to csv files with lines delimited by \t import tree_utils as tu import w_tree_utils as wtu import os import sys import numpy as np import random fro...
ps,runs,seed,weighted = False): global __pid__ global __prefix__ #set the seed random.seed(seed) np.random.seed(seed) #select tree utils module if weighted: tum = wtu genRandBinTree = lambda leaves: wtu.genRandBinTree(leaves,np.random.exponential) else: ...
bchiroma/DreamProject_2
dream/KnowledgeExtraction/KEtool_examples/TwoServers/TwoServers_example.py
Python
gpl-3.0
10,371
0.01832
''' Created on 19 Feb 2014 @author: Panos ''' # =========================================================================== # Copyright 2013 University of Limerick # # This file is part of DREAM. # # DREAM is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public Lic...
arameterB') Name=process.find('./OperationTime/Distribution/DistributionParameterB/Name') Name.text=str(M2Parameters[1]) Value=process.find('./OperationTime
/Distribution/DistributionParameterB/Value') Value.text=str(M2ParameterValue[1]) else: continue tree.write('CMSD_TwoServers_Output.xml',encoding="utf8"
poojavade/Genomics_Docker
Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/khmer-1.1-py2.7-linux-x86_64.egg/EGG-INFO/scripts/count-overlap.py
Python
apache-2.0
2,765
0.000362
#!/usr/bin/python2.7 # # This file is part of khmer, http://github.com/ged-lab/khmer/, and is # Copyright (C) Michigan State University, 2012-2014. It is licensed under # the three-clause BSD license; see doc/LICENSE.txt. # Contact: khmer-project@idyll.org # # pylint: disable=missing-docstring,invalid-name """ Count th...
its(args.ptfile) kmer_size = ht1.ksize() output = open(args.report_filename, 'w') f_curve_obj = open(args.report_filename + '.curve', 'w') ht2 = khmer.new_hashbits(kmer_size, args.min_tablesize, args.n_tables) (n_unique, n_overlap, list_curve) = ht2.count_overlap(args.fafile, ht
1) printout1 = """\ dataset1(pt file): %s dataset2: %s # of unique k-mers in dataset2: %d # of overlap unique k-mers: %d """ % (args.ptfile, args.fafile, n_unique, n_overlap) output.write(printout1) for i in range(100): to_print = str(list_curve[100 + i]) + ' ' + str(list_curve[i]) + '\n' ...
SanketDG/dpaste
dpaste/south_migrations/0006_auto__add_unique_snippet_secret_id.py
Python
mit
2,051
0.006826
# -*- coding: utf-8 -*- import datetime from django.db import models from south.db import db from south.v2 import SchemaMigration class Migration(SchemaMigration): def forwards(self, orm): # Adding unique constraint on 'Snippet', fields ['secret_id'] db.create_unique('dpaste_snippet', ['secret_i...
ntegerField', [], {'default': '1'}), 'expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), u'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'Tr...
'", 'max_length': '30'}), u'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': u"orm['dpaste.Snippet']"}), 'published': ('...
Rondineli/pybr11_tutorial
pybr11_tutorial/pybr11_tutorial/settings.py
Python
apache-2.0
2,688
0
""" Django settings for pybr11_tutorial project. Generated by 'django-admin startproject' using Django 1.8.6. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Bu...
SECRET_KEY = '4b5prz%55i#ay!qf=7w=61p^am-4a_jknjf8&jzu1d6ib@-*d^' # SECURITY WARNING: don't r
un with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pybr11_tut...
joakim-hove/ert
test-data/local/mini_ert/jobs/perlin_fail.py
Python
gpl-3.0
461
0
#!/usr/bin/env python import os import
sys iens = None if len(sys.argv) > 1: iens = int(sys.argv[1]) numbers = [1, 2, 3, 4, 5, 6] if iens in numbers: random_report_step = (numbers.index(iens) % 3) + 1 os.remove("perlin_%d.txt" % random_report_step) with open("perlin_fail.status", "w") as f: f.write("Deleted report step: %d" % rand...
!")
HopeFOAM/HopeFOAM
ThirdParty-0.1/ParaView-5.0.1/VTK/Rendering/Core/Testing/Python/pickCells.py
Python
gpl-3.0
16,540
0.026421
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # create a scene with one of each ...
) aTriangleActor.AddPosition(4,0,2) aTriangleActor.GetProperty().BackfaceCullingOn() # Polygon polygonPoints = vtk.vtkPoints() polygonPoints.SetNumberOfPoints(4) polygonPoints.InsertPoint(0,0,0,0) polygonPoints.InsertPoint(1,1,0,0) polygonPoints.InsertPoint(2,1,1,0) polygonPoints.InsertPoint(3,0,1,0) aPolygon = vtk.vtk...
berOfIds(4) aPolygon.GetPointIds().SetId(0,0) aPolygon.GetPointIds().SetId(1,1) aPolygon.GetPointIds().SetId(2,2) aPolygon.GetPointIds().SetId(3,3) aPolygonGrid = vtk.vtkUnstructuredGrid() aPolygonGrid.Allocate(1,1) aPolygonGrid.InsertNextCell(aPolygon.GetCellType(),aPolygon.GetPointIds()) aPolygonGrid.SetPoints(polygo...
CERNDocumentServer/cds
cds/modules/records/jsonresolver/schemas.py
Python
gpl-2.0
1,378
0
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2017 CERN. # # Invenio 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...
r import pkg_resources @jsonresolver.route('/schemas/<path:path>', host='cds.cern.ch') def resolve_schemas(path): """Resolve JSON sche
mas.""" with open(pkg_resources.resource_filename( 'cds_dojson.schemas', path), 'r') as f: return json.load(f)
bthirion/nipy
nipy/fixes/nibabel/orientations.py
Python
bsd-3-clause
3,877
0.001548
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the NiBabel package for the # copyright and license terms. # ### ### ### #...
n there are columns of all zero in the affine. See h
ttps://github.com/nipy/nibabel/pull/128 Remove when we depend on nibabel > 1.2.0 """ import numpy as np import numpy.linalg as npl def io_orientation(affine, tol=None): ''' Orientation of input axes in terms of output axes for `affine` Valid for an affine transformation from ``p`` dimensions to ``q`` d...
aplanas/py-tcdb
test/test-adb.py
Python
lgpl-3.0
15,634
0.000065
# -*- coding: utf-8 -*- import unittest import warnings from tcdb import adb class TestADBSimple(unittest.TestCase): def setUp(self): self.adb = adb.ADBSimple() self.adb.open('*') def tearDown(self): self.adb.close() self.adb = None def test_setgetitem(self): se...
adb.vsiz('key'), len('some text')) def test_iters(self): keys = ['key1', 'key2', 'key3', 'key4', 'key5'] for key in keys: self.adb.put(key, key) self.assertEqual(
len(self.adb.keys()), len(keys)) self.assertEqual(len(self.adb.values()), len(keys)) self.assertEqual(len(zip(keys, keys)), len(self.adb.items())) for key in self.adb: self.assert_(key in keys) for value in self.adb.itervalues(): self.assert_(value in keys) ...
jnewland/home-assistant
homeassistant/components/wirelesstag/binary_sensor.py
Python
apache-2.0
4,265
0
"""Binary sensor support for Wireless Sensor Tags.""" import logging import voluptuous as vol from homeassistant.components.binary_sensor import ( PLATFORM_SCHEMA, BinarySensorDevice) from homeassistant.const import CONF_MONITORED_CONDITIONS, STATE_OFF, STATE_ON from homeassistant.core import callback import home...
(WirelessTagBinarySensor(platform, tag, sensor_type)) add_entities(sensors, True) hass.add_job(platform.install_push_notifications, sensors) class WirelessTagBinarySensor(WirelessTagBaseSensor, BinarySensorDevice): """A binary sensor implementation f...
pe): """Initialize a binary sensor for a Wireless Sensor Tags.""" super().__init__(api, tag) self._sensor_type = sensor_type self._name = '{0} {1}'.format(self._tag.name, self.event.human_readable_name) async def async_added_to_hass(self): ...
alexsalo/genenetwork2
wqflask/basicStatistics/BasicStatisticsFunctions.py
Python
agpl-3.0
8,270
0.011487
from __future__ import print_function #import string from math import * #import piddle as pid #import os import traceback from pprint import pformat as pf from corestats import Stats import reaper from htmlgen import HTMLgen2 as HT #from utility import Plot from utility import webqtlUtil from base import webqtlCon...
omOffset = 60 canvasHeight = plotHeight + yTopOffset + yBottomOffset canvasWidth = plotWidth + xLeftOffset + xRightOffset canvas = pid.PILCanvas(size=(canvasWidth,canvasHeight)) XXX = [('', valsOnly[:])] Plot.plotBoxPlot(canvas, XXX, offset=(xLeftOffset, xRightOffset, yTopOffset, yBottomOffset
), XLabel= "Trait") filename= webqtlUtil.genRandStr("Box_") canvas.save(webqtlConfig.IMGDIR+filename, format='gif') img=HT.Image('/image/'+filename+'.gif',border=0) plotLink = HT.Span("More about ", HT.Href(text="Box Plots", url="http://davidmlane.com/hyperstat/A37797.html", target="_blank", Class="fs1...
teknolab/django.org.tr
project/local_settings-example.py
Python
bsd-3-clause
1,149
0
from django.conf.global_settings import MIDDLEWARE_CLASSES from settings_default import INSTALLED_APPS DEBUG = True TEMPLATE_DEBUG = DEBUG SECRET_KEY = 'please-generate-your-secret-key' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'sqlite.db', } } # FACEBOOK_APP...
MER_KEY = '' # TUMBLR_CONSUMER_SECRET = '' # TWITTER_CONSUMER_KEY = '' # TWITTER_CONSUMER_SECRET = '' MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',) INSTALLED_APP
S += ('django_extensions', 'debug_toolbar') INTERNAL_IPS = ('127.0.0.1',) DEBUG_TOOLBAR_PANELS = ( 'debug_toolbar.panels.version.VersionDebugPanel', 'debug_toolbar.panels.timer.TimerDebugPanel', 'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel', 'debug_toolbar.panels.headers.HeaderDebugPanel',...
KhronosGroup/COLLADA-CTS
StandardDataSets/collada/library_effects/effect/profile_COMMON/technique/phong/ambient/effect_phong_ambient_texture/effect_phong_ambient_texture.py
Python
mit
4,183
0.007172
# Copyright (c) 2012 The Khronos Group Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publ...
self.status_superior = self.__assistant.DeferJudgement(context) return self.status_superior # To pass advanced you need to pass intermediate, this object could also include additional # tests that were specific to the advanced badge def JudgeExemplary(self, context): ...
# This is where all the work occurs: "judgingObject" is an absolutely necessary token. # The dynamic loader looks very specifically for a class instance named "judgingObject". # judgingObject = SimpleJudgingObject(tagLst, attrName, attrVal, dataToCheck);
calee88/ParlAI
parlai/agents/rnn_baselines/seq2seq.py
Python
bsd-3-clause
10,385
0.001444
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. from parlai.core.agents im...
output_lines
[0]), '(true: {})'.format(true)) return output_lines def predict(self, xs): batchsize = len(xs) # first encode context xes = self.lt(xs).t() h0 = self.init_zeros(batchsize) _output, hn = self.encoder(xes, h0) # start with EOS tensor for all x = self...
ktnyt/chainer
examples/glance/glance.py
Python
mit
2,943
0
# Note for contributors: # This example code is referred to from "Chainer at a Glance" tutorial. # If this file is to be modified, please also update the line numbers in # `docs/source/glance.rst` accordingly. import chainer as ch from chainer import datasets import chainer.functions as F import chainer.links as L fro...
in, test = datasets.split_dataset_random( datasets.TupleDataset(X, Y), int(data_array.shape[0] * .7)) train_iter = ch.iterators.SerialIterator(train, 100) test
_iter = ch.iterators.SerialIterator( test, 100, repeat=False, shuffle=False) # Network definition def MLP(n_units, n_out): layer = ch.Sequential(L.Linear(n_units), F.relu) model = layer.repeat(2) model.append(L.Linear(n_out)) return model model = L.Classifier( MLP(44, 1), lossfun=F.sigmoid_...
Skufler/pybot
weather.py
Python
gpl-3.0
736
0
import pyowm import main owm = pyowm.OWM('9a55dd22782984d74bc1deecec64fc9a', language='Ru') def weather_handler(message): try: observation = owm.weather_at_place(message.text) weather = observation.g
et_weather() answer = weather.get_detailed_status() temperature = weather.get_temperature(unit='celsius') main.bot.send_message(message.chat.id
, 'Погода: {answer}, ' 'Температура: {temperature}' .format(answer=answer, temperature=temperature.get('temp'))) except Exception as e: main.bot.send_message(message.chat.id, e.args)
witten/borgmatic
borgmatic/config/generate.py
Python
gpl-3.0
10,638
0.004324
import collections import io import os import re from ruamel import yaml from borgmatic.config import load INDENT = 4 SEQUENCE_INDENT = 2 def _insert_newline_before_comment(config, field_name): ''' Using some ruamel.yaml black magic, insert a blank line in the config right before the given field and it...
tering an optional configuration option, comment out lines until the next blank # line. if line.strip().startswith('# {}'.format(COMMENTED_OUT_SENTINEL)): optional =
True continue # Hit a blank line, so reset commenting. if not line.strip(): optional = False lines.append(_comment_out_line(line) if optional else line) return '\n'.join(lines) def render_configuration(config): ''' Given a config data structure of nested...
hoburg/gpkit
gpkit/tools/tools.py
Python
mit
3,097
0
"""Non-application-specific convenience methods for GPkit""" import numpy as np def te_exp_minus1(posy, nterm): """Taylor expansion of e^{posy} - 1 Arguments --------- posy : gpkit.Posynomial Variable or expression to exponentiate nterm : int Number of non-constant terms in result...
t(x), carried to nterm terms """ if nterm > 15: raise NotImplementedError("Tangent expansion not implemented above" " 15 terms") # The first 15 Bernoulli Numbers B2n = np.asarray([1/6, -1/30, 1/42, ...
43867/798, -174611/330, 854513/138, -236364091/2730, 8553103/6, -23749461029/870, 8615841276005/14322]) res = 0 factorial_denom = 1 for i in range(1, nterm + 1): ...
rackerlabs/rackspace-python-neutronclient
neutronclient/tests/unit/test_cli20_floatingips.py
Python
apache-2.0
8,263
0
#!/usr/bin/env python # Copyright 2012 Red Hat # 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 # # Un...
def test_create_floatingip(self): # Create floatingip: fip1. resource = 'floatingip' cmd = fip.CreateFloatingIP(test_cli20.MyApp(sys.stdout), None) name = 'fip1' myid = 'myid' args = [name, '--description', 'floats like a butterfly'] position_names = ['floating...
ues = [name] self._test_create_resource(resource, cmd, name, myid, args, position_names, position_values, description='floats like a butterfly') def test_create_floatingip_and_port(self): # Create floatingip: fip1. resour...
jgirardet/unolog
unolog/unousers/models.py
Python
gpl-3.0
686
0
from django.contrib.auth.models import AbstractUser from django.db import models STATUT = ['docteur', 'secrétaire', 'interne', 'remplaçant']
class UnoUser(AbstractUser): """ Base User class for unolog define statu """ MEDECIN = "medecin" SECRETAIRE = "secretaire"
INTERNE = "interne" REMPLACANT = "remplacant" STATUT = ( (MEDECIN, 'Médecin'), (SECRETAIRE, 'Secrétaire'), (INTERNE, "Interne"), (REMPLACANT, "Remplaçant"), ) statut = models.CharField(max_length=20, choices=STATUT) """ RPPS ADELI https://github.com/codingforentrepre...
openaps/oacids
oacids/exported/triggers.py
Python
mit
3,924
0.019368
import dbus.service from gi.repository import GObject as gobject from oacids.helpers.dbus_props import GPropSync, Manager, WithProperties, ObjectManager from ifaces import BUS, IFACE, PATH, INTROSPECTABLE_IFACE, TRIGGER_IFACE, OPENAPS_IFACE EVENT_IFACE = 'org.openaps.Service.Instance.Triggers' class Emitter (GPropS...
self.path = path # self.when = armed.when # self.armed = armed GPropSync.__init__(self, self.bus.get_connection( ), path) # WithProperties.__init__(self, self.bus.get_connection( ), path) self.attrs = props @dbus.service.method(dbus_interface=OWN_IFACE, in_signature='', o
ut_signature='') def Fire (self): self.Emit('Fire') self.Do( ) @dbus.service.method(dbus_interface=OWN_IFACE, in_signature='a{sv}', out_signature='') def Update (self, props): print props @dbus.service.signal(dbus_interface=OWN_IFACE, signature='s') de...
Akagi201/learning-python
lpthw/ex32.py
Python
mit
887
0.001127
#!/usr/bin/env python # Exercise 32: Loops and Lists the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list for numb
er in the_count: print "This is count %d" % number # same as above for fruit in fruits: print "A fruit of type: %s" % fruit # also we can go through mixed lists too # notice we have to use %r since we don't know what's in it for i in change: print "I got %r" % i # we can also build lists, first start wit...
pelicanmapping/readymap-python
setup.py
Python
mit
723
0.002766
import os from setuptools import setup, find_packages version = __import__('readymap').__version__ with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), ...
gs for ReadyMap'), long_description=README,
packages=find_packages(), install_requires=['requests>=2.4.1','requests-toolbelt>=0.3.1'] )
adamrvfisher/TechnicalAnalysisLibrary
Weight.py
Python
apache-2.0
916
0.020742
# -*- coding: utf-8 -*- """ Created on Tue Feb 7 11:27:35 2017 @author: AmatVictoriaCuramIII """ #Get modules #import scipy as sp import numpy as np from pandas_datareader import data import pandas as pd #portfolio set up port = ['^GSPC', '^RUA'] numsec = len(port) equalweight = 1/numsec df2
= pd.DataFrame(columns=[]) x=0 y=0 #HERE'S AN IDEA print(list(enumerate(port, start=1))) #List the log returns in columns for s in port: x = x + 1 y = y - 1 s = data.DataReader(s, 'yahoo', start='1/1/1900',
end='01/01/2050') s[x] = np.log(s['Adj Close']/s['Adj Close'].shift(1)) #log returns s['equalweight'] = equalweight s[y] = s[x] * s['equalweight'] #This is the weighted return df2 = pd.concat([df2,s[x],s[y]], axis=1) #Multiply the individual columns by the last and sum #df2['portfolioreturn'] = df2[(r...
robhost/UPDIAN
updian/frontend/__init__.py
Python
gpl-2.0
224
0.004464
import flask from flaskext.csrf import csr
f from .basicauth import BasicAuth from .. import config app = flask.Flask(__name__) app.secret_key = config.secret_key csrf(app) basic_auth = Basi
cAuth(app) from . import views
thought-machine/please
test/python_rules/custom_runner/runner.py
Python
apache-2.0
685
0.00438
import os import pytest def run(test_names, args): """Custom test runner entry point. This is fairly minimal and serves mostly to demonstrate how to define this as an entry point.
Args: test_names: The names of the original test modules to be run (i.e. the things that were srcs to the python_test rule). args: Any command-line arguments, not incl
uding sys.argv[0]. """ results_file = os.getenv('RESULTS_FILE', 'test.results') os.mkdir(results_file) args += ['--junitxml', os.path.join(results_file, 'results.xml')] + test_names if os.environ.get('DEBUG'): args.append('--pdb') return pytest.main(args)
miraheze/puppet
modules/mediawiki/files/bin/mwupgradetool.py
Python
gpl-3.0
2,456
0.002443
#! /usr/bin/python3 import os import requests canary = 'mwtask111' serverlist = ['mw101', 'mw102', 'mw111', 'mw112', 'mw121', 'mw122'] def check_up(server: str) -> bool: headers = {'X-Miraheze-Debug': f'{server}.miraheze.org'} req = requests.get('https://meta.miraheze.org/w/api.php?action=query&meta=siteinfo...
Miraheze-Debug': f'{server}.miraheze.o
rg'} req = requests.get('https://meta.miraheze.org/w/api.php?action=query&meta=siteinfo&formatversion=2&format=json', headers=headers) response = req.json() if response['query']['general']['readonly']: return True return False print('Welcome to the MediaWiki Upgrade tool!') input('Please confi...
kelseyoo14/Wander
venv_2_7/lib/python2.7/site-packages/numpy/add_newdocs.py
Python
artistic-2.0
222,133
0.001337
""" This is only meant to add docs to objects defined in C-extension modules. The purpose is to allow easier editing of the docstrings without requiring a re-compile. NOTE: Many of the methods of ndarray have corresponding functions. If you update these docstrings, please keep also the ones in core/fromnum...
are allowed.
* 'same_kind' means only safe casts or casts within a kind, like float64 to float32, are allowed. * 'unsafe' means any data conversions may be done. op_axes : list of list of ints, optional If provided, is a list of ints or None for each operands. The list of axes for an o...