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 |
|---|---|---|---|---|---|---|---|---|
stewartsmith/bzr | bzrlib/repofmt/knitpack_repo.py | Python | gpl-2.0 | 46,938 | 0.002322 | # Copyright (C) 2007-2011 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distribute... | action = None
# for tests
self._reconcile_does_inventory_gc = True
self._reconcile_fixes_text_parents = True
self._reconcile_backsup_inventory = False
def _get_source(self, to_format):
if to_format.network_name() == self._format.network_name():
return KnitPackStr... | packs, extension, revs, pb):
packer = KnitReconcilePacker(collection, packs, extension, revs)
return packer.pack(pb)
class RepositoryFormatKnitPack1(RepositoryFormatPack):
"""A no-subtrees parameterized Pack repository.
This format was introduced in 0.92.
"""
repository_class = KnitP... |
mahak/cinder | cinder/tests/unit/volume/drivers/dell_emc/powermax/test_powermax_performance.py | Python | apache-2.0 | 18,376 | 0 | # Copyright (c) 2020 Dell Inc. or its subsidiaries.
# 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... | on())
driver = iscsi.PowerMaxISCSIDriver(
configuration=self. | reference_cinder_conf)
self.driver = driver
self.common = self.driver.common
self.performance = self.driver.performance
self.rest = self.common.rest
def test_set_performance_configuration(self):
"""Test set_performance_configuration diagnostic & real time."""
... |
openmicroscopy/webemdb | urls.py | Python | gpl-2.0 | 4,726 | 0.026449 | from django.conf.urls.defaults import *
from django.views.static import serve
from omeroweb.webemdb import views
import os
urlpatterns = patterns('',
url( r'^$', views.index, name='webemdb_index' ),
url( r'^logout/$', views.logout, name='webemdb_logout' ),
url( r'^loggedout/$', views.loggedout, name='webe... | ,
# page for OpenAstex Viewer. Project name and bit mask fileId
url( r'^oa_viewer/file/(?P<fileId>[0-9]+)/$', views.oa_viewer, name='webemdb_oa_viewer' ),
url( r'^viewport/(?P<imageId>[0-9]+)/$', views.viewport, name='webemdb_viewport' ),
# view the associated data for an entry
url( r... | tasetId>[0-9]+)/$', views.dataset, name='webemdb_dataset' ),
url( r'^image/(?P<imageId>[0-9]+)/$', views.image, name='webemdb_image' ),
url( r'^projections-imageId/(?P<imageId>[0-9]+)/$', views.mapmodel, name='webemdb_mapmodel' ), # uses OMERO Image-Id
url( r'^projections/(?P<entryId>[0-9]+)/$', views.m... |
DayGitH/Python-Challenges | DailyProgrammer/DP20151228A.py | Python | mit | 2,377 | 0 | """
[2015-12-28] Challenge #247 [Easy] Secret Santa
https://www.reddit.com/r/dailyprogrammer/comments/3yiy2d/20151228_challenge_247_easy_secret_santa/
| # Description
Every December my friends do a "Secret Santa" - the traditional gift exchange
where everybody is randomly assigned to give a gift to a frie | nd. To make
things exciting, the matching is all random (you cannot pick your gift
recipient) and nobody knows who got assigned to who until the day when the
gifts are exchanged - hence, the "secret" in the name.
Since we're a big group with many couples and families, often a husband gets
his wife as secret santa (or v... |
sevazhidkov/leonard | modules/menu.py | Python | mit | 2,095 | 0.000488 | import random
import telegram
MENU = [[('handler', 'Venues ☕', 'foursquare-location-choice'),
('handler', 'Weather 🌤', 'weather-show'),
('handler', 'News 📰', 'news-get-entry')],
[('handler', 'Vinci 🌇', 'vinci-upload-image'),
('handler', 'Get Uber 🚘', 'uber-choose-location'),
... | bot.telegram.send_message(message.u_id, phrase or random.choice(GREETING_PHRASES),
reply_markup=reply_markup)
def main_menu_callback(query, bot):
query.message.moved = True
bot.call_handler(query.message, ' | main-menu')
def get_keyboard():
keyboard = []
for line in MENU:
subkeyboard = []
for row in line:
if row[0] == 'handler':
subkeyboard.append(row[1])
if subkeyboard:
keyboard.append(subkeyboard)
return keyboard
|
infinyte/oppia | extensions/interactions/base.py | Python | apache-2.0 | 9,346 | 0 | # coding: utf-8
#
# Copyright 2014 The Oppia 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 requi... | , self.id, 'validator.js')))
def to_dict(self):
"""Gets a dict representing this interaction. Only default values are
provided.
| """
result = {
'id': self.id,
'name': self.name,
'description': self.description,
'display_mode': self.display_mode,
'is_terminal': self.is_terminal,
'customization_arg_specs': [{
'name': ca_spec.name,
... |
majgis/majgis | experiments/iterateArcMapDocsByFolder.py | Python | apache-2.0 | 2,315 | 0.011231 | # Copyright 2012 majgis Contributors
#
# Individuals comprising majgis Contributors are identified in
# the NOTICE file found in the root directory of this project.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# Y... | r\Server\biodiversity']
searchPattern = '*.mxd'
ignores = ['Overlap']
tempMsg = "{0:>90} -> {1}"
newMsg = "TABLE: {0} FIELD: {1}"
mxdSuffix = ".mxd"
msdSuffix = ".msd"
for folder in folders:
mxdPaths = glob(os.path.join(folder, searchPattern))
for mxdPath in mxdPaths:
mxd = mapping.M... |
for lyr in lyrs:
lyre = mxde[lyr.name]
joinTable = lyre.joinedTableName
joinField = lyre.symbologyShortFieldName
if joinTable:
newName = newMsg.format(joinTable, joinField)
else:
... |
danielfreeman11/convex-nets | LaunchScripts/ParseScript.py | Python | mit | 743 | 0.026918 | import os
import numpy as np
data = []
for f in os.listdir("."):
if len(f.split("."))==3 and f.split(".")[1]== | 'o38675' and int(f.split(".")[2])<1000:
with open(f) as file:
lines = file.readlines()
if len(lines) > 2 and len(lines) < 7:
data.append([float(p) for p in [lines[0].split(" ")[1], lines[1].split( | " ")[1], lines[3], lines[4]]])
#print data
#for d in data:
# print str(d[0]) + "\t" + str(d[1]) + "\t" + str(d[2]) + "\t" + str(d[3])
dictcheck = []
mydict = {}
for d in data:
if d[0] not in dictcheck:
dictcheck.append(d[0])
mydict[d[0]] = []
for d in data:
mydict[d[0]].append(d[1])
for d in dictcheck:
p... |
olemb/mido | mido/messages/strings.py | Python | mit | 1,606 | 0 | from .specs import SPEC_BY_TYPE, make_msgdict
def msg2str(msg, include_time=True):
type_ = msg['type']
spec = SPEC_BY_TYPE[type_]
words = [type_]
for name in spec['value_names']:
value = msg[name]
if name == 'data':
value = '({})'.format(','.join(str(byte) for byte in va... | type_ = words[0]
args = words[1:]
msg = {}
for arg in args:
name, value = arg.split('=', 1)
if name == 'time':
value = _parse_time(value)
elif name == 'data':
value = _parse_data(value)
else:
| value = int(value)
msg[name] = value
return make_msgdict(type_, msg)
|
nickfrostatx/bt-demo | mktorrent.py | Python | mit | 785 | 0 | import bencode
import hashlib
import math
import os
import sys
def main(argv):
announce = argv[1]
filename = argv[2]
piece_length = 2 ** int(argv[3])
length = os.path.getsize(filename)
data = {
'announce': announce.encode('ascii'),
'info': {
'length': length,
... | code('ascii'),
'piece length': piece_length,
'pieces': b'',
},
}
with open(filename, 'rb') as f:
piece = f.read(piece_length)
while len(piece) > 0:
data['info']['pieces'] += hashlib.sha1(piece).digest()
piece = f.read(piece_length)
be... | )
|
ibc/MediaSoup | worker/deps/gyp/test/win/gyptest-link-aslr.py | Python | isc | 894 | 0.011186 | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Make sure aslr setting is extracted properly.
"""
import TestGyp
import sys
|
if sys.platform == 'win32':
test = TestGyp.TestGyp(formats=['msvs', 'ninja'])
CHDIR = 'link | er-flags'
test.run_gyp('aslr.gyp', chdir=CHDIR)
test.build('aslr.gyp', test.ALL, chdir=CHDIR)
def HasDynamicBase(exe):
full_path = test.built_file_path(exe, chdir=CHDIR)
output = test.run_dumpbin('/headers', full_path)
return ' Dynamic base' in output
# Default is to be on.
if ... |
AnotherKamila/distributed-algorithms-emulator | examples/test.py | Python | mit | 424 | 0.007075 | """Test | s if it "compiles" (except that it doesn't).
Also: trivial usage example.
"""
from da import Node, Network
import topo
class MyNode(Node):
def run(self):
self.send(0, self.ID)
self.send(1, self.ID)
p, m = self.recv()
p, m = self.recv()
self.log('terminating', m, p)
def ru... | |
spseol/CzechFlaskDoc | Priklady/Dalsi/session.py | Python | gpl-2.0 | 831 | 0.00722 | from flask import | Flask, session, red | irect, url_for, escape, request
app = Flask(__name__)
app.secret_key = "Tajny klic"
@app.route('/')
def index():
if 'username' in session:
return "Logged in as %s <br><a href='logout'>Logout</a>" %escape(session['username'])
return 'You are not logged in <br><a href="login">Login</a>'
@app.route('/login... |
KarrLab/Karr-Lab-build-utils | karr_lab_build_utils/__init__.py | Python | mit | 227 | 0 | from ._version import | __version__
# :obj:`str`: version
# API
from .core import (CoverageType, Environment,
Bui | ldHelper, BuildHelperError,
TestResults, TestCaseResult, TestCaseResultType)
|
CLVsol/odoo_addons | clv_insured_ext/__init__.py | Python | agpl-3.0 | 1,546 | 0.010996 | # -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-T | oday Carlos Eduardo Vercelino - CLVsol #
# #
# This program is free software: you can redistribute it and/or | modify #
# it under the terms of the GNU Affero General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# ... |
lektor/lektor-archive | lektor/admin/modules/api.py | Python | bsd-3-clause | 9,265 | 0.000108 | import os
import posixpath
import click
from flask import Blueprint, jsonify, request, g, current_app
from lektor.utils import is_valid_id
from lektor.admin.utils import eventstream
from lektor.publisher import publish, PublishError
from lektor.environment import PRIMARY_ALT
bp = Blueprint('api', __name__, url_pref... | fig.primary_alternative
if primary_alt is not None:
for alt in tree_item.alts.itervalues():
alt_cfg = db.config.get_alternative(alt.id)
| alts.append({
'alt': alt.id,
'is_primary': alt.id == PRIMARY_ALT,
'primary_overlay': alt.id == primary_alt,
'name_i18n': alt_cfg['name'],
'exists': alt.exists,
})
return jsonify(
id=tree_item.id,
path=tre... |
mnubo/kubernetes-py | kubernetes_py/models/v1/ContainerStatus.py | Python | apache-2.0 | 5,514 | 0.003083 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE.md', which is part of this source code package.
#
from kubernetes_py.utils import is_valid_string, filter_model
from kubernetes_py.models.v1.ContainerState import ContainerState
class Contai... | t = count
# ------------------------------------------------------------------------------------- image
@property
def image(self):
return self._image
@image.setter
def image(self, image=None):
if not is_valid_string(image):
raise SyntaxError("ContainerStatus: image: [ ... | -------------------------- imageID
@property
def image_id(self):
return self._image_id
@image_id.setter
def image_id(self, iid=None):
if not is_valid_string(iid):
raise SyntaxError("ContainerStatus: image_id: [ {0} ] is invalid".format(iid))
self._image_id = iid
... |
pickleshb/PyInvoice | invoice/migrations/0008_auto_20170908_1914.py | Python | mit | 760 | 0.002632 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-09-08 19:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('invoice', '0007_profil | e_invoice_logo'),
]
operations = [
migrations.AddField(
model_name='invoiceitem',
name='quantity',
field=models.DecimalField(decimal_places=1, default=1, max_digits=5),
preserve_default=False,
),
migrations.AddField(
model_name... | default=0, max_digits=10),
preserve_default=False,
),
]
|
lot9s/pathfinder-rpg-utils | data-mining/bestiary/indexer.py | Python | mit | 2,230 | 0.00583 | '''This module contains a script and functions for obtaining a list
of URLs from d20pfsrd.com, an unofficial System Reference Document
(SRD) for the Pathfinder RPG.
This list is meant to act as an index of creatures sorted by
Challenge Rating (CR).
'''
from lxml.html import parse
__all__ = ['create_index_file', ... |
:param file_name: the name of the output file
'''
# open input files
hub_file = open('LINKS_SPECIAL_HUB.txt', 'r')
links_file = open('LINKS_SPECIAL.txt', 'r')
# open output files
out = open(file_name, 'w')
# get links from hub pages
for line in hub_file:
html_tree = parse(li... | t()
link_table =
doc.cssselect('.sites-tile-name-content-1 td:nth-child(1) a')
# write links to output file
for link in link_table:
out.write(link.get('href') + '\n')
# get links from special pages
for line in links_file:
out.write(line)
# clean up
... |
parente/bof | bof/__init__.py | Python | bsd-2-clause | 897 | 0 | # Copyright (c) Peter Parente
# Distributed under the terms of the BSD 2-Clause License.
import os
from flask import Flask
from flask_sslify import SSLify
from .model import db
from .auth import oauth
fr | om .ui import ui_bp
from .api import api_bp
app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY', os.urandom(24))
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('SQLALCHEMY_DATABASE_URI',
'sqlite:////tmp/... | _KEY')
app.config['GITHUB_CONSUMER_SECRET'] = os.getenv('GITHUB_CONSUMER_SECRET')
app.register_blueprint(api_bp)
app.register_blueprint(ui_bp)
db.init_app(app)
oauth.init_app(app)
if 'VCAP_SERVICES' in os.environ:
SSLify(app)
|
MachineLearningControl/OpenMLC-Python | MLC/mlc_parameters/mlc_parameters.py | Python | gpl-3.0 | 3,102 | 0.001613 | # -*- coding: utf-8 -*-
# MLC (Machine Learning Control): A genetic algorithm library to solve chaotic problems
# Copyright (C) 2015-2017, Thomas Duriez (thomas.duriez@gmail.com)
# Copyright (C) 2015, Adrian Durán (adrianmdu@gmail.com)
# Copyright (C) 2015-2017, Ezequiel Torres Feyuk (ezequiel.torresfeyuk@gmail.com)
# ... | for option in config_parser.options(section):
config_dict[secti | on][option] = config_parser.get(section, option)
return config_dict
@classmethod
def from_dictionary(cls, config_dict, config_type=None):
config = cls() if config_type is None else config_type()
for section, options in config_dict.iteritems():
config.add_section(section)
... |
openstreams/wflow | wflow/wflow_w3ra_new.py | Python | gpl-3.0 | 44,871 | 0.002429 | #!/usr/bin/python
"""
Definition of the wflow_W3RA model.
---------------------------------------
The model is modified from the Australian Water Resources Assessment
Landscape (AWRA-L) model version 0.5
W3RA is documented in
van Dijk et al. (2013), Water Resour. Res., 49, 2729-2746, doi:10.1002/wrcr.20251
URL: http:/... | e model
are saved to disk as pcraster maps. Use resume() to re-read them
This function is required.
"""
self.logger.info("Saving initial conditions...")
#: It is advised to use the wf_suspend() function
#: here whi | ch will suspend the variables that are given by stateVariables
#: function.
self.wf_suspend(self.SaveDir + "/outstate/")
def initial(self):
"""
*Required*
Initial part of the model, executed only once. It reads all static model
information (parameters) and sets-up the vari... |
jgsogo/django-generic-filters | demo/demoproject/urls.py | Python | bsd-3-clause | 312 | 0 | from django.conf.urls import patterns, include, url
from django.views.generic i | mport TemplateView
home = TemplateView.as_view(template_name='home.html')
urlpatterns = patterns(
'',
url(r'^filter/', include('demoproject.filter.urls')),
# An informative homepage.
url | (r'', home, name='home')
)
|
samdowd/drumm-farm | drumm_env/lib/python2.7/site-packages/phonenumbers/geodata/data20.py | Python | mit | 919,262 | 0.021584 | """Per-prefix data, mapping each prefix to a dict of locale:name.
Auto-generated file, do not edit by hand.
"""
from ..util import u
# Copyright (C) 2011-2017 The Libphonenumber Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Licens... | {'en': 'Xining, Qinghai', 'zh': u('\u9752\u6d77\u7701\u897f\u5b81\u5e02')},
'861839711':{'en': 'Xining, Qinghai', 'zh': u('\u9752\u6d77\u7701\u897f\u5b81\u5e02')},
'861831543':{'en': 'Bi | nzhou, Shandong', 'zh': u('\u5c71\u4e1c\u7701\u6ee8\u5dde\u5e02')},
'861831542':{'en': 'Qingdao, Shandong', 'zh': u('\u5c71\u4e1c\u7701\u9752\u5c9b\u5e02')},
'861831541':{'en': 'Jinan, Shandong', 'zh': u('\u5c71\u4e1c\u7701\u6d4e\u5357\u5e02')},
'861831540':{'en': 'Heze, Shandong', 'zh': u('\u5c71\u4e1c\u7701\u83cf\... |
google/google-ctf | third_party/edk2/AppPkg/Applications/Python/Python-2.7.2/Demo/sockets/unixclient.py | Python | apache-2.0 | 244 | 0 | # Echo client demo using Unix sockets
# Piet van Oostrum
from | socket import *
FI | LE = 'unix-socket'
s = socket(AF_UNIX, SOCK_STREAM)
s.connect(FILE)
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
|
lnls-sirius/dev-packages | siriuspy/siriuspy/pwrsupply/bsmp/__init__.py | Python | gpl-3.0 | 48 | 0 | """Subpackage wit | h PS-specifi | c BSMP objects."""
|
ProjectKitchen/BrainwashingMachine | src/MousePlayer/src/utils.py | Python | gpl-3.0 | 1,331 | 0.001503 | import sys
PY3 = sys.version_info >= (3,)
if PY3:
xrange = range
bytes_type = bytes
if PY3:
unicode_type = str
basestring_type = str
else:
# The names unicode and basestring don't exist in py3 so silence flake8.
unicode_type = unicode # noqa
basestring_type = ba | sestring # noqa
_TO_UNICODE_TYPES = (unicode_type, type(None))
def to_unicode(value):
"""Converts a string argument to a unicode string.
If the argument is already a unicode string or None, it is returned
unchanged. Otherwise it must be a byte string and is decoded | as utf8.
"""
if isinstance(value, _TO_UNICODE_TYPES):
return value
if not isinstance(value, bytes):
raise TypeError(
"Expected bytes, unicode, or None; got %r" % type(value)
)
return value.decode("utf-8")
def _safe_unicode(s):
try:
return to_unicode(s)
... |
synbiochem/PathwayGenie | pathway_genie/pathway.py | Python | mit | 2,745 | 0 | '''
PathwayGenie (c) University of Manchester 2017
PathwayGenie is licensed under the MIT License.
To view a copy of this license, visit <http://opensource.org/licenses/MIT/>.
@author: neilswainston
'''
from threading import Thread
import json
import time
from ice.ice import IceThread
from parts_genie.parts import... | eld 'data:' + self.__get_response(job_id) + '\n\n | '
yield 'data:' + self.__get_response(job_id) + '\n\n'
return _check_progress(job_id)
def cancel(self, job_id):
'''Cancels job.'''
self.__threads[job_id].cancel()
return job_id
def event_fired(self, event):
'''Responds to event being fired.'''
self... |
kleetus/bitcoin | qa/rpc-tests/invalidblockrequest.py | Python | mit | 4,242 | 0.003772 | #!/usr/bin/env python2
# Copyright (c) 2015 The Bitcoin Core developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from... | getbestblockhash() + "L", 0)
self.block_time = int(time.time())+1
'''
Create a new block with | an anyone-can-spend coinbase
'''
height = 1
block = create_block(self.tip, create_coinbase(height), self.block_time)
self.block_time += 1
block.solve()
# Save the coinbase for later
self.block1 = block
self.tip = block.sha256
height += 1
yi... |
elin-moco/ffclub | ffclub/product/migrations/0005_auto__add_field_product_type.py | Python | bsd-3-clause | 13,115 | 0.008082 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Product.type'
db.add_column('product_product', 'type',
self.gf('django... | nts': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'activities'", 'symmetrical': 'False', 'through': "orm['event.Participation']", 'to': "orm['auth.User']"}),
'slug': ('django.db.models.fields.CharField', [], {'default': "''", 'unique': 'True', 'max_length': '255', 'blank': 'Tru... | 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'url': ('django.db.models.fields.URLField', [], {'default': "''", 'max_length': '200', 'blank': 'True'}),
'vote_time': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'})
},
... |
JamesJGarner/cms | src/cms/models/base.py | Python | bsd-3-clause | 7,140 | 0.017367 | """Abstract base models used by the page management application."""
from django.db import models
from django.shortcuts import render
from cms import externals
from cms.models.managers import OnlineBaseManager, PublishedBaseManager, SearchMetaBaseManager, PageBaseManager
class PublishedBase(models.Model):
"... | ser_title = models.CharField(
max_length = 1000,
blank = True,
help_text = (
"The heading to use in the user's web browser. "
"Leave blank to use the page title. "
"Search engines pay particular attention to this attribute."
)
)
meta_keywo... | d list of keywords for this page. Use this to specify common mis-spellings "
"or alternative versions of important words in this page."
),
)
meta_description = models.TextField(
"description",
blank = True,
help_text = "A brief description of the contents of this pag... |
donbright/piliko | experiment/fiborec.py | Python | bsd-3-clause | 1,405 | 0.054804 | from fractions import Fraction as f
import sys
# draw points of squares->tiling a rectangle
# size of squares = fibonacci seq
def sqr(x): return x*x
def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y)
def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y)
def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y)
xs,ys=[],[ | ]
depth=50
class | Cursor:
direction=[0,1]
position=[0,0]
def forward(self,n):
self.position[0]=self.position[0]+self.direction[0]*n
self.position[1]=self.position[1]+self.direction[1]*n
def turnleft(self):
# North->West->South->East->North
# 0,1 -> -1,0 -> 0,-1 -> 1,0 -> 0,1
tmp=self.direction[0]
self.direction[0]=-1*se... |
ProgramFan/bentoo | bentoo/common/case.py | Python | mit | 3,545 | 0.000564 | # coding: utf-8
from __future__ import division, unicode_literals, print_function
class ScalingCaseMaker(object):
'''A test vector generator for scaling tests'''
def __init__(self, ref_mem_mb, ref_nnodes, min_mem, max_mem):
self.min_mem = min_mem
self.max_mem = max_mem
self.ref_mem =... | .., (-2, 512)],
[(-3, 4), (-3, 8), ..., (-3, 512)]]
'''
cases = []
mem = self.ref_mem
nnodes = self.ref_nnodes
mpn = old_div(mem, nnodes)
while mpn | <= self.max_mpn:
ratio += 1
mpn *= 2
ration -= 1
mpn = max_mpn
ratio = 0
while mpn >= min_mpn:
cases.extend((ratio, min_nodes * 2**x)
for x in range(0, max_node_multipler, steping))
ratio = ratio - steping
... |
sassoftware/bob | bob/util.py | Python | apache-2.0 | 11,894 | 0.001009 | #
# Copyright (c) SAS Institute 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 w... | build. Call I{get} to
add a new context to the build config to get the name of a context
with those parameters.
'''
# R0903 - Too few public methods
#pylint: disable-msg=R0903
def __init__(self, con | fig):
self.contexts = set()
self.config = config
def get(self, build_flavor, search_flavors, macros):
'''
Create a context in the local buildcfg out of the specified build
and search flavors, and macros.
'''
# Calculate a unique context name based on the spe... |
asedunov/intellij-community | python/testData/inspections/suppress/suppressedUnusedLocal.py | Python | apache-2.0 | 61 | 0.016393 | de | f foo():
#noinspection PyUnusedLocal
status = | None
|
manqala/erpnext | erpnext/schools/doctype/school_house/test_school_house.py | Python | gpl-3.0 | 231 | 0.008658 | # -*- c | oding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
from __future__ import unicode_literals
i | mport frappe
import unittest
class TestSchoolHouse(unittest.TestCase):
pass
|
1001genomes/AraGWAS | aragwas_server/gwasdb/migrations/0008_remove_study_easygwas_link.py | Python | mit | 396 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1. | 11b1 on 2017-06-27 16:09
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
| ('gwasdb', '0007_study_n_hits_thr'),
]
operations = [
migrations.RemoveField(
model_name='study',
name='easygwas_link',
),
]
|
paltman/idios | idios/middleware.py | Python | bsd-3-clause | 2,543 | 0.000786 | import re
from django import forms
f | rom django.conf import settings
from django.db import models
from django.template import RequestContext
from django.shortcuts import render_to_response, redirect
from django.views.decorators.csrf import csrf_protect
from idios.utils import get_profile_model
class AdditionalInfoMiddleware(object):
def proces... | r"^%s" % settings.MEDIA_URL,
r"^%s" % settings.STATIC_URL,
r"^/__debug__",
r"^/account", # @@@ hack for now
]
for exemption in exemptions:
if re.match(exemption, request.path):
return None
kickstart = request.session.get("idios_ad... |
gewaltig/cython-neuron | pynest/nest/tests/test_errors.py | Python | gpl-2.0 | 3,727 | 0.009928 | #! /usr/bin/env python
#
# test_errors.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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
... | t_UnknownModel(self):
"""Unknown model name"""
nest.ResetKernel()
try:
nest.Create(-1)
self.fail( | 'an error should have risen!') # should not be reached
except nest.NESTError:
info = sys.exc_info()[1]
if not "UnknownModelName" in info.__str__():
self.fail('wrong error message')
# another error has been thrown, this is wrong
except:
... |
karthik-sethuraman/ONFOpenTransport | RI/flask_server/tapi_server/models/tapi_connectivity_createconnectivityservice_input.py | Python | apache-2.0 | 8,650 | 0.002081 | # coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from tapi_server.models.base_model_ import Model
from tapi_server.models.tapi_connectivity_connectivity_constraint import TapiConnectivityConnectivityConstraint # noqa... | ogy_constraint of this TapiConnectivityCreateconnectivityserviceInput.
:param topology_constraint: The topology_constraint of this TapiConnectivityCreateconnectivityserviceInput.
:type topology_constraint: TapiPathComputationTopolo | gyConstraint
"""
self._topology_constraint = topology_constraint
@property
def end_point(self):
"""Gets the end_point of this TapiConnectivityCreateconnectivityserviceInput.
none # noqa: E501
:return: The end_point of this TapiConnectivityCreateconnectivityserviceInp... |
gregarmer/trunserver | trunserv/autoreload.py | Python | mit | 5,239 | 0.002291 | # Autoreloading launcher.
# Borrowed from Peter Hunt and the CherryPy project (http://www.cherrypy.org).
# Some taken from Ian Bicking's Paste (http://pythonpaste.org/).
# Adjustments made by Michael Elsdoerfer (michael@elsdoerfer.com).
#
# Portions copyright (c) 2004, CherryPy Team (team@cherrypy.org)
# All rights res... | _mtimes = {}
return True
return False
def reloader_thread(softexit=False):
"""If ``soft_exit`` is True, we use sys.exit(); otherwise ``os_exit``
will be used to end the process.
"""
while RUN_RELOADER:
if code_changed():
# force reload
if softexi... | sys.exit(3)
else:
os._exit(3)
time.sleep(1)
def restart_with_reloader():
while True:
args = [sys.executable] + sys.argv
if sys.platform == "win32":
args = ['"%s"' % arg for arg in args]
new_environ = os.environ.copy()
new_environ[... |
kg-bot/SupyBot | plugins/RequestBot/plugin.py | Python | gpl-3.0 | 11,545 | 0.005717 | ###
# Copyright (c) 2015, KG-Bot
# 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 t... | tionalization
_ = PluginInternationalization('RequestBot')
except ImportError:
# Placeholder that allows to run the plugin on a bot
# without the i18n module
_ = lambda x:x
class RequestBot(callbacks.Plugin):
"""Plugin is used to automate bot requests for some channel."""
threaded = True
... | elf.dailyChecksInterval = conf.supybot.plugins.RequestBot.dailyCheckInterval()
self.stopDailyCheck = conf.supybot.plugins.RequestBot.stopDailyCheck()
self.numberOfChecks = conf.supybot.plugins.RequestBot.numberOfChecks()
self.numberOfValidUsers = conf.supybot.plugins.RequestBot.numberOfValidUser... |
endthestart/safarido | safarido/todos/migrations/0001_initial.py | Python | mit | 3,046 | 0.007879 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'TodoList'
db.create_table(u'todos_todolist', (
(u'id', self.gf('django.db.models... | =50)),
))
db.send_create_signal(u'todos', ['TodoList'])
# Adding model 'Todo'
db.create_table(u'todos_todo', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('create | d_on', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
('modified_on', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
('list', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['todos.TodoList'])),
('title', ... |
mcohoon/api-samples | batching/permissions.py | Python | apache-2.0 | 2,389 | 0.012139 | """A simple example of Google Analytics batched user permissions."""
import json
from apiclient.errors import HttpError
from apiclient.http import BatchHttpRequest
def call_back(request_id, response, exception):
"""Handle batched request responses."""
print request_id
if exception is not None:
if isinstance(... | view_id = view.get('id')
# Construct the Profile User Link.
l | ink = analytics.management().profileUserLinks().insert(
accountId=account_id,
webPropertyId=property_id,
profileId=view_id,
body={
'permissions': {
'local': permissions
},
'userRef': {
... |
google-research/google-research | poem/core/pipeline_utils.py | Python | apache-2.0 | 18,823 | 0.004781 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | ,
num_shards=1,
shard_index=None,
| common_module=common,
dataset_class=tf.data.TFRecordDataset,
input_example_parser_creator=None,
seed=None):
"""Reads data from dataset table.
IMPORTANT: We assume that 2D keypoints from the input h... |
maclandrol/profileNJ | profileNJ/TreeLib/ClusterUtils.py | Python | gpl-3.0 | 11,942 | 0.000586 | # This file is part of profileNJ
#
# Date: 02/2014
# ClusterUtils contain implementation of nj and upgma clustering algo, and
# required methods
__author__ = "Emmanuel Noutahi"
from TreeClass import TreeClass
import os
import numpy as np
from StringIO import StringIO
import random
try:
from lxml import etree
... | in range(nj_depth):
Q_matrix = calculate_Q_matrix(matrice)
index_1, index_2 = find_smallest_index(Q_matrix)
smallest_index = (index_1, in | dex_2)
row_order = condense_node_order(
matrice, smallest_index, node_order, method='nj')
matrice = condense_matrix(matrice, smallest_index, method='nj')
tree = node_order[smallest_index[1]]
return tree, matrice, smallest_index
def UPGMA_cluster(matrice, node_order, upgma_depth... |
raulhigueras/LolaVA | config/profile.py | Python | mit | 1,553 | 0.051613 | # encoding=utf8
import | pickle
from speech import output
fro | m speech import input
def change_config():
opciones = get_config()
output.say("A continuacion voy a cambiar la configuración:")
output.say("¿Cual es tu nombre?:")
opciones["nombre"] = input.ask()
output.say("Cual es tu periodico favorito?")
opciones["periodico"] = input.ask()
output.say("En que ciu... |
npinto/sthor | sthor/operation/lpool.py | Python | bsd-3-clause | 2,793 | 0.000716 | """
Local Pooling Operation.
Easy-to-understand (but slow) naive numpy implementation.
"""
# Authors: Nicolas Pinto <nicolas.pinto@gmail.com>
#
# License: Proprietary
__all__ = ['LPoolScipyNaive']
# -- Imports
import numpy as np
from pythor3.operation.common.lsum import lsum
from pythor3.operation.lpool_.plugins im... | arr_in.shape[:2]
tmp_h = in_h - ker_shape[0] + 1
tmp_w = in_w - ker_shap | e[1] + 1
if arr_in.ndim == 3:
in_d = arr_in.shape[2]
tmp_d = in_d
tmp_shape = tmp_h, tmp_w, tmp_d
else:
tmp_shape = tmp_h, tmp_w
return tmp_shape
def run(self):
"""XXX: doctring"""
tmp_shape = self._get_tmp_shape(self.arr_in, ... |
ic-labs/django-icekit | icekit/plugins/location/content_plugins.py | Python | mit | 391 | 0 | """
Definitio | n of the plugin.
"""
from django.utils.translation import ugettext_lazy as _
from fluent_contents.extensions import ContentPlugin, plugin_pool
from . import models
@plugin_pool.register
class LocationPlugin(ContentPlugin):
model = models.LocationItem
category = _('Assets')
render_template = 'icekit/plugi... | raw_id_fields = ['location', ]
|
Impactstory/total-impact-webapp | totalimpactwebapp/countries_info.py | Python | mit | 322,120 | 0.001021 | countries_info_list = [
{
"name": {
"common": "Afghanistan",
"official": "Islamic Republic of Afghanistan",
"native": {
"common": "\u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627\u0646",
"official": "\u062f \u0627\u0641\u063a\u0627\u0646\u... | "spa": "Albania"
},
"latlng": [41, 20],
"demonym": "Albanian",
"borders": ["MNE", "GRC", "MKD", "KOS"],
"area": 28748
},
{
"name": {
"common": "Algeria",
"official": "People's Democratic Republic of Algeria",
"native": {
... | u062c\u0645\u0647\u0648\u0631\u064a\u0629 \u0627\u0644\u062f\u064a\u0645\u0642\u0631\u0627\u0637\u064a\u0629 \u0627\u0644\u0634\u0639\u0628\u064a\u0629 \u0627\u0644\u062c\u0632\u0627\u0626\u0631\u064a\u0629"
}
},
"tld": [".dz", "\u0627\u0644\u062c\u0632\u0627\u0626\u0631."],
"cca2": ... |
arteria/django-hijack | hijack/tests/test_settings.py | Python | mit | 3,291 | 0 | """Settings that need to be set in order to run the tests."""
import os
DEBUG = True
SITE_ID = 1
APP_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
DATABASES = {
'default': {'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:', }
}
LOGIN_REDIRECT_URL = '/hello'
HIJA... | auth.middleware.AuthenticationMiddleware',
'django.contrib.m | essages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'hijack.middleware.HijackRemoteUserMiddleware',
)
MIDDLEWARE_CLASSES = MIDDLEWARE
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
... |
chengzhoukun/LeetCode | 1117. Building H2O/solution.py | Python | lgpl-3.0 | 742 | 0 | from collections import deque
class H2O:
def __init__(self):
self.h_queue = deque()
self.o_queue = deque()
def hydrogen(self, releaseHydrogen: "Callab | le[[], None]") -> None:
# releaseHydrogen() outputs "H". Do not change or remove this line.
self.h_queue.append(releaseHydrogen)
self.build() |
def oxygen(self, releaseOxygen: "Callable[[], None]") -> None:
# releaseOxygen() outputs "O". Do not change or remove this line.
self.o_queue.append(releaseOxygen)
self.build()
def build(self) -> None:
if len(self.h_queue) >= 2 and len(self.o_queue) >= 1:
self.h_q... |
wlanslovenija/django-postgres | postgres/fields/composite.py | Python | bsd-3-clause | 1,779 | 0.001124 | from django.db.models import fields
from django.db import connection
from django.dispatch import receiver, Signal
from psycopg2.extras import register_composite
from psycopg2.extensions import register_adapter, adapt, AsIs
from psycopg2 import ProgrammingError
_missing_types = {}
class CompositeMeta(type):
def... | register_adapter(cls.python_type, adapt_composite)
class CompositeField(fields.Field):
# We should also incorporate the stuff from SubFieldBase, so
# we convert any iterable of the correct arity, and coercable types
# into the python_type.
__metaclass__ = CompositeMeta
"""
A handy bas... | ef register_composite_late(sender, db_type, **kwargs):
_missing_types.pop(db_type).register_composite()
|
CityGenerator/Megacosm-Generator | tests/test_govt.py | Python | gpl-2.0 | 2,530 | 0.007115 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"Fully test this module's functionality through the use of fixtures."
from megacosm.generators import Govt, Country, City
import unittest2 as unittest
import fakeredis
import fixtures
from config import TestConfiguration
class TestGovt(unittest.TestCase):
def setU... | a.import_fixtures(self)
self.redis.lpush('npc_race','gnome')
def tearDown(self):
self.redis.flushall()
def test_random_govt(self):
""" "" | "
govt = Govt(self.redis)
self.assertEqual('far longer than should be allowed', govt.age['name'])
def test_static_body(self):
""" """
country=Country(self.redis)
govt = Govt(self.redis,{'body':country})
self.assertIn('Central Afkil', str(govt.body))
self.asse... |
praekelt/molo | molo/core/scripts/tests/test_cli.py | Python | bsd-2-clause | 4,820 | 0 | from unittest import TestCase
import pkg_resources
from mock import patch
from click import UsageError
from click.testing import CliRunner
class TestCli(TestCase):
@patch('molo.core.cookiecutter.cookiecutter')
def test_scaffold(self, mock_cookiecutter):
from molo.core.scripts import cli
pac... | .core.scripts import cli
package = pkg_resources.get_distribution('molo.core')
runner = CliRunner()
runner.invoke(cli.scaffold, ['foo', 'bar'])
[call] = mock_cookiecutter.call_args_list
args, kwargs = call
| self.assertTrue(kwargs['extra_context'].pop('secret_key'))
self.assertEqual(kwargs, {
'no_input': True,
'extra_context': {
'app_name': 'foo',
'directory': 'bar',
'author': 'Praekelt Foundation',
'author_email': 'dev@pra... |
danlrobertson/servo | components/style/gecko/regen_atoms.py | Python | mpl-2.0 | 6,961 | 0.00316 | #!/usr/bin/env python
# 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 https://mozilla.org/MPL/2.0/.
import re
import os
import sys
from io import BytesIO
GECKO_DIR = os.path.dirname(__file__.rep... |
# Matches lines like `GK_ATOM(foo, "foo", 0x12345678, true, nsStaticAtom, PseudoElementAtom)`.
PATTERN = re.compile('^GK_ATOM\(([^,]*),[^"]*"([^"]*)",\s*(0x[0-9a-f]+),\s*[^,]*,\s*([^,]*),\s*([^)]*)\)',
re.MULTILINE)
FILE = "include/nsGkAtomList.h"
| def map_atom(ident):
if ident in {"box", "loop", "match", "mod", "ref",
"self", "type", "use", "where", "in"}:
return ident + "_"
return ident
class Atom:
def __init__(self, ident, value, hash, ty, atom_type):
self.ident = "nsGkAtoms_{}".format(ident)
self.original... |
meyer-group/meyer-group.github.io | _legacy/scrape-pubs.py | Python | mit | 2,235 | 0.035794 | #!/usr/bin/python
import json, os, re, string, sys, traceback
from bs4 import BeautifulSoup
f = open('pubs-2017-12-27.html')
# f = open('blah.html')
content = f.read()
soup = BeautifulSoup(content, 'html.parser')
pubs = {
'selected': [],
'most-cited': [],
'selected-reviews': [],
'publications': []
}
def proces... | e.sub(r'\.$', '', pub['jour']).strip()
# links:
pub['links'] = map(lambda x: {'text': re.sub('\s+', ' ', x.get_text().strip()), 'href': x['href']}, p.find_all('a'))
except Exception as e:
print >> sys.stderr, e
print >> sys.stderr, p
print >> sys.stderr, traceback.format_exc()
raise e
return pub
for... | pubs:
for p in soup.find('div', {'id': g}).find_all('p'):
try:
if 'highlight' in p['class']:
print >> sys.stderr, 'ignoring ' + p.get_text()
continue
parsed = process(p)
pubs[g].append(parsed)
except KeyError as k:
# from ['class'], ignore.
pass
except Exception as e:
print >> sys.stde... |
dandersson/shortweb | swlib/dbinteraction.py | Python | gpl-2.0 | 12,341 | 0.001053 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import datetime
import random
import unittest
import dateutil.tz
import MySQLdb
import MySQLdb.cursors
import _mysql_exceptions
import basetranslate
import config
class ShortDBConn(object):
"""Connection to Short database.
Args:
data_table_name: name of... | ess_counter += 1
class TestSequence(unittest.TestCase):
def setUp(self):
c = config.ConfigItems(config_file='../shortweb.test.config')
| self.host = c.dbargs['host']
self.user = c.dbargs['user']
self.passwd = c.dbargs['passwd']
self.db = c.dbargs['db']
self.data_table_name = c.dbargs['data_table_name']
self.base_id_with_no_corresponding_db_entry = \
c.dbargs['base_id_with_no_corresponding_db_entr... |
HybridF5/nova | nova/tests/unit/scheduler/test_scheduler_utils.py | Python | apache-2.0 | 16,922 | 0.000414 | # Copyright (c) 2013 Rackspace Hosting
# 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 req... | properties_no_forced_host_no_force_node | (self):
sched_hints = {'hint': ['over-there']}
forced_host = None
forced_node = None
instance_type = objects.Flavor()
filt_props = scheduler_utils.build_filter_properties(sched_hints,
forced_host, forced_node, instance_type)
self.assertEqual(sched_hints, f... |
eReuse/DeviceHub | ereuse_devicehub/resources/device/component/settings.py | Python | agpl-3.0 | 1,594 | 0.002509 | from contextlib import suppress
from ereuse_devicehub.resources.device.benchmark_settings import BenchmarkHardDrive, BenchmarkProcessor, Benchmark
from ereuse_devicehub.resources.device.schema import Device
from ereuse_devicehub.resources.device.settings import DeviceSettings, DeviceSubSettings
class Component(Devic... | l_types['benchmark']['schema'] = union_of_benchmarks
return global_types
class ComponentSettings(DeviceSetti | ngs):
_schema = Component
resource_methods = []
item_methods = []
class ComponentSubSettings(DeviceSubSettings):
_schema = False
|
charettes/django-mutant | mutant/contrib/boolean/migrations/0002_update_field_defs_app_label.py | Python | mit | 820 | 0.003659 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import functools
from django.db import migrations
def _update_field_def_cts_app_label(from_app_label, to_app_label, apps, schema_editor):
cts = apps.get_model('contenttypes', 'contenttype').objects
model_n | ames = [
'booleanfielddefinition',
'nullbooleanfielddefinition',
]
cts.filter(
app_label=from_app_label, model__in=model_names
).update(app_label=to_app_label)
class Migration(migrations.Migration):
dependencies = [
('boolean', '0001_initial'),
]
operations = ... | _label, 'mutant', 'boolean'),
functools.partial(_update_field_def_cts_app_label, 'boolean', 'mutant'),
),
]
|
cpcloud/numexpr | numexpr/version.py | Python | mit | 855 | 0 | ###################################################################
# Numexpr - Fast numerical array expression evaluator for NumPy.
#
# License: MIT
# Author: See AUTHORS.txt
#
# See LICENSE.txt and | LICENSES/*.txt for details about co | pyright and
# rights to use.
####################################################################
version = '2.4.1'
release = False
if not release:
version += '.dev'
import os
svn_version_file = os.path.join(os.path.dirname(__file__),
'__svn_version__.py')
if os.p... |
kaiping/incubator-singa | examples/imagenet/densenet/convert.py | Python | apache-2.0 | 3,187 | 0.001255 | # 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... | t('nb_classes', default=1000, type=int)
args = parser.parse_args()
net = model.create_net(args.depth, args.nb_classes)
url = 'densenet%d' % args.depth
torch_ | dict = model_zoo.load_url(model_urls[url])
params = {'SINGA_VERSION': 1101}
# resolve dict keys name mismatch problem
print(len(net.param_names()), len(torch_dict.keys()))
for pname, pval, torch_name in\
zip(net.param_names(), net.param_values(), torch_dict.keys()):
#torch_name = rename... |
jamesthechamp/zamboni | mkt/site/models.py | Python | bsd-3-clause | 10,570 | 0 | import contextlib
import threading
from django.db import models, transaction
from django.utils import translation
import multidb.pinning
_locals = threading.local()
class TransformQuerySet(models.query.QuerySet):
def __init__(self, *args, **kwargs):
super(TransformQuerySet, self).__init__(*args, **kw... | results)
return iter(results)
return result_iter
def pop_transforms(self):
qs = self._clone()
transforms = qs._transform_fns
qs._transform_fns = []
return transforms, qs
def no_transforms(self):
return | self.pop_transforms()[1]
def only_translations(self):
"""Remove all transforms except translations."""
from mkt.translations import transformer
# Add an extra select so these are cached separately.
return (self.no_transforms().extra(select={'_only_trans': 1})
.trans... |
mojodna/debian-mapnik | plugins/input/geos/build.py | Python | lgpl-2.1 | 1,730 | 0.001734 | #
# This file is part of Mapnik (c++ mapping toolkit)
#
# Copyright (C) 2007 Artem Pavlenko, Jean-Francois Doyon
#
# Mapnik is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the Li... | or, Boston, MA 02110-1301 USA
#
# $Id$
Import ('env')
p | refix = env['PREFIX']
plugin_env = env.Clone()
geos_src = Split(
"""
geos_datasource.cpp
geos_featureset.cpp
"""
)
libraries = [env['PLUGINS']['geos']['lib']]
# Link Library to Dependencies
libraries.append('mapnik')
libraries.append(env['ICU_LIB_NAME'])
libraries.append('boost_system%... |
estaban/pyload | module/plugins/accounts/BitshareCom.py | Python | gpl-3.0 | 1,729 | 0.002892 | # -*- coding: utf-8 -*-
"""
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License,
or (at your option) any later version.
This program is distributed in... | the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
"""
from module.plugins.Account impo... | t):
__name__ = "BitshareCom"
__version__ = "0.12"
__type__ = "account"
__description__ = """Bitshare account plugin"""
__author_name__ = "Paul King"
__author_mail__ = None
def loadAccountInfo(self, user, req):
page = req.load("http://bitshare.com/mysettings.html")
if "\"h... |
Cinntax/home-assistant | homeassistant/components/rfxtrx/cover.py | Python | apache-2.0 | 2,494 | 0 | """Support for RFXtrx covers."""
import voluptuous as vol
from homeassistant.components import rfxtrx
from homeassistant.components.cover import PLATFORM_SCHEMA, CoverDevice
from homeassistant.const import CONF_NAME
from homeassistant.helpers import config_validation as cv
from . import (
CONF_AUTOMATIC_ADD,
... | IGNAL_REPETITIONS,
DEFAULT_SIGNAL_REPETITIONS,
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_DEVICES, default={}): {
cv.string: vol.Schema(
{
vol.Required(CONF_NAME): cv.string,
| vol.Optional(CONF_FIRE_EVENT, default=False): cv.boolean,
}
)
},
vol.Optional(CONF_AUTOMATIC_ADD, default=False): cv.boolean,
vol.Optional(
CONF_SIGNAL_REPETITIONS, default=DEFAULT_SIGNAL_REPETITIONS
): vol.Coerce(int),
}
)
def setup_platform... |
villalonreina/dipy | doc/examples/segment_clustering_features.py | Python | bsd-3-clause | 11,258 | 0.002665 | """
============================================
Tractography Clustering - Available Features
============================================
This page lists available features that can be used by the tractography
clustering framework. For every feature a brief description is provided
explaining: what it does, when it's ... | colormap_full, point_radius=0.2))
fvtk.record(ren, n_frames=1, out_path='center_of_mass_feature.png', size=(600, 600))
"""
.. figure:: center_of_mass_feature.png
:align: center
**Showing the center of mass of each streamline and colored according to
the QuickBundles results**.
.. _clustering-examples-Midpoi... | the feature will then
correspond to the point halfway between the two middle points.
**When:** This feature can be useful when you *only* need information about the
spatial position of a streamline. This can also be an alternative to the
`CenterOfMassFeature` if the point extracted must be on the streamline.
"""
imp... |
EternityForest/KaithemAutomation | kaithem/src/thirdparty/tatsu/rendering.py | Python | gpl-3.0 | 3,873 | 0.000775 | # -*- coding: utf-8 -*-
"""
The Renderer class provides the infrastructure for generating template-based
code. It's used by the .grammars module for parser generat | ion.
"""
from __future__ import generator_stop
import itertools
import string
from tatsu.util import indent, isiter, trim
def render(item, join='', **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, str):
return item
elif isinstance(item, Re... | in(render(e, **fields) for e in iter(item) if e is not None)
elif isinstance(item, (int, float)):
return item
else:
return str(item)
class RenderingFormatter(string.Formatter):
def render(self, item, join='', **fields):
return render(item, join=join, **fields)
def format_field... |
impallari/Impallari-Fontlab-Macros | IMP Simplepolator/Simplepolator 5 steps.py | Python | apache-2.0 | 1,229 | 0.03336 | #FLM: Simplepolator 5 steps
# Simplepolator v1.1
# Description:
# A simple macro to interpolate compatible glyphs inside FontLab.
# To easily apply the Gunnlaugur SE Briem's method
# http://66.147.242.192/~operinan/2/2.3.3a/2.3.3.02.tests.htm
# Credits:
# Pablo Impallari
# http://www.impallari.com/projects/overview/... |
from robofab.interface.all.dialogs import Message
f = CurrentFont()
if fl.count_selected != 2:
Message("Select 2 glyphs for Simplepolation")
else:
source1 = f.selection[0]
source2 = f.selection[1]
if f[source1].isCompatible(f[source2], False):
f["interpolation.1"] = f[source1]
f["interpolation.1"].m... | nterpolation.2"].mark = 80
f["interpolation.3"].interpolate(0.50, f[source1], f[source2])
f["interpolation.3"].round()
f["interpolation.3"].mark = 80
f["interpolation.4"].interpolate(0.75, f[source1], f[source2])
f["interpolation.4"].round()
f["interpolation.4"].mark = 80
f["interpolation.5"] = f[so... |
mattbierner/blotre-py | setup.py | Python | mit | 407 | 0.004914 | from setuptools import setup
setup(
name='blotre',
version='0.1.1',
author="Matt Bierner",
author_email="mattbierner@users. | noreply.github.com",
license="MIT",
description="Thin Python Blot're client.",
url="https://github.com/mattbierner/blotre-py",
py_modules=['blotre'],
install_requires=[
'requ | ests'],
keywords = ['blotre', "blot're", 'REST', 'oauth2']
)
|
rlindner81/pyload | module/plugins/hooks/ExpertDecoders.py | Python | gpl-3.0 | 3,102 | 0.000645 | # -*- coding: utf-8 -*-
from __future__ import with_statement
import base64
import uuid
import pycurl
from module.network.HTTPRequest import BadHeader
from module.network.RequestFactory import getRequest as get_request
from module.plugin | s.internal.Addon import Addon
from module.plugins.internal.misc import threaded
class ExpertDecoders(Addon):
__name__ = "ExpertDecoders"
__type__ = "hook"
__version__ = "0.09"
__status__ = "testing"
__config__ = [("a | ctivated", "bool", "Activated", False),
("passkey", "password", "Access key", ""),
("check_client", "bool", "Don't use if client is connected", True)]
__description__ = """Send captchas to expertdecoders.com"""
__license__ = "GPLv3"
__authors__ = [("RaNaN", "RaNaN@pyload... |
cbingos/hongmafund | ems/views.py | Python | mit | 11,040 | 0.014365 | # -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.http import HttpRequest
#from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_protect
from django.shortcuts import render_to_response,get_object_or_404,get_list_or_404,RequestContext
from django.contrib.sit... | article_category(request,'qqsmjj')
article_srcp = glob_article_category(request,'srcp')
article_zzvip = glob_article_c | ategory(request,'zzvip')
chart,chart2 = index_chart(request)
#print(chart)
from hmchart.views import admanager
ad1,ad2 = admanager(request)
return render_to_response('index2.html',locals())
def spzh_list(request):
article_dlsp = glob_article_category(request,'dlsp')
#print(article_dlsp)
... |
DailyActie/Surrogate-Model | 01-codes/numpy-master/numpy/core/einsumfunc.py | Python | mit | 35,518 | 0.000113 | """
Implementation of optimized einsum.
"""
from __future__ import division, absolute_import, print_function
from numpy.core.multiarray import c_einsum
from numpy.core.numeric import asanyarray
__all__ = ['einsum', 'einsum_path']
einsum_symbols = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
einsum_symbols... | set(einsum_symbols)
def _compute_size_by_dict(indices, idx_dict):
"""
Computes the product of the elements in indices based on the dictionary
idx_dict.
Parameters
----------
indices : iterable
Indices to base the product on.
idx_dict : dictionary
Dictionary of | index sizes
Returns
-------
ret : int
The resulting product.
Examples
--------
>>> _compute_size_by_dict('abbc', {'a': 2, 'b':3, 'c':5})
90
"""
ret = 1
for i in indices:
ret *= idx_dict[i]
return ret
def _find_contraction(positions, input_sets, output_set... |
bitcoinxt/bitcoinxt | qa/rpc-tests/maxblocksinflight.py | Python | mit | 3,769 | 0.001857 | #!/usr/bin/en | v python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accom | panying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.mininode import *
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
import logging
'''
In this test we connect to one node over p2p, send it numerous inv's, and
compare the ... |
dtwiers/PyFracking | src/Formula.py | Python | gpl-3.0 | 2,090 | 0.009569 | from collections import deque
import re
class Formula(object):
"""
Formula allows translation from a prefix-notation expression in a string to a complex number.
This is eventually to be replaced with a cython, c++, or openCL implementation as I'm sure
the performance of this class... | value == 'z'):
return z
elif (value == 'c'):
return c
elif (re.compile('^[\d\.]+').match(value)):
return float(value)
elif (re.compile('^[\d\.]+[\+\-][\d\.]+i$').match(value)):
nums = re.split('[\+\-]', value)
return complex(float(nums[... | ][:-1]))
else:
return EOFError |
jgraving/pinpoint | pinpoint/utils.py | Python | apache-2.0 | 33,939 | 0.000029 | """
Copyright 2015-2018 Jacob M. Graving <jgraving@gmail.com>
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... | ers
----------
contour : array_like
Contour to fit a polygon to
tolerance : int or float, default = 0.1
Tolerance for fitting a polygon as a proportion
of the perimet | er of the contour. This value is used
to set epsilon, which is the maximum distance between
the original contour and its polygon approximation.
Higher values decrease the number of vertices in the polygon.
Lower values increase the number of vertices in the polygon.
This paramete... |
wkh124/wkh124 | gene_expression_correlation.py | Python | gpl-3.0 | 6,865 | 0.004516 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Correlating gene expression measures from two experiments
# Example, comparing NGS vs microarray data
__authors__ = "Eric Normandeau"
__program_name__ = "gene_expression_correlation"
__version_info__ = ('0', '0', '1')
__version__ = '.'.join(__version_info__)
__revision_... | pass
except:
print "Input Error: No ratios_2 file specified or file not found."
print "Use -h for help."
sys.exit(0)
try:
with open(clusters_1_file) as test:
pass
except:
print "Input Error: No clusters_1 file specified or file not found."
print "... | ys.exit(0)
try:
with open(clusters_2_file) as test:
pass
except:
print "Input Error: No clusters_2 file specified or file not found."
print "Use -h for help."
sys.exit(0)
try:
with open(correspondance_file) as test:
pass
except:
pri... |
aperigault/ansible | lib/ansible/modules/network/fortios/fortios_icap_profile.py | Python | gpl-3.0 | 11,540 | 0.0013 | #!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lic... | 'supported_by': 'community',
'metadata_version': '1.1'}
DOCUMENTATION = '''
---
module: fortios_icap_profile
short_description: Configure ICAP profiles in Fortinet's FortiOS and FortiGate.
description:
- This module is able to configure a FortiGate or FortiOS by
allowing the user to... | before usage.
Tested with FOS v6.0.2
version_added: "2.8"
author:
- Miguel Angel Munoz (@mamunozgonzalez)
- Nicolas Thomas (@thomnico)
notes:
- Requires fortiosapi library developed by Fortinet
- Run as a local_action in your playbook
requirements:
- fortiosapi>=0.9.8
options:
host:
... |
watchdogpolska/poradnia | poradnia/letters/migrations/0013_auto_20211230_1439.py | Python | mit | 433 | 0 | # Generated by Django 2.2.25 on 2021-12-30 13:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
(" | letters", "0012_letter_created_by_staff"),
]
operations = [
mi | grations.AlterField(
model_name="letter",
name="created_by_is_staff",
field=models.BooleanField(verbose_name="Created by staff member"),
),
]
|
scotartt/PandocReferencr | PandocReferencr.py | Python | gpl-2.0 | 7,483 | 0.03381 | import sublime, sublime_plugin, sys, re, operator
## This class self-tests! Kind of. Run the CheckRef command over this file.
## It will then check itself. There are deliberate errors that it should find.
## See the comments next to the pandoc refs in python comments below.
footnote_insert = re.compile(r'(\[\^([a-zA-... | ue.pattern)
fn_match = fn_textvalue.search(all_buffer)
if f | n_match:
print(grp + " got match")
matched_fn[fn] = fn_match.group(2)
else :
print(grp + " no match found")
def new_view(self, edit, ownerview):
ownername = ownerview.file_name();
if not ownername:
ownername = ownerview.name()
if not ownername:
ownername = ownerview.id()
newview = owner... |
unnikrishnankgs/va | venv/lib/python3.5/site-packages/nbconvert/exporters/tests/cheese.py | Python | bsd-2-clause | 1,485 | 0.006734 | """
Contains CheesePreprocessor
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#----------... | preprocess | ors to pass variables into the Jinja engine.
"""
resources['cheese'] = 'real'
return nb, resources
|
bhargavvader/pycobra | tests/test_diagnostics.py | Python | mit | 3,735 | 0.005355 | # Licensed under the MIT License - https://opensource.org/licenses/MIT
import unittest
import pytest
import numpy as np
from pycobra.cobra import Cobra
from pycobra.ewa import Ewa
from pycobra.diagnostics import Diagnostics
import logging
class TestOptimal(unittest.TestCase):
def setUp(self):
# setting ... | mse = self.cobr | a_diagnostics.optimal_alpha_grid(self.test_data[0], self.test_response[0])
expected_alpha, expected_mse = 1, 0.01331659692231877
self.assertEqual(expected_alpha, alpha)
self.assertAlmostEqual(expected_mse, mse[0], places=3)
@pytest.mark.slow
def test_machines_grid(self):
(ma... |
gem/oq-hazardlib | openquake/hmtk/seismicity/utils.py | Python | agpl-3.0 | 21,990 | 0.001046 | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# LICENSE
#
# Copyright (c) 2010-2017, GEM Foundation, G. Weatherill, M. Pagani,
# D. Monelli.
#
# The Hazard Modeller's Toolkit is free software: you can redistribute
# it and/or modify it under the terms of the GNU Affero General Public
# License ... | .array([lat1])
else:
nlocs1 = np.max(np.s | hape(lon1))
if not np.shape(lon2):
nlocs2 = 1
lon2 = np.array([lon2])
lat2 = np.array([lat2])
else:
nlocs2 = np.max(np.shape(lon2))
# Pre-allocate array
distance = np.zeros((nlocs1, nlocs2))
i = 0
while i < nlocs2:
# Perform distance calculation
dl... |
michalkurka/h2o-3 | h2o-py/h2o/sklearn/wrapper.py | Python | apache-2.0 | 36,985 | 0.003839 | """
Provides all the logic to construct the `sklearn` wrappers from standard H2O estimators or transformers.
The only requirements from the original estimator are the following:
- it must have a `train` method (equivalent of `sklearn` `fit` method).
- `train` must accept `h2o.H2OFrame` as `training_frame` param.
""... | is_generic=is_generic,
custom_params=custom_params,
)
def transformer(cls, name=None, module=None, default_params=None, mixins=None, custom_params=None):
"""
A slightly simpler method on top of :func:`wrap_estimator` to generate `Trans... | else ()
return wrap_estimator(cls=cls,
bases=(H2OtoSklearnTransformer,) + mixins,
name=name,
module=module,
default_params=default_params,
custom_params=custom_params)
def _to_h2o_fra... |
icereval/osf.io | api/preprint_providers/serializers.py | Python | apache-2.0 | 1,430 | 0.000699 | from rest_framework import serializers as ser
from api.base.serializers import ShowIfVersion
from api.providers.serializers import PreprintProviderSerializer
class DeprecatedPreprintProviderSerializer(PreprintProviderSerializer):
class Meta:
type_ = 'preprint_providers'
| # Deprecate | d fields
header_text = ShowIfVersion(
ser.CharField(read_only=True, default=''),
min_version='2.0', max_version='2.3'
)
banner_path = ShowIfVersion(
ser.CharField(read_only=True, default=''),
min_version='2.0', max_version='2.3'
)
logo_path = ShowIfVersion(
se... |
google/budou | budou/mecabsegmenter.py | Python | apache-2.0 | 3,631 | 0.007469 | # -*- coding: utf-8 -*-
#
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | 10/mecab>`_.
You need to install MeCab to use this segmenter.
The easiest way to install MeCab is to run :code:`make install-mecab`. The
script will download source codes from GitHub and build the tool. It also setup
`IPAdic <https://ja. | osdn.net/projects/ipadic/>`_, a standard dictionary for
Japanese.
"""
import logging
import sys
import six
from .segmenter import Segmenter
from .chunk import Chunk, ChunkList
_DEPENDENT_POS_FORWARD = set()
_DEPENDENT_POS_BACKWARD = {u'助詞', u'助動詞'}
_DEPENDENT_LABEL_FORWARD = set()
_DEPENDENT_LABEL_BACKWARD = {u'非自立'}... |
wdv4758h/ZipPy | edu.uci.python.benchmark/src/benchmarks/fasta3t.py | Python | bsd-3-clause | 2,864 | 0.009777 | # The Computer Language Benchmarks Game
# http://shootout.alioth.debian.org/
#
# modified by Ian Osgo | od
# modified again by Heinrich Acker
# modified by Justin Peel
# modified by Mariano Chouza
# 2to3
import sys, bisect, array
import time
bb = bisect.bisect
alu = (
'GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG'
'GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA'
'CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT'
'ACAAA... | TTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA'
'GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG'
'AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC'
'AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA')
iub = list(zip('acgtBDHKMNRSVWY', [0.27, 0.12, 0.12, 0.27] + [0.02]*11))
homosapiens = [
('a', 0.3029549426680),
('c', 0.1979883004921)... |
pedrosino/tnoodle | svglite/tmtproject.py | Python | gpl-3.0 | 256 | 0.003906 | import tmt
DESCRIPTION = "A dead simple svg generation library written in pure Java, with no dependencies. This code runs on both desktop Java, Android, and compiles to Javascript with GWT."
tmt.EclipseProject(tmt.projectName(), description | =DESCR | IPTION)
|
xyuanmu/XX-Net | python3.8.2/Lib/distutils/cygwinccompiler.py | Python | bsd-2-clause | 16,478 | 0.001456 | """distutils.cygwinccompiler
Provides the CygwinCCompiler class, a subclass of UnixCCompiler that
handles the Cygwin port of the GNU C compiler to Windows. It also contains
the Mingw32CCompiler class which handles the mingw32 port of GCC (same as
cygwin in no-cygwin mode).
"""
# problems:
#
# * if you use a msvc com... | -i", src, "-o", obj])
except DistutilsExecError as msg:
raise CompileError(msg)
else: # for other files use the C-compiler
try:
self.spawn(self.compiler_so + cc_args + [src, '-o', obj] +
extra_postargs)
| except DistutilsExecError as msg:
raise CompileError(msg)
def link(self, target_desc, objects, output_filename, output_dir=None,
libraries=None, library_dirs=None, runtime_library_dirs=None,
export_symbols=None, debug=0, extra_preargs=None,
extra_po... |
GM-Alex/compose | compose/cli/utils.py | Python | apache-2.0 | 3,615 | 0.00083 | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import os
import platform
import ssl
import subprocess
import sys
import docker
import compose
from ..const import HOME_DIR
from ..const import IS_WINDOWS_PLATFORM
from ..const import PLUGIN_DIR
# WindowsE... | eturn False
elif answer == "":
return default
else:
return None
def input(prompt):
"""
Version of input (raw_input in Python 2) which forces a flush of sys.stdout
to avoid problems where the prompt fails to appear due to line buffering
"""
sys.std | out.write(prompt)
sys.stdout.flush()
return sys.stdin.readline().rstrip('\n')
def call_silently(*args, **kwargs):
"""
Like subprocess.call(), but redirects stdout and stderr to /dev/null.
"""
with open(os.devnull, 'w') as shutup:
try:
return subprocess.call(*args, stdout=sh... |
datalogics/scons | test/PharLap.py | Python | mit | 8,931 | 0.001792 | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... | 254 is for kernel services
pop edx ; Restore registers
pop ebx ;
pop eax ;
ret ; and return
PutCharTarget endp
;
; The __pl_unpackrom unpacks initialized RAM based data variables
; out of the ROMINIT segment into their RAM area. They are put
; in the ROMINIT segment wit | h the -ROMINIT switch in the link file.
;
extrn __pl_unpackrom:near
;
; The _EtsExitProcess function is used to terminate our program
;
extrn _EtsExitProcess:near
;
; The linker will define symbols for the beginning and end of the
; BSS segment.
;
extrn __p_SEG__bss_BEGIN:dword
extrn __p_SEG__bss_END:dword
;
; _... |
grepme/CMPUT410Lab01 | virt_env/virt1/lib/python2.7/site-packages/WebHelpers-1.3-py2.7.egg/webhelpers/__init__.py | Python | apache-2.0 | 113 | 0 | """WebHelpers is wide variety | of functions for web applicati | ons and other
applications.
"""
__version__ = "1.3"
|
arasdar/DL | impl-dl/etc/rnns/impl_imagernn_karpathy/generic_batch_generator.py | Python | unlicense | 5,701 | 0.017892 | import numpy as np
import code
from imagernn.utils import merge_init_structs, initw, accumNpDicts
from imagernn.lstm_generator import LSTMGenerator
from imagernn.rnn_generator import RNNGenerator
def decodeGenerator(generator):
if generator == 'lstm':
return LSTMGenerator
if generator == 'rnn':
return RNNG... | ze, image_encoding_size) # image encoder
model['be'] = np.zeros((1,image_encoding_size) | )
model['Ws'] = initw(vocabulary_size, word_encoding_size) # word encoder
update = ['We', 'be', 'Ws']
regularize = ['We', 'Ws']
init_struct = { 'model' : model, 'update' : update, 'regularize' : regularize}
# descend into the specific Generator and initialize it
Generator = decodeGenerator(gene... |
hardikk/newfies-dialer | newfies/api/store_cdr_api.py | Python | mpl-2.0 | 7,506 | 0.001865 | # -*- coding: utf-8 -*-
#
# Newfies-Dialer License
# http://www.newfies-dialer.org
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (C) 2011-2013 Star2Bi... | ')
class CdrValidation(Validation):
"""
CDR Validation Class
"""
def is_valid(self, bundle, request=None):
errors = {}
if not bundle.data:
return {'__all__': 'Not quite what I had in mind.'}
opt_cdr = | request.POST.get('cdr')
if not opt_cdr:
errors['CDR'] = ["Wrong parameters - missing CDR!"]
return errors
class CdrResource(ModelResource):
"""
**Attributes**:
* ``cdr`` - XML string assigned from the Telephony engine
**Validation**:
* CdrValidation()
**... |
hephaestus9/Ironworks | ironworks/serverTools.py | Python | mit | 6,472 | 0.001391 | # -*- coding: utf-8 -*-
import keyring
from ironworks.database import mDb, db
app = None
rundir = None
datadir = None
logger = None
webroot = ""
log_list = []
log_file = ""
commits_behind = 0
latest_commit = None
current_commit = None
commits_compare_url = ""
use_git = False
first_run = 0
threads = []
host = '0.0.0.0'... |
global port
return port
def setAdminLogin(val):
global adminLogin
adminLogin = val
def getAdminLogin():
global adminLogin
| return adminLogin
def setPyEmoncmsLogin(val, user):
global pyemoncmsLogin, pyemoncmsUser
pyemoncmsLogin = val
pyemoncmsUser = user
def getPyEmoncmsLogin():
global pyemoncmsLogin, pyemoncmsUser
status = {"user": pyemoncmsUser, "status": pyemoncmsLogin}
return status
#sqlite database-----... |
sdpython/pyquickhelper | src/pyquickhelper/pycode/unittest_cst.py | Python | mit | 1,760 | 0.000568 | """
@file
@brief Helpers to compress constant used in unit tests.
"""
import base64
import json
import lzma
import pprint
def compress_cst(data, length=70, as_text=False):
"""
Transforms a huge constant into a sequence of compressed binary strings.
:param data: data
:param length: line length
:pa... | turns the results as text
:return: results
.. runpython::
:showcode:
from pyquickhelper.pycode.unittest_cst import compress_cst, decompress_cst
data = {'values': [0.5, 6.9]}
| cp = compress_cst(data)
back = decompress_cst(cp)
print(back)
"""
if isinstance(data, list):
data = b"".join(data)
data64 = base64.b64decode(data)
data_in = lzma.decompress(data64)
dec = data_in.decode('utf-8')
return json.loads(dec)
|
CoderMatthias/ortholog-assignment | 05_scripts/10_ortho_analysis.py | Python | gpl-2.0 | 9,985 | 0.000401 | #!/usr/bin/python3
import sys
import argparse
import re
def logs():
print 'Running script {}'.format(sys.argv[0])
print 'Check 00_logs folder to see output for this script\n\n'
sys.stdout = open('../00_logs/10_{}_analyzed.out'.format(sys.argv[1]), 'w')
print 'Input file was:', sys.argv[1]
print
... | ine in ortholog_list:
if line[index].strip() and not line[index + 1].strip() \
and float(line[index].split(',')[1]) > 200:
| line[line.index('null')] = line[index].split(',')[0]
unambig_list.append(line)
else:
trim_ortho_list.append(line)
print
print 'Only one blastn match assessment'
print 'unambiguous= {}'.format(len(unambig_list))
print 'remain orthos= {}'.format(len(trim_ortho_list))
... |
mediawiki-utilities/python-mwrefs | mwrefs/utilities/diffs.py | Python | mit | 2,473 | 0.001617 | """
Extracts reference diffs from Wikipedia XML database dumps.
Generates a TSV dataset with one row per revision with the following fields.
* rev_id
* rev_timestamp
* user_id
* user_text
* page_id
* page_title
* references_added (a list of complete "<ref>...</ref>" and '<ref name="..."/>' tags)
* references_removed ... | user_id = revision.contributor.id
user_text = revision.contributor.user_text
else:
user_id = 0
user_text = None
yield (revision.id, revision.timestamp, user_id, user_text,
... | last_references = references
print("\t".join(["rev_id", "rev_timestamp", "user_id", "user_text",
"page_id", "page_title", "references_added",
"references_removed"]))
for vals in xml_dump.map(dump_files, process_dump):
print("\t".join(tsv_encode(val) for val ... |
SciTools/cartopy | lib/cartopy/tests/mpl/test_plots.py | Python | lgpl-3.0 | 917 | 0 | # Copyright Cartopy Contributors
#
# This file is part of Cartopy and is released under the LGPL license.
# See COP | YING and COPYING.LESSER in the root of the repository for full
# licensing details.
from io import BytesIO
import matplotlib.pyplot as plt
import numpy as np
import cartopy.crs as ccrs
def test_empty_plot():
"""Test making a plot with empty arrays."""
fig = plt.figure()
ax = plt.axes(projection=ccrs.Me... |
def test_triplot_bbox_tight():
"""Test triplot with a tight bbox (#1060)."""
x = np.degrees([-0.101, -0.090, -0.069])
y = np.degrees([0.872, 0.883, 0.888])
triangles = np.asarray([[0, 1, 2]])
fig = plt.figure()
ax = plt.axes(projection=ccrs.OSGB(approx=False))
ax.triplot(x, y, triangles, t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.