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
avanzosc/cost_simulator
cost_simulator/models/simulation_template.py
Python
agpl-3.0
4,268
0
# -*- encoding: utf-8 -*- ############################################################################## # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the...
indirect_cost_rate, } return {'value': res} def onchange_type_cost(self, cr, uid, ids, type, context=Non
e): res = {'product_id': '', 'name': '', 'description': '', 'uom_id': '', 'amount': 0 } return {'value': res}
jameshicks/pydigree
scripts/frequencies.py
Python
apache-2.0
1,422
0.004923
"A script that calculates allele frequencies from plink data" import argparse impor
t pydigree as pyd parser = argparse.ArgumentParser() parser.add_argument('--ped', required=True, help='Plink formatted PED file') parser.add_argument('--map', required=True, help='Plink formatted MAP file') parser.add_argument('--snps', required=None, nargs='*', metavar='SNP', default=None, ...
, mapfile=args.map) if args.snps is not None: onlysnps = set(args.snps) def formatted(*cells): "Print values in tab-delimited format" return '\t'.join([str(x) for x in cells]) for chromidx, chromobj in enumerate(peds.chromosomes): for locidx, markername in enumerate(chromobj.labels): ...
was4444/chromium.src
build/android/gyp/lint.py
Python
bsd-3-clause
12,623
0.010061
#!/usr/bin/env python # # Copyright (c) 2013 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. """Runs Android's lint tool.""" import argparse import os import re import sys import traceback from xml.dom import minidom fr...
path', _RelativizePath(jar_path)]) if processed_config_path: cmd.extend(['--config', _RelativizePath(processed_config_path)]) if resource_dir: cmd.extend(['--resources', _RelativizePath(resource_dir)]) if classpath:
# --libraries is the classpath (excluding active target). cp = ':'.join(_RelativizePath(p) for p in classpath) cmd.extend(['--libraries', cp]) # There may be multiple source files with the same basename (but in # different directories). It is difficult to determine what part of the path #...
arauzoliver/uip-iiig2016-prog3
FinalPC3/book.py
Python
mit
636
0.037736
import string """ Se inicializa la clase con collecciones a la base de datos MongoDB """ class book(object):
#Inicimos la clase y se configura la base de datos con collecciones def __init__(self, database): self.db = database self.mynames = database.mynames #Esta funcion busca los nombres def find_names(self): l = [] for each_name in self.mynames.find(): l.append({'name':each_name['name'], 'email':ea...
mail} self.mynames.insert(newname)
NovoImpossible/pinos
panic.py
Python
isc
149
0.040268
#Panic For Pinos by Maxim Pinigin (c) 2016-2017 import time def pa
nic(reason): print("") p
rint("Pinos Panic: " + reason) time.sleep(10) exit()
InfraBox/infrabox
src/api/handlers/account/account.py
Python
mit
3,081
0.001623
import os from email.utils import parseaddr from flask import g, request, abort from flask_restplus import Resource, fields import bcrypt from pyinfraboxutils import get_logger from pyinfraboxutils.ibflask import OK from pyinfraboxutils.ibrestplus import api from pyinfraboxutils.token import encode_user_token from...
T_SIGNUP_ENABLED'] != 'true': abort(404) b = request.get_json() email = b['email'] password1 = b['password1'] password2 = b['password2'] username = b['username'] if password1
!= password2: abort(400, 'Passwords don\'t match') e = parseaddr(email) if not e: abort(400, 'Invalid email') if not e[1]: abort(400, 'Invalid email') if not username.isalnum(): abort(400, 'Username is not alphanumeric') user =...
CPrompt/DiamondBack
check_config.py
Python
gpl-3.0
4,482
0.004462
#!/usr/bin/env python # -*- coding: utf-8 -*- # # check_config.py # # Copyright 2012 Curtis Adkins <curtadkins@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 ...
ger('default',outputFile) data = { "backupprefs":
{ "title": "BACKUP", "directories": [{ "directoryBackup": "/path/to/main/backup/", "redundantBackup": "/path/to/redundant/backup/" }], "files": [{ "filesBackup": "/home/user/.config/diamondback/filelist", "outputFile": "/home/user/.conf...
beiko-lab/gengis
plugins/MultiTreeOptimalCrossingTest/MultiTreeOptimalCrossingTestLayout.py
Python
gpl-3.0
9,286
0.06526
# -*- coding: utf-8 -*- ########################################################################### ## Python code generated with wxFormBuilder (version Sep 8 2010) ## http://www.wxformbuilder.org/ ## ## PLEASE DO "NOT" EDIT THIS FILE! ##########################################################################...
ticText( self, wx.ID_ANY, u"Weighted/Unweighted :", wx.DefaultPosition, wx.DefaultSize, 0 ) self.lblCrossingWeighted.Wrap( -1 ) bSizer82.Add( self.lblCrossingWeighted, 1, wx.ALL|wx.EXPAND, 5 ) chcCrossingWeightedChoices = [ u"Normalised", u"Unweighted" ] self.chcCrossingWeighted = wx.Choice( self, wx.ID...
chcCrossingWeighted.SetSelection( 1 ) bSizer82.Add( self.chcCrossingWeighted, 1, wx.ALL|wx.ALIGN_BOTTOM|wx.EXPAND, 5 ) szrLocation1.Add( bSizer82, 0, wx.EXPAND, 5 ) bSizer9 = wx.BoxSizer( wx.VERTICAL ) self.txtWeightInfo = wx.TextCtrl( self, wx.ID_ANY, u"The total number of crossings from accros...
doismellburning/whereami
whereami/whereami/urls.py
Python
mit
598
0.001672
from django.conf.urls import patterns, inclu
de, url # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', url(r'', include('main.urls')), # Examples: # url(r'^$', 'whereami.views.home', name='home'), # url(r'^whereami/', include('whereami.foo.urls')), # Unco...
nclude('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # url(r'^admin/', include(admin.site.urls)), )
alirizakeles/zato
code/zato-server/src/zato/server/service/internal/channel/web_socket/subscription.py
Python
gpl-3.0
3,770
0.002122
# -*-
coding: utf-8 -*- """ Copyright (C) 2016, Zato Source s.r.o. https://zato.io Licensed under LGPLv3, see LICENSE.txt for terms and conditions. """ from __future
__ import absolute_import, division, print_function, unicode_literals # stdlib from contextlib import closing # Zato from zato.common import WEB_SOCKET from zato.common.odb.model import WebSocketSubscription from zato.server.service import AsIs, Bool from zato.server.service.internal import AdminService, AdminSIO _p...
hsoft/xibless
demos/localized/MainWindow.py
Python
bsd-3-clause
820
0
ownerclass = 'AppDelegate' ownerimport = 'AppDelegate.h' # Init result = Window(330, 110, "Tell me your name!") nameLabel = Label(result, text="Name:") nameLabel.width = 45 nameField = TextField(result, text="")
helloLabel = Label(result, text="") button = Button(result, title="Say Hello", action=Action(owner, 'sayHello')) button.width = 100 # Owner Assignments owner.nameField = nameField owner.helloLabel = helloLabel #
Layout nameLabel.moveTo(Pack.UpperLeft) nameField.moveNextTo(nameLabel, Pack.Right, Pack.Middle) nameField.fill(Pack.Right) helloLabel.moveNextTo(nameLabel, Pack.Below, Pack.Left) helloLabel.fill(Pack.Right) button.moveNextTo(helloLabel, Pack.Below, Pack.Right) nameField.setAnchor(Pack.UpperLeft, growX=True) helloLabe...
acq4/acq4
acq4/__init__.py
Python
mit
1,108
0.001805
from __future__ import print_func
tion import os, sys __version__ = '0.9.3' # If we are running from a git repo, generate a more descriptive version number from .util.gitversion import getGitVersion try: gitv = getGitVersion('acq4', os.path.join(os.path.dirname(__file__), '..')) if gitv is not None: __version__ = gitv except Exceptio...
if no config is explicitly specified) # First we check the parent directory of the current module. # This path is used when running directly from a source checkout modpath = os.path.dirname(os.path.abspath(__file__)) CONFIGPATH = [ os.path.normpath(os.path.join(modpath, '..', 'config')), ] # Next check for stand...
flowlo/gothon
test/revcomp.py
Python
apache-2.0
750
0.006667
# The Computer Language Benchmarks Game # http://benchmarksgame.alioth.debian
.org/ # # contributed by Jacob Lee, Steven Bethard, et al # 2to3, fixed by Daniele Varrazzo # modified by Daniel Nanz import sys def show(seq, table=bytes.maketrans(b'ACBDGHKMNSRUTWVYacbdghkmnsrutwvy', b'TGVHCDMKNSYAAWBRTGVHCDMKNSYAAWBR'), write=sys.stdout.buffer.write, n...
nl)[: : -1] write(b'>' + header + nl) for i in range(0, len(s), 60): write(s[i : i + 60] + nl) def main(): sys.stdin = sys.stdin.detach() seqs = b''.join([line for line in sys.stdin]).split(b'>')[1 : ] for seq in seqs: show(seq) main()
Infernion/django-wiki
wiki/views/mixins.py
Python
gpl-3.0
1,668
0.001199
from __future__ import unicode_literals from __future__ import absolute_import from django.views.generic.base import TemplateResponseMixin from wiki.core.plugins import registry from wiki.conf import settings class ArticleMixin(TemplateResponseMixin): """A mixin that receives an article object as a parameter (u...
buteError as e: raise Exception( "Attribute error most likely caused by wrong MPTT version. Use 0.5.3+.\n\n" + str(e)) return super(ArticleMixin, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): kwargs['url
path'] = self.urlpath kwargs['article'] = self.article kwargs['article_tabs'] = registry.get_article_tabs() kwargs['children_slice'] = self.children_slice[:20] kwargs['children_slice_more'] = len(self.children_slice) > 20 kwargs['plugins'] = registry.get_plugins() return...
RRCKI/panda-server
pandaserver/test/missing.py
Python
apache-2.0
1,267
0.014996
import re import commands stMap = [] tmpMap = {} nLog = 30 for i in range(0,nLog): if i == 0: out = commands.getoutput('cat /data/sm/prod/httpd/logs/panda-Adder.log') else: out = commands.getoutput(
'zcat /data/sm/prod/httpd/logs/panda-Adder.log.%s.gz' % (nLog-i)) for line in out.split('\n'): stStr = re.search('start: finished',line) idsStr = re.search('ids = .*$',line) mapStr = re.search('idMap = .*$',line) if stStr == None and idsStr == None and mapStr == None: ...
except: continue if stStr != None: stMap.append(pandaID) if idsStr != None: exec idsStr.group(0) tmpMap[pandaID] = ids if mapStr != None: exec mapStr.group(0) if (pandaID in stMap) and idMap == {} and tmpMap[pandaID]...
alerta/python-alerta-client
alertaclient/cli.py
Python
apache-2.0
2,859
0.002448
import os import sys import click from alertaclient.api import Client from alertaclient.auth.utils import get_token from alertaclient.config import Config CONTEXT_SETTINGS = dict( auto_envvar_prefix='ALERTA', default_map={'query': {'compact': True}}, help_option_names=['-h', '--help'], ) cmd_folder = os....
'Output format. eg. plain, simple, grid, psql, presto, rst, html, json, json_lines') @click.option('--json', 'output', flag_value='json', help='Output in JSON format. Shortcut for "--output json"') @click.option('--color/--no-color', help='Color-coded output based on severity.') @click.option('--debug', is_fla
g=True, help='Debug mode.') @click.pass_context def cli(ctx, config_file, profile, endpoint_url, output, color, debug): """ Alerta client unified command-line tool. """ config = Config(config_file) config.get_config_for_profle(profile) config.get_remote_config(endpoint_url) ctx.obj = config...
sammyt/p3
tests/p3_select_all_vows.py
Python
mit
3,512
0.001708
from p3 import P3 from pyvows import Vows, expect import lxml from lxml.etree import ElementBase from lxml.html import builder as E from lxml.html import fromstring, tostring from lxml.cssselect import CSSSelector @Vows.batch class SelectionSelectAll(Vows.Context): class SelectBody(Vows.Context): """se...
econd'))) ) return P3(html).select('body') def select_all_matching(self, body): div = body.select_all('div') doc = div.root.document expect(div[0][0]).to_equal(doc[1][0]) expect(div[0][1]).to_equal(doc[1][1]) def progrates_parent...
doc = div.root.document expect(div[0].parent_node).to_equal(doc[1]) def does_not_propogate_data(self, body): div = body.data(['a', 'b']).select_all('div') ds = div.root.dataset expect(ds.get(div[0][0], "nope")).to_equal('nope') expect(d...
Phantasus/intelmq
intelmq/bots/collectors/xmpp/collector.py
Python
agpl-3.0
11
0.090909
''' TB
D '
''
fedebell/Laboratorio3
Laboratorio2/Diodo/analisi.py
Python
gpl-3.0
3,409
0.018796
import numpy import math import pylab from scipy.optimize import curve_fit import math import scipy.stats import lab def fit_function(x, a, b): return b*(numpy.exp(x/a)-1) FileName='/home/federico/Documenti/Laboratorio2/Diodo/dati_arduino/dati.txt' N1, N2 = pylab.loadtxt(FileName, unpack="True") errN2 = numpy.arra...
or i in range(len(N1))]) Rd = 3280.0 errRd = 30.0 eta = 4.89/1000 erreta = 0.02/1000 V1 = eta
*N1 V2 = eta*N2 I = (V1-V2)/Rd #Inserire errori per i i V errV2 = (erreta/eta + errN2/N2)*V2 errV1 = (erreta/eta + errN1/N1)*V1 errI = (errRd/Rd)*I #for i in range(len(I)): # errI[i] = 50e-06 for i in range(len(I)): if(I[i]==0.0): I[i] = 1.0e-11*i for i in range(len(V2)): if(V2[i]==0.0): V...
Erotemic/hotspotter
hotspotter/feature_compute2.py
Python
apache-2.0
7,452
0.002013
''' Computes feature representations ''' from __future__ import division, print_function from hscom import __common__ (print, print_, print_on, print_off, rrr, profile) = __common__.init(__name__, '[fc2]') # scientific import numpy as np # python from os.path import join # hotspotter from hscom import helpers as util ...
of individual kpts and desc') except MemoryError: print('\n------------') print('[fc2] Out of memory'
) print('[fc2] Trying to read: %r' % feat_path) print('[fc2] len(kpts_list) = %d' % len(kpts_list)) print('[fc2] len(desc_list) = %d' % len(desc_list)) raise if feat_cfg.whiten: desc_list = whiten_features(desc_list) return kpts_list, desc_list # Maps a preference strin...
FreshXOpenSource/wallaby-plugin-elasticsearch
wallaby/pf/peer/elasticsearch.py
Python
bsd-2-clause
5,705
0.007187
# Copyright (c) by it's authors. # Some rights reserved. See LICENSE, AUTHORS. from wallaby.pf.peer.peer import * from wallaby.pf.peer.database import * from wallaby.pf.peer.abstractQuery import * from wallaby.pf.peer.documentIDQueryResult import * from wallaby.pf.peer.valueQueryResult import * from wallaby.common.qu...
yield searcher.reindex(filter=self._filter,
templatePath=os.path.join(FX.appPath, "es")) except (Exception, Failure) as e: print "Exception while reindexing:", str(e) @defer.inlineCallbacks def _deleteIndex(self, pillow, feathers): if self._index == None: return if self._url == None: searche...
frague59/wagtailmenus
wagtailmenus/migrations/0001_initial.py
Python
mit
4,600
0.004783
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import modelcluster.fields class Migration(migrations.Migration): dependencies = [ ('wagtailcore', '0023_alter_page_revision_on_delete_behaviour'), ] operations = [ migrations.Create...
ite.', max_length=255, b
lank=True)), ('site', models.ForeignKey(related_name='flat_menus', to='wagtailcore.Site', verbose_name='site')), ], options={ 'verbose_name': 'flat menu', 'verbose_name_plural': 'flat menus', }, ), migrations.CreateModel...
harmishhk/catkin
test/unit_tests/test_find_in_workspace.py
Python
bsd-3-clause
7,589
0.003162
import os import unittest import tempfile import shutil from mock import Mock try: import catkin from catkin.find_in_workspaces import find_in_workspaces, _get_valid_search_dirs from catkin.workspace import CATKIN_MARKER_FILE except ImportError as impe: raise ImportError( 'Please adjust your p...
makedirs(ws1) os.makedirs(inc) os.makedirs(share) os.makedirs(p1inc) os.
makedirs(p1share) with open(os.path.join(ws1, CATKIN_MARKER_FILE), 'w') as fhand: fhand.write('loc1;loc2') try: fp_backup = catkin.find_in_workspaces.find_packages root_dir = tempfile.mkdtemp() catkin.find_in_workspaces.find_packages = Mock() ...
iulian787/spack
var/spack/repos/builtin/packages/py-vsts/package.py
Python
lgpl-2.1
623
0.00321
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) class PyVsts(PythonPackage): """Python wrapper around the VSTS APIs.""" homepage = "https://github.com/Microsoft...
-api" url = "https://pypi.io/packages/source/v/vsts/vsts-0.1.25.tar.gz" version('0.1.25', sha256='da179160121f5b38be061dbff29cd2b60d5d029b2207102454d77a7114e64f97') depends_on('py-setuptools', type='build') depends_on('py-msrest@0.6.0:0.6.999',
type=('build', 'run'))
rave-engine/rave
modules/opengl/common/__init__.py
Python
bsd-2-clause
648
0.007716
""" Common OpenGL functionality. """ from OpenGL import GL import rave.log from .math import ortho, identity from .versions import get_version_range def dump_info(context): context.make_current() _log('OpenGL context: {profile} {major}.{minor}', profile=context.profile, major=context.major, minor=context.mino...
ENDOR).decode('utf-8')) _log('OpenGL renderer: {renderer}', renderer=GL.glGetString(GL.GL_RENDERER).decode('utf-8')) _log('OpenGL driver: {version}', version=GL.glGetStr
ing(GL.GL_VERSION).decode('utf-8')) ## Internals. _log = rave.log.get(__name__)
cypsun/FreeCAD
src/Mod/Fem/TestFem.py
Python
lgpl-2.1
4,603
0.007386
# Unit test for the FEM module #*************************************************************************** #* Copyright (c) 2015 - FreeCAD Developers * #* Author: Przemo Firszt <przemo@firszt.eu> * #* ...
eeCAD.Console.PrintMessage('\nChecking FEM new mesh...\n') mesh = Fem.FemMesh() mesh.addNode(0, 1, 0) mesh.addNode(0, 0, 1) mesh.addNode(1, 0, 0) mesh.addNode(0, 0,
0) mesh.addNode(0, 0.5, 0.5) mesh.addNode(0.5, 0.03, .5) mesh.addNode(0.5, 0.5, 0.03) mesh.addNode(0, 0.5, 0) mesh.addNode(0.03, 0, 0.5) mesh.addNode(0.5, 0, 0) mesh.addVolume([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) self.failUnless(mesh, "FemTest of new mesh fai...
francisar/rds_manager
aliyun/api/rest/Ecs20140526UnassociateEipAddressRequest.py
Python
mit
364
0.027473
''' Created by auto_sdk on 2015.06.23 ''' from aliyun.api.base import RestApi class Ecs20140526
UnassociateEipAddressRequest(RestApi): def __init__(self,domain='ecs.aliyuncs.com',port=80): RestApi.__init__(se
lf,domain, port) self.AllocationId = None self.InstanceId = None def getapiname(self): return 'ecs.aliyuncs.com.UnassociateEipAddress.2014-05-26'
enavarro222/bblamp
user_apps/blink.py
Python
agpl-3.0
492
0.014228
#-*- coding:utf-8 -*- from lampapp import LampApp from hardware.lamp import Color #FIXME odd import.. app = LampApp() app.need("lamp") @app.setup() def setup(): app.lamp.turn_on(20, Color.fr
om_html('#
009900')) app.lamp.turn_on(18, Color.from_html('#cc0000')) on = True @app.every(1) def loop(): global on if on: app.lamp.turn_off(18) else: app.lamp.turn_on(18, Color.from_html('#cc0000')) on = not on if __name__ == "__main__": app.run()
stefanseifert/redash
old_migrations/0025_add_query_snippets_table.py
Python
bsd-2-clause
214
0
from redash.models import db, QuerySnippet if __name__ == '__main__': with db.database.transaction(): if not QuerySnippet.table_exists(): QuerySnippet.create_table()
db.close
_db(None)
anhstudios/swganh
data/scripts/templates/object/tangible/component/item/quest_item/shared_momentum_compensator.py
Python
mit
495
0.044444
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from sw
gpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/component/item/quest_item/shared_momentum_compensator.iff" result.attribute_temp
late_id = -1 result.stfName("craft_item_ingredients_n","momentum_compensator") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
device42/chef_to_device42_sync_py
nodefilter.py
Python
bsd-3-clause
3,560
0.001404
# -*- coding: utf-8 -*- # import re def node_filter(ndata, filterlist): retval = True for flt in filterlist: if 'attribute' not in flt or 'value' not in flt: continue # wrong structure apath = flt['attribute'].strip().split('.') fval = flt['value'] oprt = flt['co...
attribute']) return False
return retval
florentchandelier/zipline
zipline/data/benchmarks.py
Python
apache-2.0
2,211
0.001357
# # Copyright 2013 Quantopian, 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...
mport json import pandas as pd import numpy as np import requests import os def get_benchmark_returns(symbol): """ Get a Series of benchmark returns from IEX associated with `symbol`. Default i
s `SPY`. Parameters ---------- symbol : str Benchmark symbol for which we're getting the returns. The data is provided by IEX (https://iextrading.com/), and we can get up to 5 years worth of data. """ r = requests.get( 'https://api.iextrading.com/1.0/stock/{}/chart/5y'.form...
ThatIndividual/midas
src/statement.py
Python
gpl-2.0
3,777
0.002118
from typing import List import expression as E VAR_DECL = "STM_VAR_DECL" FUN_DECL = "STM_FUN_DECL" BLOCK = "STM_BLOCK" IF = "STM_IF" WHILE = "STM_WHILE" BREAK = "STM_BREAK" RETURN = "STM_RETURN" PRINT = "STM_PRINT" EXP_STM = "STM_EXP_STM" class Stm(object): def __init__(self, kind): ...
): res = " " * i + "[ if " + str(self.cond) + "\n" res += " " * (i + 2) + "then\n" res += self.then_block.__str__(i + 4) if self.else_block != None: res += " " * (i + 2) + "else\n" res += self.else_block.__str__(i + 4) res += "
" * i + "]\n" return res def accept(self, visitor): return visitor.visitStmIf(self) class While(Stm): def __init__(self, cond: E.Exp, body: Stm): super().__init__(WHILE) self.cond = cond self.body = body def __str__(self, i=0): res = " " * i + "[ while " ...
barche/k3d
tests/python/get_dependency.py
Python
gpl-2.0
401
0.014963
#python import k3d doc = k3d.new_document() axes = k3d.plugin.create("Axes", doc) k3d.property.connect
(doc, axes.get_property("axes"), axes.get_property("xyplane")); if k3d.property.connection(doc, axes.get_property("xyplane")).name() != "axes": raise "xyplane dependency should be axes" if k3d.property.connection(doc, axes.get
_property("yzplane")): raise "yzplane dependency should be null"
rutsky/letsencrypt
letsencrypt-apache/letsencrypt_apache/tests/parser_test.py
Python
apache-2.0
8,007
0.000125
"""Tests for letsencrypt_apache.parser.""" import os import shutil import unittest import augeas import mock from letsencrypt imp
ort errors from letsencrypt_apache.tests import util class BasicParserTest(util.ParserTest): """Apache Parser Test.""" def setUp(self): # pylint: disable=arguments-differ super(BasicParserTes
t, self).setUp() def tearDown(self): shutil.rmtree(self.temp_dir) shutil.rmtree(self.config_dir) shutil.rmtree(self.work_dir) def test_find_config_root_no_root(self): # pylint: disable=protected-access os.remove(self.parser.loc["root"]) self.assertRaises( ...
bbuchalter/python_koans
python2/koans/about_with_statements.py
Python
mit
3,777
0.004236
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Based on AboutSandwichCode in the Ruby Koans # from runner.koan import * import re # For regular expression string comparisons class AboutWithStatements(Koan): def count_lines(self, file_name): try: f = open(file_name) try: ...
cept IOError: # should never happen self.fail() def test_
finding_lines(self): self.assertEqual("test\n", self.find_line("example_file.txt")) ## ------------------------------------------------------------------ ## THINK ABOUT IT: ## ## The count_lines and find_line are similar, and yet different. ## They both follow the pattern of "sandwich code"...
pythononwheels/pow_clean
start/stubs/rest_handler_template.py
Python
mit
2,856
0.011555
#from {{appname}}.handlers.base import BaseHandler from {{appname}}.handlers.powhandler import PowHandler from {{appname}}.models.{{model_type}}.{{handler_name}} import {{handler_model_class_name}} from {{appname}}.config import myapp, database from {{appname}}.application import app import tornado.web @app.add_rest_r...
class {{handler_name}}Handler(PowHandler): # # every pow handler automatically gets these RESTful routes # thru the @app.add_rest_routes() decorator. # # 1 GET /{{handler_name}} #=> list # 2 GET /{{handler_name}}/1 #=> show # 3 GET /{{handler_name}}/new #=> new ...
}}/1 #=> update # 8 POST /{{handler_name}} #=> create # 9 DELETE /{{handler_name}}/1 #=> destroy # # standard supported http methods are: # SUPPORTED_METHODS = ("GET", "HEAD", "POST", "DELETE", "PATCH", "PUT", "OPTIONS") # you can overwrite any of those directly or leave th...
Digilent/u-boot-digilent
tools/buildman/control.py
Python
gpl-2.0
14,941
0.001673
# SPDX-License-Identifier: GPL-2.0+ # Copyright (c) 2013 The Chromium OS Authors. # import multiprocessing import os import shutil import subprocess import sys from buildman import board from buildman import bsettings from buildman import toolchain from buildman.builder import Builder from patman import command from ...
bject. If None, then it will be created and scanned make_func: Make function to use for the builder. This is called to execute 'make'. If this is None, the normal function will be used, which calls the 'make' tool with suitable arguments. This setting is useful fo...
rds. If this is None it will be created and scanned. """ global builder if options.full_help: pager = os.getenv('PAGER') if not pager: pager = 'more' fname = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), 'README') comma...
Vagab0nd/SiCKRAGE
lib3/twilio/rest/fax/v1/fax/__init__.py
Python
gpl-3.0
19,977
0.002002
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import deserialize from twilio.base import serialize from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import...
set, date_created_on_or_before=values.unset, date_created_after=values.unset, page_token=values.unset, page_number=values.unset, page_size=values.unset): """ Retrieve a single pa
ge of FaxInstance records from the API. Request is executed immediately :param unicode from_: Retrieve only those faxes sent from this phone number :param unicode to: Retrieve only those faxes sent to this phone number :param datetime date_created_on_or_before: Retrieve only faxes creat...
ThomasChiroux/boksh
build_scripts/version.py
Python
gpl-3.0
2,745
0.001098
# -*- coding: utf-8 -*- # Author: Douglas Creager <dcreager@dcreager.net> # This file is placed into the public domain. # Calculates the current version number. If possible, this is the # output of “git describe”, modified to conform to the versioning # scheme that setuptools uses. If “git describe” returns an error #...
simply import it your setup.py file, and use the # results of get_git_version() as your package version: # # from version import * # # setup( # version=get_git_version(), # . # . # . # ) # # This will au
tomatically update the RELEASE-VERSION file, if # necessary. Note that the RELEASE-VERSION file should *not* be # checked into git; please add it to your top-level .gitignore file. # # You'll probably want to distribute the RELEASE-VERSION file in your # sdist tarballs; to do this, just create a MANIFEST.in file that #...
Guneet-Dhillon/mxnet
example/ssd/demo.py
Python
apache-2.0
6,468
0.003092
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
efix : str load model prefix epoch : int load model epoch data_shape : int resize image shape mean_pixels : tuple (float, float, float) mean pixel values (R, G, B) ctx : mx.ctx running context, mx.cpu() or mx.gpu(?) num_class : int number of classes ...
hreshold force_nms : bool force suppress different categories """ if net is not None: net = get_symbol(net, data_shape, num_classes=num_class, nms_thresh=nms_thresh, force_nms=force_nms, nms_topk=nms_topk) detector = Detector(net, prefix, epoch, data_shape, mean_pixels, ctx=c...
MarcusMoeller/mfc
deb/builds/mfc1_1.0-3/mfc1-1.0/mfc1/msg.py
Python
gpl-3.0
5,415
0.000554
#!/usr/bin/python # -*- coding: utf-8 -*- # With the MindfulClock you turn your device into a Bell of Mindfulness. # Concept, Design: Marcurs Möller # <marcus.moeller@outlook.com> # <http://apps.microsoft.com/windows/de-de/app/ # mindfulclock/58063160-9cc6-4dee-9d92-...
mail.com>, # <http://erasand.jimdo.com/kontakt/> # # This file is part of the "MindfulClock". # "MindfulClock" 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...
mplied 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 # "MindfulClock". If not, see <http://www.gnu.org/licenses/>. import wx class Msg(wx.Dialog): '''mfc1...
r4fek/django-cassandra-engine
testproject/common/tests/test_django_cassandra_models.py
Python
bsd-2-clause
15,971
0.001315
from datetime import datetime from unittest import skipIf import copy import uuid from cassandra.cqlengine import ValidationError as CQLValidationError from django.core import validators from django.forms import fields from common.models import CassandraFamilyMember from django_cassandra_engine.test import TestCase a...
lyMember.all() with self.assertRaises(AttributeError): CassandraFamilyMember.get() with self.assertRaises(AttributeError): CassandraFamilyMember.filter() def test_manager_has_a_name(self): self.assertEqual(CassandraFamilyMember._default_manager.name, "objects") ...
al( CassandraFamilyMember._meta.get_all_related_objects_with_model(), [], ) def test_related_objects_property(self): self.assertEqual(CassandraFamilyMember._meta.related_objects, []) def test_db_table(self): self.assertEqual( CassandraFamilyMember._m...
sissaschool/xmlschema
xmlschema/validators/wildcards.py
Python
mit
37,107
0.002398
# # Copyright (c), 2016-2020, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author Davide Brunato <brunato@...
return all(x in
self.not_qname or get_namespace(x) in self.not_namespace for x in names) elif '##any' in self.namespace: return all(x in self.not_qname for x in names) elif '##other' in self.namespace: return all(x in self.not_qname or get_namespace(x) == self.target_names...
qedsoftware/commcare-hq
custom/up_nrhm/reports/district_functionality_report.py
Python
bsd-3-clause
3,729
0.002414
from sqlagg.columns import SimpleColumn from corehq.apps.reports.datatables import DataTablesHeader, DataTablesColumnGroup from corehq.apps.reports.generic import GenericTabularReport from corehq.apps.reports.sqlreport import DatabaseColumn from corehq.apps.reports.standard import DatespanMixin, CustomProjectReport fro...
end(format_datatables_data('%.1f%%' % value, '%.1f%%' % value)) rows[index].append(format_datatables_data(grade, grade)) else: rows[index].append(row[-1]) val = row[-1]['sort_key']
grade = get_grade(val) rows[index].append(format_datatables_data(grade, grade)) return rows, 0
dbartumeu/bower.jvectormap
converter/processor.py
Python
gpl-2.0
2,409
0.029058
import json import shapely.wkb import shapely.geometry import shapely.ops import codecs import os import inspect from osgeo import ogr from osgeo import osr infile = "/Users/kirilllebedev/Maps/ne_110m_admin_0_map_units/ne_110m_admin_0_map_units.shp" outfile = "/Users/kirilllebedev/Maps/continents_wb/continents_wb.shp"...
yer = shp_ds.CreateLayer( in_defn.GetName(), geom_type = in_defn.GetGeomType(), srs = in_layer.GetSpatialRef() ) fd = ogr.FieldDefn( 'code', 4 ) fd.SetWidth( 5 ) shp_layer.CreateField( fd ) fd = ogr.FieldDefn( 'name', 4 ) fd.SetWidth( 254 ) shp_layer.Cre...
= [] for feature in in_layer: geometry = feature.GetGeometryRef() if geometry.GetGeometryType() == ogr.wkbPolygon or geometry.GetGeometryType() == ogr.wkbMultiPolygon: geometry = shapely.wkb.loads( geometry.ExportToWkb() ) geometry = geometry.buffer(0.000000001, 1) geometries.append( geomet...
mjirik/skelet3d
skelet3d/__init__.py
Python
bsd-3-clause
187
0
__all__ = ["skeletonizer", "skeleton_analyser"] __version__ = "1.8.6
" from . import skeleton_analyser from .skeleton_analyser import SkeletonAnalyser from .skeletonizer import skele
t3d
stevenmirabito/GoalSentry
api/goalsentry/__init__.py
Python
mit
5,717
0.0007
""" Goal Sentry API Main Application """ from flask import Flask, request from database import session as db from json import dumps as jsonify from utilities import row2dict import authentication import models app = Flask(__name__) @app.route("/") def hello(): return "<h1>Goal Sentry API</h1>" """ Standard Re...
ser in models.User.query.all(): user_dict = row2dict(user) users.append(user_dict)
return jsonify(users) @app.route("/user/<user_id>", methods=["GET"]) def get_user_by_id(user_id): try: user = models.User.query.filter_by(id=user_id).first() response = return_user(user) except Exception as e: response = return_error(e) return jsonify(response) @app.route(...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractSixtranslationTumblrCom.py
Python
bsd-3-clause
562
0.033808
def extractSixtranslationTumblrCom(item): ''' Parser for 'sixtranslation.tumblr.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lo
wer(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous',
'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
lnielsen/invenio
invenio/celery/config.py
Python
gpl-2.0
3,153
0.009515
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2013, 2014 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## publishe
d by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTAB
ILITY 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA def default_...
amurzeau/streamlink-debian
src/streamlink/plugins/cbsnews.py
Python
bsd-2-clause
1,008
0.000992
import re from streamlink.plugin import Plugin, pluginmatcher from streamlink.plugin.api import validate from streamlink.stream.hls import HLSStream @pluginmatcher(re.compile( r"https?://www\.cbsnews\.com/live/" )) class CBSNews(Plugin): _re_default_payload = re.compile(r"CBSNEWS.defaultPayload = (\{.*)") ...
ems") )) ) def _get_streams(self): items = self.sess
ion.http.get(self.url, schema=self._schema_items) if items: for hls_url in items: yield from HLSStream.parse_variant_playlist(self.session, hls_url).items() __plugin__ = CBSNews
MusculoskeletalAtlasProject/mapclient
src/mapclient/tools/pmr/dialogs/ui_registerdialog.py
Python
gpl-3.0
6,405
0.004215
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'registerdialog.ui' ## ## Created by: Qt User Interface Compiler version 5.15.2 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! ###########...
ckedWidgetRegister.setCurrentIndex(0) QMetaObj
ect.connectSlotsByName(RegisterDialog) # setupUi def retranslateUi(self, RegisterDialog): RegisterDialog.setWindowTitle(QCoreApplication.translate("RegisterDialog", u"PMR Register", None)) self.label.setText(QCoreApplication.translate("RegisterDialog", u"Physiome Model Repository", None)) ...
sbesson/openmicroscopy
components/tools/OmeroWeb/test/integration/test_csrf.py
Python
gpl-2.0
13,891
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2014-2015 Glencoe Software, Inc. # All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 o...
ek(0) request_url = reverse
('annotate_file') data = { 'image': img.id.val, 'index': 0, 'annotation_file': temp } post(self.django_client, request_url, data) finally: temp.close() # link existing annotation is handled by the same reque...
rajalokan/nova
nova/api/openstack/compute/flavor_rxtx.py
Python
apache-2.0
1,768
0
# Copyright 2012 Nebula, 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...
@wsgi.extends def detail(self, req, resp_obj): context = req
.environ['nova.context'] if not context.can(fr_policies.BASE_POLICY_NAME, fatal=False): return self._extend_flavors(req, list(resp_obj.obj['flavors']))
nwiizo/workspace_2017
pen_test_code/XSS-injection.py
Python
mit
571
0.047285
import mechanize url =
"http://www.webscantest.com/crosstraining/aboutyou.php" browser = mechanize.Browser() attackNumber = 1 with open('XSS-vectors.txt') as f: for line in f: browser.open(url) browser.select_form(nr=0) browser["fname"] = line res = browser.submit() content = res.read() # check the attack vector is pr...
utput.write(content) output.close() print(attackNumber) attackNumber += 1
ai-ku/langvis
jython-2.1/Lib/macpath.py
Python
mit
6,265
0.004789
"""Pathname and path-related operations for the Macintosh.""" import os from stat import * __all__ = ["normcase","isabs","join","splitdrive","split","splitext", "basename","dirname","commonprefix","getsize","getmtime", "getatime","islink","exists","isdir","isfile", "walk","exp...
e this is to raise an exception raise norm_error, 'Cannot use :: immedeately after volume name' else: i = i + 1 s = ":".join(comps) # remove trailing ":" except for ":" and "Volume:" if s[-1] == ":" and len(comps) > 2 and s != ":"*len(s): s = s[:-1] ...
called, where dirname is the name of the directory and filenames is the list of files (and subdirectories etc.) in the directory. The func may modify the filenames list, to implement a filter, or to impose a different order of visiting.""" try: names = os.listdir(top) except os....
postrational/django
django/contrib/admin/sites.py
Python
bsd-3-clause
18,932
0.001796
from functools import update_wrapper from django.http import Http404, HttpResponseRedirect from django.contrib.admin import ModelAdmin, actions from django.contrib.admin.forms import AdminAuthenticationForm from django.contrib.auth import logout as auth_logout, REDIRECT_FIELD_NAME from django.contrib.contenttypes impor...
ur " "INSTALLED_APPS setting in order to use the admin application.") if not ContentType._meta.installed: raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in " "your INSTALLED_APPS setting in order to use the admin application.") if not ('django.c...
ssors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS or 'django.core.context_processors.auth' in settings.TEMPLATE_CONTEXT_PROCESSORS): raise ImproperlyConfigured("Put 'django.contrib.auth.context_processors.auth' " "in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the ...
joedicastro/turses
turses/api/helpers.py
Python
gpl-3.0
5,201
0.000192
""" This module contains various methods for checking the type of timelines and a class that creates all kinds of timelines. """ import re from functools import partial from gettext import gettext as _ from turses.models import Timeline, is_DM HOME_TIMELINE = 'home' MENTIONS_TIMELINE = 'mentions' FAVORITES_TIMELINE...
line, update_function_name=None): if not isinstance(timeline, Timeline): return False update_function = timeline.update_function if update_function is None: return False return update_function.__name__ == update_function_name is_home_timeline = partial(check_update_f
unction_name, update_function_name='get_home_timeline') is_mentions_timeline = partial(check_update_function_name, update_function_name='get_mentions') is_favorites_timeline = partial(check_update_function_name, update_function_na...
sdoran35/hate-to-hugs
venv/lib/python3.6/site-packages/nltk/tbl/demo.py
Python
mit
14,715
0.006116
# -*- coding: utf-8 -*- # Natural Language Toolkit: Transformation-based learning # # Copyright (C) 2001-2017 NLTK Project # Author: Marcus Uneson <marcus.uneson@gmail.com> # based on previous (nltk2) version by # Christopher Maloof, Edward Loper, Steven Bird # URL: <http://nltk.org/> # For license information, see...
ature. """ postag(templates=[Template(Word([0]), Pos([-2,-1]))]) def demo_template_statistics(): """ S
how aggregate statistics per template. Little used templates are candidates for deletion, much used templates may possibly be refined. Deleting unused templates is mostly about saving time and/or space: training is basically O(T) in the number of templates T (also in terms of memory usage, which often ...
CMUSV-VisTrails/WorkflowRecommendation
vistrails/packages/controlflow/list_module.py
Python
bsd-3-clause
2,364
0.021151
############################################################################### ## ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ##
## "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, ## this list of conditions and the following disclaimer. ## - Redistributions in bi...
ollowing disclaimer in the ## documentation and/or other materials provided with the distribution. ## - Neither the name of the University of Utah nor the names of its ## contributors may be used to endorse or promote products derived from ## this software without specific prior written permission. ## ## T...
ibigbug/leetcode
longest-common-prefix.py
Python
mit
542
0
# Link: https://leetcode.com/problems/longest-common-prefix/ class Solution: # @param {string[]} strs # @return {string} def longestCommonPrefix(self, strs): if not len(strs): return '' if len(strs) == 1: return strs[0] ret = [] for i in range(0, len(...
if len(strs[j]) == i or strs[j][i] != strs[0][i]:
return ''.join(ret) ret.append(strs[0][i]) return ''.join(ret)
mwgamera/u413
newmessage.py
Python
agpl-3.0
2,828
0.045262
'''u413 - an open-source BBS/transmit/PI-themed forum Copyright (C) 2012 PiMaster Copyright (C) 2012 EnKrypt This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the Licens...
er==None: return False return True def nmsg_f
unc(args,u413): if "step" in u413.cmddata: if u413.cmddata["step"]==1: u413.cmddata["step"]=2 args=args.strip().split()[0] to=user_id(args) if to==None: u413.type('"%s" is not a u413 user.'%args) return u413.cmddata["to"]=to u413.type("Enter the topic:") u413.set_context("TOPIC") u413...
kachick/topaz
topaz/consts.py
Python
bsd-3-clause
2,843
0
import sys from rpython.rlib.unroll import unrolling_iterable SEND_EFFECT = 0xFF ARRAY_EFFECT = 0xFE BLOCK_EFFECT = 0xFD UNPACK_EFFECT = 0xFC # Name, number of arguments, stack effect BYTECODES = [ ("LOAD_SELF", 0, +1), ("LOAD_SCOPE", 0, +1), ("LOAD_BLOCK", 0, +1), ("LOAD_CODE", 0, +1), ("LOAD_C...
L", 1, 0), ("DEFINED_GLOBAL", 1, +1), ("BUILD_ARRAY", 1, ARRAY_EFFECT), ("BUILD_ARRAY_SPLAT", 1, ARRAY_EFFECT), ("BUILD_STRING", 1, ARRAY_EFFECT), ("BUILD_HASH", 0, +1), ("BUILD_RANGE", 0, -1), ("BUILD_RANGE_EXCLUSIVE", 0, -1), ("BUILD_FUNCTION", 0, -1), ("BUILD_BLOCK", 1, BLOCK_EFF...
("BUILD_CLASS", 0, -2), ("BUILD_MODULE", 0, -1), ("BUILD_REGEXP", 0, -1), ("COERCE_ARRAY", 1, 0), ("COERCE_BLOCK", 0, 0), ("COERCE_STRING", 0, 0), ("UNPACK_SEQUENCE", 1, UNPACK_EFFECT), ("UNPACK_SEQUENCE_SPLAT", 2, UNPACK_EFFECT), ("DEFINE_FUNCTION", 0, -2), ("ATTACH_FUNCTION", 0...
arkarkark/feedapp
src/server/crud/crud_model.py
Python
mit
7,336
0.008315
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
ct methods. """ # If your model has a parent type, you need to set it here as a string. par
ent_model_name = None def AsJsonDict(self, entity_id=None, json_dict=None, include=None, exclude=None): """Make a dict suitable for json encoding from this model entity.""" return JsonDictFromEntity(self, entity_id=entity_id, json_dict=json_dict, include=include...
rubik/pyg
tests/pypi_cache_server.py
Python
mit
3,301
0.003635
''' Pypi cache server Original author: Victor-mortal ''' import os import httplib import urlparse import logging import locale import json import hashlib import webob import gevent from gevent import wsgi as wsgi_fast, pywsgi as wsgi, monkey CACHE_DIR = '.cache' wsgi = wsgi_fast # comment to use pywsgi host = '0.0.0...
) start_response(o['response'], o['headers']) return self.yieldData( open(cache_file) ) self.log.debug('Request from %s to %s', req.remote_addr, path) url = path conn = httplib.HTTPConnection(self.pypiHost, timeout=self.timeout) #headers['X-Forwarded-For'] = re...
thod, url, headers=headers, body=req.body) response = conn.getresponse() except Exception, e: msg = str(e) if os.name == 'nt': _, encoding = locale.getdefaultlocale() msg = msg.decode(encoding) self.log.warn('Bad gateway with reason...
Babaritech/babar3
back/babar_twitter/admin.py
Python
mit
267
0
from django.contrib import admin from .models import * class TweetAdmin(admin.ModelAdmin): fiel
ds = ['time', 'message', 'timestamp'] readonly_fields = ['time', 'message', 'timesta
mp'] list_filter = ['timestamp'] admin.site.register(Tweet, TweetAdmin)
rabipanda/tensorflow
tensorflow/python/grappler/memory_optimizer_test.py
Python
apache-2.0
12,186
0.00476
# Copyright 2017 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...
folding=rewr
iter_config_pb2.RewriterConfig.OFF, memory_optimization=rewriter_config_pb2.RewriterConfig.MANUAL) graph = tf_optimizer.OptimizeGraph(rewriter_config, mg) self.assertEqual(len(graph.node), graph_size) self.assertItemsEqual([node.name for node in graph.node], nodes) def testSimpleSwap(self): ...
satuma777/evoltier
evoltier/selection/pbil_selection.py
Python
gpl-3.0
1,621
0.002468
import numpy as np from math import floor from ..weight import RankingBasedSelection class PBILSelection(RankingBasedSelection): """ This selection scheme is used by PBIL and compact GA. Also, PBIL selection scheme also used in natural gradient update with Bernoulli distribution. See also, [Shira...
ion_rate=0.5, is_use_negative=True, is_minimize=True, is_normalize=False): super(PBILSelection, self).__init__(is_minimize, is_normalize) self.selection_rate = selection_rate self.is_use_negative = is_use_negative def transform(self, rank_based_vals, xp=np): weights = xp.zeros_like(...
half_num_weight = floor(worst_rank * self.selection_rate / 2.) # the best floor(lam * selection_rate / 2) samples get the positive weights idx_positive = idx_sorted_rank[:half_num_weight] weights[idx_positive] = 1 # the worst floor(lam * selection_rate / 2) samples get ...
emersonsoftware/ansiblefork
lib/ansible/plugins/terminal/junos.py
Python
gpl-3.0
1,690
0.000592
# # (c) 2016 Red Hat Inc. # # 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 later version. # # Ansible is d...
"unknown command"), re.compile(r"syntax error,") ] def on_open_shell(self): try: for c in ['set cli timestamp disable', 'set cli screen-length 0']: self._exec_cli_command(c) except AnsibleConnectionFailure: raise
AnsibleConnectionFailure('unable to set terminal parameters') @staticmethod def guess_network_os(conn): stdin, stdout, stderr = conn.exec_command('show version') if 'Junos' in stdout.read(): return 'junos'
draios/python-sdc-client
examples/user_team_mgmt.py
Python
mit
2,675
0.001495
#!/usr/bin/env python # # This example shows the different aspects of user/team management. # import sys from sdcclient import SdcClient # # Parse arguments # if len(sys.argv) != 4: print(('usage: %s <sysdig-token> team-name user-name' % sys.argv[0])) print('You can find your token at https://app.sysdigcloud...
eam_name) if not ok: print(('Team creation failed:', res, '. Exiting.')) sys.exit(1) else: print(('Team creation succeeded.', res)) print(('Now trying to find team with name:', team_name)) ok, res = sdclient.get_team(team_name) if not ok: print(('Could not get team info:', res, '. Exiting.')) sys.e...
ed') print(('Now trying to edit team:', team_name)) memberships = { 'admin@draios.com': 'ROLE_TEAM_MANAGER', 'john-doe@sysdig.com': 'ROLE_TEAM_READ' } ok, res = sdclient.edit_team(team_name, description='Nextgen2', memberships=memberships) if not ok: print(('Could not edit team:', res, '. Exiting.')) s...
beppec56/core
solenv/gdb/libreoffice/cppu.py
Python
gpl-3.0
5,260
0.002662
# -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*- # # This file is part of the LibreOffice project. # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # ...
= impl['elements'].cast(elemtype.pointer()) return self.iterator(elements, int(impl['nElements'])) else: # TODO is that the best thing to do here? return None
def display_hint(self): if self.value['_pSequence']: return 'array' else: return None class UnoTypePrinter(object): '''Prints UNO Type''' def __init__(self, typename, value): self.value = value self.typename = typename.replace('com::sun::star::', '...
jongha/gedit-removetrailingspaces
src/gedit/plugins/removetrailingspaces.py
Python
mit
1,987
0.005033
#!/usr/bin/env python from gi.repository import GObject, Gtk, Gedit UI_XML = '''<ui> <menubar name="MenuBar"> <menu name="ToolsMenu" action="Tools"> <placeholder name="ToolsOps_2"> <menuitem name="Remove Trailing Spaces" action="RemoveTrailingSpacesPlugin"/> </placeholder> </menu> </menuba...
veTrailingSpacesPlugin(GObject.Object, Gedit.WindowActivatable): __gtype_name__ = 'RemoveTrailingSpacesPlugin' window = GObject.property(type=Gedit.Window) def __init__(self): GObject.Object.__init__(self) def _add_ui(self): manager = self.window.get_ui_manager() self._actions ...
ActionGroup('RemoveTrailingSpacesActions') self._actions.add_actions([ ( 'RemoveTrailingSpacesPlugin', Gtk.STOCK_INFO, 'Remove Trailing Spaces', '<control><alt>s', 'Remove trailing space in current document', self.on_remove_tail...
kizzen/Baller-Shot-Caller
ModelFitting/single_Kmeans.py
Python
mit
3,462
0.009821
""" In this case, imputing helps the classifier get close to the original score. Cross Validation Link: http://scikit-learn.org/stable/auto_examples/model_selection/grid_search_digits.html#sphx-glr-auto-examples-model-selection-grid-search-digits-py """ ############################## # Module imports and dependencie...
) df.max() df.min() type(predictors) #============================================================================== # Clustering using Kmea
ns #============================================================================== #defining the object that will carry out the kmeans clustering part. KMeans_object = KMeans(init = 'k-means++', n_clusters = 17, n_init= 10) #doing the kmeans clustering KMeans_object.fit(predictors) #printing the inertia print('The Ine...
rossant/spiky
experimental/ephyview.py
Python
bsd-3-clause
7,411
0.006882
import os import numpy as np import tables import galry.pyplot as plt from galry import Visual, process_coordinates, get_next_color, get_color from qtools import inthread MAXSIZE = 5000 CHANNEL_HEIGHT = .25 class MultiChannelVisual(Visual): def initialize(self, x=None, y=None, color=None, point_size=1.0, ...
np.arange(nprimitives), nsamples) color_array_index = np.array(color_array_index) ncolors = color.shape[0] ncomponents = color.shape[1] color = color.reshape((1, ncolors, ncomponents)) dx = 1. / ncolors offset = dx / 2. self.add_text...
ndex', ndim=1, vartype='int', data=color_array_index) self.add_varying('vindex', vartype='int', ndim=1) self.add_uniform('nchannels', vartype='float', ndim=1, data=float(nprimitives)) self.add_uniform('channel_height', vartype='float', ndim=1, data=channel_height) self.add_verte...
bartoszj/Mallet
mallet/loader.py
Python
mit
21,220
0.002545
#! /usr/bin/env python # -*- coding: utf-8 -*- # The MIT License (MIT) # # Copyright (c) 2014 Bartosz Janda # # 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 w...
() self.loaded_packages = list() # Reload builtin scripts. self.__reload_internal_scripts()
# Clean log file. clean_log_file = False if u"clean_logs" in user_configuration: clean_log_file = bool(user_configuration[u"clean_logs"]) if clean_log_file: logger.get_shared_logger_configurator().clean_log_file() # Configure logger. configure_lo...
Heaven91/Robotics-AI
Chapter5-PID/robot_navigation.py
Python
agpl-3.0
19,283
0.000363
# ----------- # User Instructions # # Familiarize yourself with the code below. Most of it # reproduces results that you have obtained at some # point in this class. Once you understand the code, # write a function, cte, in the run class that # computes the crosstrack # error for the case of a segmented path. Y...
[f, g, h, x, y]] found = False # flag that is set when search complete resign = False # flag set if we can't find expand count = 0
while not found and not resign: # check if we still have elements on the open list if len(open) == 0: resign = True print '###### Search terminated without success' else: # remove node from list ope...
bstroebl/QGIS
python/plugins/sextante/grass/ext/v_univar.py
Python
gpl-2.0
1,499
0.00467
# -*- coding: utf-8 -*- """ *************************************************************************** v_univar.py --------------------- Date : December 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ****************************...
********************************************* """ __author__ = 'Victor Olaya' __date__ = 'December 2012' __copyright__ = '(C) 2012, Victor Olaya' # This will get replaced with a git SHA1 w
hen you do a git archive __revision__ = '$Format:%H$' def postProcessResults(alg): htmlFile = alg.getOutputFromName('html').value found = False f = open(htmlFile, "w") f.write("<h2>v.univar</h2>\n") for line in alg.consoleOutput: if found and not line.strip()....
Uberspace/ansible-mountopts
library/mountopts.py
Python
mit
2,560
0.008203
from ansible.module_utils.basic import AnsibleModule import os.path try: import fstab HAS_FSTAB_LIB = True except: HAS_FSTAB_LIB = False def find_mount(ft, directory): for l in ft.lines: if l.has_filesystem() and l.directory == directory: return l def parse_options(options): ...
ed value was set') module.ex
it_json(changed=changed) if __name__ == '__main__': main()
acetcom/cellwire
lib/gtp/support/cache/tlv-msg-list.py
Python
gpl-3.0
3,258
0.049417
msg_list["Echo Request"] = { "type" : "1" } msg_list["Echo Response"] = { "type" : "2" } msg_list["Version Not Supported Indication"] = { "type" : "3" } msg_list["Create Session Request"] = { "type" : "32" } msg_list["Create Session Response"] = { "type" : "33" } msg_list["Delete Session Request"] = { "type" : "36" } m...
_list["Change Notification Response"] = { "type" : "39" } msg_list["Resume Notification"] = { "type" : "164" } msg_list["Resume Acknowledge"] = { "type" : "165" } msg_list["Modify Bearer Command"] = { "type" : "64" } msg_list["Modify Bearer Failure Indication"] = { "type" : "65" } msg_list["Delete Bearer Command"] = { ...
} msg_list["Delete Bearer Failure Indication"] = { "type" : "67" } msg_list["Bearer Resource Command"] = { "type" : "68" } msg_list["Bearer Resource Failure Indication"] = { "type" : "69" } msg_list["Downlink Data Notification Failure Indication"] = { "type" : "70" } msg_list["Trace Session Activation"] = { "type" : "7...
gmimano/commcaretest
corehq/apps/hqmedia/decorators.py
Python
bsd-3-clause
1,354
0.002954
from django.contrib.auth import get_user from django.utils.importlib import import_module from corehq.apps.domain.decorators import login_and_domain_required from django.conf import settings from corehq.apps.users.models import CouchUser def login_with_permission_from_post(login_decorator=login_and_domain_required): ...
insert the cookie directly into the header of the request. """ def view_decorator(view_func): def new_view(req, domain, *args, **kwargs): if req.method == 'POST': cookie = req.POST.get('_cookie') if cookie: cookies = dict(map(lambda x: ...
t(settings.SESSION_COOKIE_NAME, None) engine = import_module(settings.SESSION_ENGINE) req.session = engine.SessionStore(session_key) req.user = get_user(req) req.couch_user = CouchUser.from_django_user(req.user) return login_de...
lnlfp/lnlfp
lionel/urls.py
Python
mit
198
0
from django.conf.urls i
mport url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^loader/', include('loader.urls', namespace='loader')), ]
huggingface/transformers
tests/transfo_xl/test_tokenization_transfo_xl.py
Python
apache-2.0
4,120
0.001942
# coding=utf-8 # Copyright 2020 The HuggingFace Team. 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 requir...
ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ..test_tokeni...
tion_common import TokenizerTesterMixin class TransfoXLTokenizationTest(TokenizerTesterMixin, unittest.TestCase): tokenizer_class = TransfoXLTokenizer test_rust_tokenizer = False test_seq2seq = False def setUp(self): super().setUp() vocab_tokens = [ "<unk>", ...
mkuron/espresso
testsuite/python/random_pairs.py
Python
gpl-3.0
3,399
0.000588
# Copyright (C) 2010-2018 The ESPResSo project # # This file is part of ESPResSo. # # ESPResSo 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 v...
the cell systems, which should be identical. This check is repeated for all valid combinations of periodicities. """ system = espressomd.System(box_l=3 * [10.]) def setUp(self): s = self.system s.time_step = .1 s.cell_system.skin = 0.0 s.min_global_cut = 1.5 ...
.random.random((n_part, 3))) self.all_pairs = [] dist_func = self.system.distance for pair in self.system.part.pairs(): if dist_func(pair[0], pair[1]) < 1.5: self.all_pairs.append((pair[0].id, pair[1].id)) self.all_pairs = set(self.all_pairs) ...
kylepjohnson/cltk
src/cltk/lemmatize/naive_lemmatizer.py
Python
mit
4,766
0.001679
import math import os import re from abc import ABC, abstractmethod from typing import List, Tuple, Union from numpy import argmax from cltk.utils import CLTK_DATA_DIR def _build_match_and_apply_functions(pattern, replace): def matches_rule(word): return re.search(pattern, word) def ...
_counts.get(word, 0) return math.log(count / len(self.unigram_counts)) if count > 0 else 0 def _apply_regex(self, token): """Looks for a m
atch in the regex rules with the token. If found, applies the replacement part of the rule to the token and returns the result. Else just returns the token unchanged. """ for matches_rule, apply_rule in self.regex_rules: if matches_rule(token): return ap...
ankurankan/scikit-learn
sklearn/metrics/tests/test_ranking.py
Python
bsd-3-clause
37,643
0.000027
from __future__ import division, print_function import numpy as np from itertools import product import warnings from sklearn import datasets from sklearn import svm from sklearn import ensemble from sklearn.datasets import make_multilabel_classification from sklearn.random_projection import sparse_random_matrix fro...
k for correctness of `average_precision_score`.""" pos_label = np.unique(y_true)[1] n_pos = np.sum(y_true == pos_label) order = np.argsort(y_score)[::-1] y_score = y_score[order] y_true = y_
true[order] score = 0 for i in range(len(y_score)): if y_true[i] == pos_label: # Compute precision up to document i # i.e, percentage of relevant documents up to document i. prec = 0 for j in range(0, i + 1): if y_true[j] == pos_label: ...
dtnaylor/web-profiler
tools/test.py
Python
mit
2,306
0.008239
#! /usr/bin/env python import os import sys import shutil import logging import argparse import tempfile sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from webloader.phantomjs_loader import PhantomJSLoader from webloader.curl_loader import CurlLoader from webloader.pythonrequests_loader import Python...
import FirefoxLoader def get_loader(**kwargs): loader = args.loader.lower() if 'python' in loader or 'requests' in loader: return PythonRequestsLoader(full_page=False, **kwargs) elif 'curl' in loader: return CurlLoader(full_page=False, **kwargs) elif 'phantom'
in loader or 'js' in loader: return PhantomJSLoader(**kwargs) elif 'chrome' in loader: return ChromeLoader(**kwargs) elif 'firefox' in loader: return FirefoxLoader(**kwargs) else: logging.error('Unknown loader: %s', args.loader) sys.exit(-1) def main(): outdir ...
XeCycle/indico
indico/MaKaC/conference.py
Python
gpl-3.0
377,852
0.009117
# This file is part of Indico. # Copyright (C) 2002 - 2015 European Organization for Nuclear Research (CERN). # # Indico 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 (a...
imezone from pytz import all_timezones from persistent import Persistent from BTrees.OOBTree import OOBTree, OOTreeSet from BTrees.OIBTree import OIBTree,OISet,union import MaKaC from MaKaC.common import indexes from MaKaC.common.timezoneUtils import nowutc, maxDatetime import MaKaC.fileRepository as fileRepository fr...
LinkedTimeSchEntry, BreakTimeSchEntry) import MaKaC.review as review from MaKaC.common import utils from MaKaC.common.Counter import Counter from MaKaC.common.ObjectHolders import ObjectHolder from MaKaC.common.Locators import Locator from MaKaC.accessControl import AccessController from MaKaC.errors import MaKaCError...
danakj/chromium
third_party/WebKit/Tools/Scripts/webkitpy/tool/servers/rebaseline_server_unittest.py
Python
bsd-3-clause
12,199
0.00082
# Copyright (C) 2010 Google Inc. 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, this list of conditions and the f...
'Rebaselining fast/image...', ' Updating baselines for mac', ' Updated image-expected.checksum',
' Updated image-expected.png', ]) def test_gather_baselines(self): example_json = layouttestresults_unittest.LayoutTestResultsTest.example_full_results_json results_json = json.loads(strip_json_wrapper(example_json)) server = RebaselineServer() server...
tangfeng1/flask
tests/test_basic.py
Python
bsd-3-clause
42,900
0.00021
# -*- coding: utf-8 -*- """ tests.basic ~~~~~~~~~~~~~~~~~~~~~ The basic functionality. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import pytest import re import uuid import time import flask import pickle from datetime import datetime from threading ...
flask.session['testing'] = 42 return 'Hello World' rv = app.test_client().get('/', 'http://example.com:8080/') assert 'domain=.example.com' in rv.headers['set-cookie'].lower() assert 'httponly' in rv.headers['set-cookie'].lower() def test_session_using_server_name_port_and_path(): app = fla...
@app.route('/') def index(): flask.session['testing'] = 42 return 'Hello World' rv = app.test_client().get('/', 'http://example.com:8080/foo') assert 'domain=example.com' in rv.headers['set-cookie'].lower() assert 'path=/foo' in rv.headers['set-cookie'].lower() assert 'httponly' i...
msabramo/ianitor
src/ianitor/service.py
Python
lgpl-3.0
4,043
0
# -*- coding: utf-8 -*- # Copyright (C) 2014 by Clearcode <http://clearcode.cc> # and associates (see AUTHORS.md). # This file is part of ianitor. # ianitor is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundat...
e:" + self.service_id def start(self): """ Start service process. :return: """ logger.debug("starting service: %s" % " ".join(self.command)) self.process = subprocess.Popen(self.command) self.register() def is_up(self): """ Poll service process ...
) and self.process.poll() is None def kill(self): """ Kill service process and make sure it is deregistered from consul cluster. :return: """ logger.debug("killing service") if self.process is None: raise RuntimeError("Process does not exist") ...
programa-stic/barf-project
barf/arch/__init__.py
Python
bsd-2-clause
1,406
0.001422
# Copyright (c) 2014, Fundacion Dr. Manuel Sadosky # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this # list of condit...
R A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTER...
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from __future__ import absolute_import from .arch import *
nparley/mylatitude
lib/Crypto/SelfTest/Cipher/test_pkcs1_15.py
Python
mit
7,342
0.005176
# -*- coding: utf-8 -*- # # SelfTest/Cipher/test_pkcs1_15.py: Self-test for PKCS#1 v1.5 encryption # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone i...
23 a3 54 7e 02 0b 42 1d 61 6c af 67 b8 4e 17 56 80 66 36 04 64 34 26 8a 47 dd 44 b3 1a b2 17 60 f4 91 2e e2 b5 95 64 cc f9 da c8 70 94 54 86 4c ef 5b 08 7d 18 c4 ab 8d 04 06 33 8f ca 15 5f 52 60 8a a1 0c f5 08 b5 4c bb 99 b8 94 25 04 9c e6...
65 61 13 8a a7 47 77 81 ae 0d b8 2c 4d 50 a5''' ), ) def testEncrypt1(self): for test in self._testData: # Build the key key = RSA.importKey(test[0]) # RNG that takes its random numbe...
gbezyuk/django-react-redux-universal-hot-example
backend/api/serializers/photo.py
Python
mit
292
0
from photos.models import Photo from rest_framework.serializers import HyperlinkedModelSerializer from .utils import MyImageField class PhotoSerializer(HyperlinkedModelSerializer):
image = MyImageField() class Meta:
model = Photo fields = ('name', 'slug', 'image')
nigroup/pypet
pypet/tests/all_examples.py
Python
bsd-3-clause
4,589
0.001743
"""Module running all examples in the examples directory Suppresses all openings of plots """ __author__ = 'Robert Meyer' import glob import os import sys import platform import subprocess try: import brian except ImportError: print('No BRIAN module found, will skip the example') brian = None try: i...
s.pat
h.join('..','..','examples')) sys.path.append(os.getcwd()) simple_examples = glob.glob('*.py') assert len(simple_examples) == 24 - 5 + 1 + 2 # + Number of Examples - Number of Packages + __init__.py + 19b and 19c for simple_example in simple_examples: if simple_example == '__init__': ...
mabotech/mabozen
mabozen/lib/parse_url.py
Python
mit
163
0.018405
from mabozen.lib.url import parse_rfc1738_args def pa
rse_url(db_url): """parse url""" components = parse_rfc1738_args(db_url) return
components
HeraldStudio/HeraldAppApi
mod/kuaidi/Utlis/Helper.py
Python
mpl-2.0
667
0
# -*- codin
g=utf-8 -*- """ Created on Aug 10, 2016 @author: corvo """ import json import urllib import urllib2 def get_card(_uuid): """ 通过uuid 获取一卡通号 """ _check_path = 'http://www.heraldstudio.com/api/user' # print (_uuid) params = {'uuid': _uuid} data = urllib.urlencode(params) ...
]['cardnum'] def check_superuser(_superuser): """ 修改状态时, 用于超级用户是否有效 """ return True
atantet/transferCZ
plot/plot_index_loop_seasonal.py
Python
gpl-2.0
5,743
0.004527
import os import numpy as np import matplotlib.pyplot as plt from matplotlib import cm, colors initDir = '../init/' nlat = 31 nlon = 30 # Dimensions L = 1.5e7 c0 = 2 timeDim = L / c0 / (60. * 60. * 24) H = 200 tau_0 = 1.0922666667e-2 delta_T = 1. sampFreq = 0.35 / 0.06 * 12 # (in year^-1) # Case definition muRng = n...
transform and shift zero frequency to center fts = np.fft.fft(tsWindowed, nfft, 0) fts = np.fft.fftshift(fts) # Get periodogram perio = np.abs(fts / nt)**2 # Apply runn
ing average perioRAVG = perio.copy() for iavg in np.arange(nRAVG/2, nfft-nRAVG/2): perioRAVG[iavg] = perio[iavg-nRAVG/2:iavg+nRAVG/2 + 1].mean()\ / nRAVG # Plot fig = plt.figure() ax = fig.add_subplot(1,1,...
mkopar/Virus-classification-theano
VirClass/load.py
Python
mit
29,948
0.004374
"""Module for building new datasets or reading it from files. Upper layer of data (sequence) management.""" # pylint: disable=too-many-arguments, too-many-locals import gzip import math import os import pickle import random import sys from collections import defaultdict import numpy as np from Bio import SeqIO from Bi...
tion. From vector x, we get matrix of sizes [x.length, n]. Example: We have 5 different classes (0, 1, 2, 3, 4) and vector x = [0, 0, 1, 2, 2, 3, 4]. From that we would get matrix of sizes [7, 5] and the matrix would look like: [1, 0, 0, 0, 0], ...
0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1] :param x: vector of true classes (Y) :param n: number of classes :return: Y matrix in binary representation """ assert np.max(x) < n, "Cannot create numpy array; number of classes must be bigger than max n...
fingeronthebutton/RIDE
utest/controller/test_resourcefilecontrollerfactory.py
Python
apache-2.0
1,771
0.011293
import unittest from robotide.controller.filecontrollers import ResourceFileControllerFactory class ResourceFileControllerFactoryTestCase(unittest.TestCase): def setUp(self): namespace = lambda:0 project = lambda:0 self._resource_file_controller_factory = ResourceFileControllerFactory(nam...
ports_unresolved() self.assertFalse(self._resource_file_controller_factory.is_all_resource_file_imports_resolved()) def test_all_resource_imports_is_unresolved_when_new_resource
_is_added(self): self._resource_file_controller_factory.set_all_resource_imports_resolved() data = lambda:0 data.source = 'source' data.directory = 'directory' self._resource_file_controller_factory.create(data) self.assertFalse(self._resource_file_controller_factory.is_a...
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/south/tests/autodetection.py
Python
agpl-3.0
12,026
0.009479
from south.tests import unittest from south.creator.changes import AutoChanges, InitialChanges from south.migration.base import Migrations from south.tests import Monkeypatcher from south.creator import freezer from south.orm import FakeORM from south.v2 import SchemaMigration try: from django.utils.six.moves imp...
elf): "Test with a completely unchanged definition." self.assertEqual( AutoChanges.different_attributes( ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['southdemo.Lizard']"}), ('django.db.models.fields.related.ForeignKey', [], {'to': "...
('django.db.models.fields.related.ForeignKey', ['ohhai', 'there'], {'to': "somewhere", "from": "there"}), ('django.db.models.fields.related.ForeignKey', ['ohhai', 'there'], {"from": "there", 'to': "somewhere"}), ), False, ) def test_pos_change(self): ...