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 |
|---|---|---|---|---|---|---|---|---|
looooo/paraBEM | examples/tests/test_parallel.py | Python | gpl-3.0 | 359 | 0 | import paraBEM
from paraBEM im | port | pan3d
from paraBEM.mesh import mesh_object
mesh = mesh_object.from_OBJ("../mesh/box_minimal.obj")
case = pan3d.DirichletDoublet0Case3(mesh.panels)
case.v_inf = paraBEM.Vector3(1, 0, 0)
a = case.panels[0]
b = case.panels[1]
print(a.center, " ", a.n)
print(b.center, " ", b.n)
print(pan3d.doublet_3_0_vsaero(a.center,... |
jpinsonault/learning_machine | tests.py | Python | mit | 9,652 | 0.001554 | import unittest
from Computer import Computer
class TestInstructions(unittest.TestCase):
def setUp(self):
self.computer = Computer()
def test_load(self):
self.computer.load_program([['load', [2, '1']]])
self.computer.run_program()
self.failUnless(self.computer.memory['1'].val... | f_pos_on_positive(self):
self.computer.load_program([
['load', [5, '1']],
['jump_if_pos', ['1', 2]],
['load', [1, '2']], # Should never | run
['load', [2, '3']],
])
self.computer.run_program()
self.failUnlessEqual(self.computer.memory['3'].value, 2)
self.failIfEqual(self.computer.memory['2'].value, 1)
def test_jump_if_pos_on_negative(self):
self.computer.load_program([
['load', [-1, '... |
bmispelon/django-formtags | tests/forms.py | Python | mit | 388 | 0 | from django import forms
def dummy_validator(value):
if value == 'invalid':
r | aise forms.ValidationError('invalid')
return value
class TestForm(forms.Form):
foo = forms.CharField(required=False, validators=[dummy_validator])
bar = forms.CharField(help_text='help bar', required=False)
baz = forms.C | harField(label='<baz>', help_text='<baz>', required=False)
|
tschalch/pyTray | src/dataStructures/tray_item.py | Python | bsd-3-clause | 847 | 0.005903 | import dataStructures
import logging, os
log = logging.getLogger("tray_item")
log.setLevel(logging.WARN)
class TrayItem:
"""
Parent Class for all items in a tray.
"""
def __init__(self):
self.selected = False
self.changed = False
dataStructures.changingItems.appe... | ds = []
def SetSelected(self, value):
self.selected = value
def SetChanged(self, state):
self.changed = state
if state:
#import traceback
#traceback.print_stack()
log.debug("TrayItem change registered for %s", self.eleme | nt)
def Clone(self):
clone = TrayItem()
clone.selected = self.selected
clone.data = self.data.copy()
clone.fields = self.fields
return clone
|
wuxue/altanalyze | genmappDBs.py | Python | apache-2.0 | 3,609 | 0.030202 | ###genmapp
#Copyright 2005-2008 J. David Gladstone Institutes, San Francisco California
#Author Nathan Salomonis - [email protected]
#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... | PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
#INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
#PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
#HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHE | THER IN AN ACTION
#OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
#SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import sys, string
import math
import os.path
import unique
import copy
import time
import export
def filepath(filename):
fn = unique.filepath(filename)
r... |
santisiri/popego | envs/ALPHA-POPEGO/lib/python2.5/site-packages/ipython-0.8.2-py2.5.egg/IPython/ColorANSI.py | Python | bsd-3-clause | 6,449 | 0.010699 | # -*- coding: utf-8 -*-
"""Tools for coloring text in ANSI terminals.
$Id: ColorANSI.py 2167 2007-03-21 06:57:50Z fperez $"""
#*****************************************************************************
# Copyright (C) 2002-2006 Fernando Perez. <[email protected]>
#
# Distributed under the terms of the BSD... | be created empty and manually filled or it can be
created with a list of valid color schemes AND the | specification for
the default active scheme.
"""
# create object attributes to be set later
self.active_scheme_name = ''
self.active_colors = None
if scheme_list:
if default_scheme == '':
raise ValueError,'you must specify the... |
tdyas/pants | src/python/pants/auth/cookies.py | Python | apache-2.0 | 2,261 | 0.001769 | # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
from http.cookiejar import LWPCookieJar
from pants.process.lock import OwnerPrintingInterProcessFileLock
from pants.subsystem.subsystem import Subsystem
from pants.util.dirutil ... | )
register(
"--path",
advanced=True,
fingerprint=True,
default=os.path.join(register.bootstrap.pants_bootstrapdir, "auth", "cookies"),
help="Path to file that stores persistent cookies. "
"Defaults to <pants bootstrap dir>/auth/cookies.",
... | stances, such as a CookieJar.
"""
cookie_jar = self.get_cookie_jar()
for cookie in cookies:
cookie_jar.set_cookie(cookie)
with self._lock:
cookie_jar.save()
def get_cookie_jar(self):
"""Returns our cookie jar."""
cookie_file = self._get_cookie... |
ObsidianBlk/GemRB--Unofficial- | gemrb/GUIScripts/bg2/Start2.py | Python | gpl-2.0 | 9,946 | 0.044842 | # GemRB - Infinity Engine Emulator
# Copyright (C) 2003 The GemRB Project
#
# 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 versi... | = GemRB.LoadTable ("songlist")
# the table has useless rownames, so we can't search for BG2Theme
theme = MusicTable.GetValue ("33", "RESOURCE")
GemRB.LoadMusicPL (theme, 1)
return
def SinglePlayerPress():
SinglePlayerButton.SetText (13728)
SinglePlayerButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, NewSingle)
Mult... | _GUI_BUTTON_ENABLED)
if not GUICommon.GameIsBG2Demo():
if GemRB.GetVar("oldgame")==1:
MoviesButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, Tutorial)
MoviesButton.SetText (33093)
else:
MoviesButton.SetEvent (IE_GUI_BUTTON_ON_PRESS, ImportGame)
MoviesButton.SetText (71175)
ExitButton.SetText (15416)
ExitBu... |
Nehoroshiy/urnn | manifolds/__init__.py | Python | mit | 100 | 0.01 | from .unitary import Unitary
from .unitary_kron import UnitaryKron
__all | __ = [Unitary, UnitaryKro | n] |
gdi2290/django | tests/postgres_tests/models.py | Python | bsd-3-clause | 822 | 0 | from django.contrib.postgres.fields import ArrayField, HStoreField
from django.db import models
class IntegerArrayModel(models.Model):
field = ArrayField(models.IntegerField | ())
class NullableIntegerArrayModel(models.Model):
field = ArrayField(models.IntegerField(), blank=True, null=True)
class CharArrayModel(models.Model):
field = ArrayField(models.CharField(max_length=10))
class DateTimeArrayModel(models.Model):
field = ArrayField(models.DateTimeField())
class Nes | tedIntegerArrayModel(models.Model):
field = ArrayField(ArrayField(models.IntegerField()))
class HStoreModel(models.Model):
field = HStoreField(blank=True, null=True)
class CharFieldModel(models.Model):
field = models.CharField(max_length=16)
class TextFieldModel(models.Model):
field = models.TextF... |
Vagab0nd/SiCKRAGE | sickchill/oldbeard/dailysearcher.py | Python | gpl-3.0 | 3,608 | 0.002494 | import datetime
import threading
import sickchill.oldbeard.search_queue
from sickchill import logger, settings
from sickchill.helper.exceptions import MultipleShowObjectsException
from sickchill.show.Show import Show
from . import common, db, network_timezones
class DailySearcher(object): # pylint:disable=too-few-... | er.info("No new released episodes found ...")
# queue episode for daily search
dailysearch_queue_item = sickchill.oldbeard.search_queue.DailySearchQueueItem()
settings.searchQu | eueScheduler.action.add_item(dailysearch_queue_item)
self.amActive = False
|
LinuxCircle/tea5767 | hello.py | Python | mit | 114 | 0.008772 | pr | int("TEA5767 FM Radio project")
print("[email protected]")
print("Excellent codes will be uploaded here!") | |
lmazuel/azure-sdk-for-python | azure-mgmt-resource/azure/mgmt/resource/resources/v2016_02_01/models/resource_group.py | Python | mit | 1,961 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | 'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
}
def __init__(self, location, name=None, properties=None, tags=None):
super(ResourceGroup, self).__init__()
self.id = None
self.name = name
self.propert | ies = properties
self.location = location
self.tags = tags
|
coblo/pyiscclib | tests/test_iscclib_image.py | Python | bsd-2-clause | 600 | 0 | # -*- coding: utf-8 -*-
import pytest
from os.path import dirname, join
from iscclib.image import ImageID
TEST_IMG = join(dirname(__file__), '4.2.04.jpg')
TEST_CODE = u'CAUD7P6NU73ID | '
TEST_IDENT = 13733935459959803788
def test_image_id_min_max():
max_value = 2 ** 64 - 1
iid = ImageID(ident=max_value)
assert iid.code == ImageID.CODE_MAX
def test_image_id_from_image():
iid = ImageID.from_image(TEST_IMG)
assert iid.code == TEST_CODE
assert iid.ident == TEST_IDENT
def tes... | , bits=32)
|
ragavvenkatesan/Convolutional-Neural-Networks | tests/layers/test_conv_pool.py | Python | mit | 23,881 | 0.020225 | import unittest
import numpy
import theano
from yann.layers.conv_pool import conv_pool_layer_2d as cl
from yann.layers.conv_pool import dropout_conv_pool_layer_2d as dcl
from yann.layers.conv_pool import deconv_layer_2d as dl
from yann.layers.conv_pool import dropout_deconv_layer_2d as ddl
try:
from unittest.mock i... | d.output,self.input_ndarray))
self.assertTrue(numpy.allclose(self.conv_pool_layer_2d.inference,self.input_ndarray))
@patch('theano.tensor.unbroadcast')
@patch('yann.layers.conv_pool. | _activate')
@patch('yann.layers.conv_pool.batch_normalization_test')
@patch('yann.layers.conv_pool.batch_normalization_train')
def test2_conv_pool_layer_2d_ip_none(self,mock_batch_normalization_train,mock_batch_normalization_test,mock_activate,mock_unbroadcast):
mock_unbroadcast.return_value = 1
... |
anselmobd/fo2 | src/comercial/migrations/0012_metafaturamento_faturamento_integer.py | Python | mit | 464 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2020-02-10 21:39
from __future__ import unicode_literals
from django.db import migrations, models
class | Migration(migrations.Migration):
dependencies = [
('comercial', '0011_metafaturamento'),
]
operations = [
migrations.AlterField(
model_name='metafaturamento',
name='faturamento',
field=mod | els.IntegerField(default=0),
),
]
|
2degrees/wsgi-xsendfile | setup.py | Python | bsd-3-clause | 2,005 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2010-2015, 2degrees Limited.
# All Rights Reserved.
#
# This file is part of wsgi-xsendfile <http://pythonhosted.org/xsendfile/>,
# which is subject to the provisions of the BSD at
# <http://dev.2deg... | "Operating System :: OS Independent",
"Programming Language :: Python :: 2",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI",
"Topic :: Security",
],
key | words="x-sendfile xsendfile x-accel authorization token url hot-link",
author="2degrees Limited",
author_email="[email protected]",
url="http://pythonhosted.org/xsendfile/",
license="BSD (http://dev.2degreesnetwork.com/p/2degrees-license.html)",
py_modules=["xsendfile"],
install... |
opennode/nodeconductor-assembly-waldur | src/waldur_mastermind/support/migrations/0005_extend_icon_url_size.py | Python | mit | 437 | 0.002288 | # Generated by Django 2.2.10 on 2020-04-05 11:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('support', '0004_templateconfirmationcomment'),
]
operations = [
migrations.AlterField(
model_name='priority',
name=... | con url'),
| ),
]
|
LowerSilesians/ursa-rest-sqlserver | ursa_rest_sqlserver/manage.py | Python | apache-2.0 | 817 | 0.001224 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ursa_rest_sqlserver.settings")
try:
from django.core.management import execute_from_command_line
| except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"... | import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
|
spaam/svtplay-dl | lib/svtplay_dl/tests/test_service.py | Python | mit | 2,933 | 0.002387 | import unittest
from svtplay_dl.service import Generic
from svtplay_dl.service import opengraph_get
from svtplay_dl.service import Service
from svtplay_dl.service import service_handler
from svtplay_dl.service.services import sites
from svtplay_dl.utils.parser import setup_defaults
class MockService(Service):
su... | config = setup_defaults()
generic = Generic(config, "http://example.com")
data = 'source src="http://example.com/hls.m3u8" type="application/x-mpegURL"'
assert isinstance(generic._match(data, sites)[1], Service)
def test_tv | 4(self):
config = setup_defaults()
generic = Generic(config, "http://example.com")
data = "rc=https://www.tv4play.se/iframe/video/12499319 "
assert isinstance(generic._match(data, sites)[1], Service)
def test_vimeo(self):
config = setup_defaults()
generic = Generic(c... |
vishnu-kumar/PeformanceFramework | rally_os/plugins/openstack/scenarios/tempest/tempest.py | Python | apache-2.0 | 4,269 | 0 | # Copyright 2014: Mirantis 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 agreed to in writing, software
# distributed und... | KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from rally import consts
from rally.plugins.openstack import scenario
from rally.plugins.openstack.scenarios.tempest import utils
from rally.task import validation
class Temp... |
iamweilee/pylearn | threading-example-1.py | Python | mit | 2,573 | 0.008162 | '''
×¢ÒâÏß³ÌÖ§³ÖÄ£¿éÊÇ¿ÉÑ¡µÄ, ÓпÉÄÜÔÚһЩ Python ½âÊÍÆ÷Öв»¿ÉÓÃ.
Ö´ÐÐ Python ³ÌÐòµÄʱºò, Êǰ´ÕÕ´ÓÖ÷Ä£¿é¶¥¶ËÏòÏÂÖ´ÐеÄ.
Ñ»·ÓÃÓÚÖØ¸´Ö´Ðв¿·Ö´úÂë, º¯ÊýºÍ·½·¨»á½«¿ØÖÆÁÙÊ±ÒÆ½»µ½³ÌÐòµÄÁíÒ»²¿·Ö.
ͨ¹ýÏß³Ì, ÄãµÄ³ÌÐò¿ÉÒÔÔÚͬʱ´¦Àí¶à¸öÈÎÎñ. ÿ¸öÏ̶߳¼ÓÐËü×Ô¼ºµÄ¿ØÖÆÁ÷.
ËùÒÔÄã¿ÉÒÔÔÚÒ»¸öÏß³ÌÀï´ÓÎļþ¶ÁÈ¡Êý¾Ý, Áí¸öÏòÆÁÄ»Êä³öÄÚÈÝ.
Î... | Java µÄÏß³ÌʵÏÖ.
ºÍµÍ¼¶µÄ thread Ä£¿éÏàͬ, Ö»ÓÐÄãÔÚ±àÒë½âÊÍÆ÷ʱ´ò¿ªÁËÏß³ÌÖ§³Ö²Å¿ÉÒÔʹÓÃËü .
ÄãÖ»ÐèÒª¼Ì³Ð Thread Àà, ¶¨ÒåºÃ run ·½·¨, ¾Í¿ÉÒÔ´´½¨Ò» ¸öеÄÏß³Ì.
ʹÓÃʱÊ×ÏÈ´´½¨¸ÃÀàµÄÒ»¸ö»ò¶à¸öʵÀý, È»ºóµ÷Óà start ·½·¨ | .
ÕâÑùÿ¸öʵÀýµÄ run ·½·¨¶¼»áÔËÐÐÔÚËü×Ô¼ºµÄÏß³ÌÀï.
'''
import threading
import time, random
class Counter:
def __init__(self):
self.lock = threading.Lock()
self.value = 0
def increment(self):
self.lock.acquire() # critical section
self.value = value = self.value + 1
... |
coherence-project/Coherence | coherence/extern/et.py | Python | mit | 4,662 | 0.001287 | # -*- coding: utf-8 -*-
#
# Licensed under the MIT li | cense
# http://opensource.org/licenses/mit-license.php
#
# Copyright 2006,2007 Frank Scholz <[email protected]>
# Copyright 2014 Hartmut Goebel <[email protected]>
#
"""
little helper to get the proper ElementTree package
"""
import re
import exceptions
try:
import cElementTree as ET
import ele... | enttree
except ImportError:
# this seems to be necessary with the python2.5 on the Maemo platform
try:
from xml.etree import cElementTree as ET
from xml import etree as elementtree
except ImportError:
try:
from xml.etree import ElementTree ... |
andreikop/qutepart | qutepart/syntax/data/regenerate-definitions-db.py | Python | lgpl-2.1 | 3,241 | 0.005554 | #!/usr/bin/env python3
import os.path
import json
import sys
_MY_PATH = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(_MY_PATH, '..', '..', '..'))
from qutepart.syntax.loader import loadSyntax
from qutepart.syntax import SyntaxManager, Syntax
def _add_php(targetFileName, srcFileName)... |
syntaxNameToXmlFileName[syntax.name] = (syntax.priority, xmlFileNam | e)
if syntax.mimetype:
for mimetype in syntax.mimetype:
if not mimetype in mimeTypeToXmlFileName or \
mimeTypeToXmlFileName[mimetype][0] < syntax.priority:
mimeTypeToXmlFileName[mimetype] = (syntax.priority, xmlFileName)
if syntax.exte... |
coala/coala | tests/parsing/CliParsingTest.py | Python | agpl-3.0 | 3,059 | 0 | import argparse
import unittest
from coalib.parsing.CliParsing import parse_cli, check_conflicts
class CliParserTest(unittest.TestCase):
def setUp(self):
self.test_arg_parser = argparse.ArgumentParser()
self.test_arg_parser.add_argument('-t', nargs='+', dest='test')
self.test_arg_parser.... | alue)) for key, value in section.contents.items()]))
return parsed_dict
def test_parse_cli(self):
# regular parse
parsed_sections = parse_cli(
['-t', 'ignored1', 'ignored2',
'-t', 'taken',
'-S', 'section1.key1,section2.key2=value1,value2',
... | er',
'.key=only_in_cli',
'default_key1,default_key2=single_value',
'default_key3=first_value,second_value'],
arg_parser=self.test_arg_parser)
expected_dict = {
'cli': {
('test', 'taken'),
('key', 'only_in_cli'),
... |
FreeJournal/freejournal | controllers/controller.py | Python | mit | 15,637 | 0.003645 | from models.keyword import Keyword
from models.document import Document
from models.collection import Collection
from bitmessage.bitmessage import Bitmessage
from models.fj_message import FJMessage
from models.signature import Signature
from cache.cache import Cache
from config import DOCUMENT_DIRECTORY_PATH, MAIN_CHAN... |
for doc in payload["documents"]:
db_doc = self.cache.get_document_by_hash(doc["hash"])
if db_doc is not None:
collection.documents.append(db_doc)
else:
collection.documents.append(Document(collection_address=doc["address"], description=doc["de... | hash=doc["hash"], title=doc["title"], filename=doc["filename"], accesses=doc["accesses"]))
def _cache_collection(self, payload, message):
"""
Checks to see if this collection is already in the cache. If it is we update the collection with the new data.
Otherwis... |
joyhope/open62541 | tools/pyUANamespace/ua_namespace.py | Python | lgpl-3.0 | 30,372 | 0.013499 | #!/usr/bin/env/python
# -*- coding: utf-8 -*-
###
### Author: Chris Iatrou ([email protected])
### Version: rev 13
###
### This program was created for educational purposes and has been
### contributed to the open62541 project by the author. All licensing
### terms for this source is inherited by the terms and... | t aliasst in self.aliases:
self.aliases[aliasst] = aliasnd
log(self, "Added new alias \"" + str(aliasst) + "\" == \"" + str(aliasnd) + "\"")
else | :
if self.aliases[aliasst] != aliasnd:
log(self, "Alias definitions for " + aliasst + " differ. Have " + self.aliases[aliasst] + " but XML defines " + aliasnd + ". Keeping current definition.", LOG_LEVEL_ERROR)
def getNodeByBrowseName(self, idstring):
""" Returns the first node in the n... |
kkzzzzzz/Deep-Learing | Sensor/code.py | Python | mit | 991 | 0.00904 | #coding:utf-8
# 感知器 y = f(Wn * x + b)
# 代码实现的是一个逻辑AND操作,输入最后一项一直为1,代表我们可以理解偏置项b的特征值输入一直为1
# | 这样就是 y = f(Wn+1*[x,1]), Wn+1就是b
# https://www.zybuluo.com/hanbingtao/note/433855
from numpy import array, dot, random
from random import choice
def fun_1_or_0(x): return 0 if x < 0 else 1
training_data = [(array([0, 0, 1]), 0), (array([0, 1, 1]), 0),
(array([1, 0, 1]), 0), (array([1, 1, 1]), 1)]
... | s:",weights)
learning_rate = 0.2
num_iteratios = 100
for i in range(num_iteratios):
input, truth = choice(training_data)
result = dot(weights, input)
error = truth - fun_1_or_0(result)
weights += learning_rate * error * input
print("after traning, weights:",weights)
for x, _ in training_data:
... |
Jay-Jay-D/LeanSTP | Algorithm.Python/AddUniverseSelectionModelAlgorithm.py | Python | apache-2.0 | 2,903 | 0.013444 | # QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the Lice... | Create("AAPL", SecurityType.Equity, Market.USA) ]))
self.AddUniverseSelection(ManualUniverseSelectionModel(
Symbol.Create("SPY", SecurityType.Equity, Market.USA), # duplicate will be ignored
Symbol.Create("FB", SecurityType.Equity, Market.USA)))
def OnEndOfAlgorithm(self):
... | nt")
if self.UniverseManager.ActiveSecurities.Count != 3:
raise ValueError("Unexpected active securities") |
brutalic/pynet_brutal | class6/library/eos_vlan.py | Python | apache-2.0 | 18,361 | 0.001362 | #!/usr/bin/python
#
# Copyright (c) 2015, Arista Networks, 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,
# t... | ey in self.__attributes__:
if getattr(self, key) is not None:
config[key] = getattr(self, key)
if 'transport' not in config:
raise ValueError('Connection must define a transport')
connection = pyeapi.client.make_connection(**config)
node = pyeapi.client.... | pilib.ConnectionError, pyeapi.eapilib.CommandError):
raise ValueError('unable to connect to {}'.format(node))
return node
class EosAnsibleModule(AnsibleModule):
meta_args = {
'config': dict(),
'username': dict(),
'password': dict(),
'host': dict(),
'con... |
yuyuyu101/VirtualBox-NetBSD | src/VBox/GuestHost/OpenGL/state_tracker/state_defs.py | Python | gpl-2.0 | 1,397 | 0.004295 | # Copyright (c) 2001, Stanford University
# All rights reserved.
#
# See the file LICENSE.txt for information on redistributing this software.
import sys
import apiutil
apiutil.CopyrightDef()
print """DESCRIPTION ""
EXPORTS
"""
keys = apiutil.GetDispatchedFunctions(sys.argv[1]+"/APIspec.txt")
for func_name in ap... | erPosUpdate
crStateText | ureCheckDirtyImages
crStateExtensionsInit
crStateSetExtensionString
crStateUseServerArrays
crStateUseServerArrayElements
crStateComputeVersion
crStateTransformXformPointMatrixf
crStateTransformXformPointMatrixd
crStateInitMatrixStack
crStateLoadMatrix
__currentBits
"""
|
gridcf/gct | gridftp/net_manager/test/port_plus_one.py | Python | apache-2.0 | 297 | 0 | def pre_listen(task_id, transport, attr_array):
new_attrs = []
for (scope, name, value) in attr_array:
if scope == transport and name == 'port':
value = str(int(value) + 1)
new_attr = (scope, | name, value)
new_attrs. | append(new_attr)
return new_attrs
|
BackupTheBerlios/cuon-svn | cuon_server/WEB/html/fromGladeToHtml.py | Python | gpl-3.0 | 9,485 | 0.017294 | # -*- coding: utf-8 -*-
##Copyright (C) [2010] [Jürgen Hamel, D-32584 Löhne]
##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 versio... | ry:
signal = child.nodeValue
except:
pass
elif att.getAttribute('handler'):
print '1--- ', att.getAttribute('handler')
... | for child in childs:
print 'child handler 1= ', child.nodeValue
print 'child handler 2 = ', child.nodeName
try:
handler = child.nodeValue
... |
gEndelf/cmsplugin-testimonials | cmsplugin_testimonials/admin.py | Python | mit | 88 | 0 | f | rom django.contrib import admin
import models
admin.site.register(models.Testimonia | l)
|
drayside/kodkod | libs/.waf-1.6.6-c57dd0fa119e23d36c23d598487c6880/waflib/Tools/c_preproc.py | Python | mit | 16,576 | 0.083072 | #! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! http://waf.googlecode.com/svn/docs/wafbook/single.html#_obtaining_the_waf_file
import sys
if sys.hexversion < 0x020400f0: from sets import Set as set
import re,sys,os,string,traceback
from waflib import Logs,Build,Utils,Errors
from waflib.Logs import deb... | else:
return get_term(lst[i+1:])
else:
num2,lst=get_nu | m(lst[1:])
if not lst:
num2=reduce_nums(num,num2,v)
return get_term([(NUM,num2)]+lst)
p2,v2=lst[0]
if p2!=OP:
raise PreprocError("op expected %r"%lst)
if prec[v2]>=prec[v]:
num2=reduce_nums(num,num2,v)
return get_term([(NUM,num2)]+lst)
else:
num3,lst=get_num(lst[1:])
num3=redu... |
jonathanxqs/lintcode | 171.py | Python | mit | 1,786 | 0.014558 | import copy
class Solution:
# @param strs: A list of strings
# @return: A list of strings
def anagrams(self, strs):
# write your code here
str1=copy.deepcopy(strs)
def hashLize(s):
dicts1= dict()
for i in range(26):
dicts1[chr(i+ord("a"... | ,len(strs)):
# if i==j:
# continue
# if flag[j]:
# continue
# if str1[i]==str1[j]:
# if flag[i]==0:
# str_rt.append(strs[i])
# flag[i] = 1
# flag... | # str_rt.append(strs[j])
|
karmix/blivet | blivet/partitioning.py | Python | gpl-2.0 | 81,110 | 0.001763 | # partitioning.py
# Disk partitioning functions.
#
# Copyright (C) 2009, 2010, 2011, 2012, 2013 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any... | part_type = parted.PARTITION_NORMAL
elif logical_count < max_logicals:
# we have an extended with logical slots, so use one.
part_type = parted.PARTITION_LOGICAL
else:
# there are two or more primary slots left. use one unless ... | if extended and logical_count < max_logicals:
part_type = parted.PARTITION_LOGICAL
elif extended and logical_count < max_logicals:
part_type = parted.PARTITION_LOGICAL
return part_type
def getBestFreeSpaceRegion(disk, part_type, req_size, start=None,
boot=Non... |
osantana/ami-push | ami_push/bridge.py | Python | mit | 1,262 | 0 | # coding: utf-8
import asyncio
import logging
from panoramisk import Manager
from .controller import Controller, DEFAULT_MAX_QUEUES, DEFAULT_MAX_QUEUE_SIZE
from .messages import MessageWrapper
class Bridge:
def __init__(self, options, filters, push_configs):
self.loop = asyncio.get_event_loop()
... | roller(self.loop, max_queues, max_queue_size)
self.controller.load_configs(filters, push_configs)
options.pop("loop", None) # discard invalid argument
self.manager = Manager(loop=self.loop, **options)
self.manager.log.addHandler(logging.NullHandler())
self.manager.register_even... | ts(self, manager, message):
wrapper = MessageWrapper(message)
yield from self.controller.handle(wrapper)
@asyncio.coroutine
def connect(self):
yield from self.manager.connect()
def run(self):
try:
self.loop.run_until_complete(self.connect())
self.loo... |
Juanvvc/scfs | webserver/cherrypy/test/modwsgi.py | Python | gpl-2.0 | 4,799 | 0.002917 | """Wrapper for mod_wsgi, for use as a CherryPy HTTP server.
To autostart modwsgi, the "apache" executable or script must be
on your system path, or you must override the global APACHE_PATH.
On some platforms, "apache" may be called "apachectl" or "apache2ctl"--
create a symlink to them if needed.
KNOWN BUGS
========... |
## output is then truncated again by Apache. See test_core.testRanges.
## This was worked around in http://www.cherrypy.org/changeset/1319.
2. Apache does not allow custom HTTP methods like CONNECT as per the spec.
See test_core.testHTTPMethods.
3. Max request header and body setti | ngs do not work with Apache.
##4. Apache replaces status "reason phrases" automatically. For example,
## CherryPy may set "304 Not modified" but Apache will write out
## "304 Not Modified" (capital "M").
##5. Apache does not allow custom error codes as per the spec.
##6. Apache (or perhaps modpython, or modpython... |
AlienCowEatCake/ImageViewer | src/ThirdParty/Exiv2/exiv2-0.27.5-Source/tests/bugfixes/redmine/test_issue_1202.py | Python | gpl-3.0 | 1,550 | 0.001935 | # -*- coding: utf-8 -*-
import system_tests
@system_tests.CopyFiles("$data_path/exiv2-bug1202.jpg")
class CheckFocusContinuous(metaclass=system_tests.CaseMeta):
url = "http://dev.exiv2.org/issues/1202"
filename = "$data_path/exiv2-bug1202_copy.jpg"
commands = [
"""$exiv2 -M"set Exif.CanonCs.Focu... | CanonCs.FocusContinuous $filename""",
"""$exiv2 -M"set Exif.CanonCs.FocusContinuous SShort 9" $filename""",
"""$exiv2 -K Exif.CanonCs.FocusContinuous $filename""",
"""$exiv2 -M"set | Exif.CanonCs.FocusContinuous SShort -1" $filename""",
"""$exiv2 -K Exif.CanonCs.FocusContinuous $filename""",
]
stdout = [
"",
"Exif.CanonCs.FocusContinuous Short 1 Single\n",
"",
"Exif.CanonCs.FocusContinuous Short 1 Conti... |
asavonic/moldynam | data/particles.py | Python | gpl-2.0 | 1,052 | 0.03327 | import random
import sys
class Particle:
def __init__( self ):
pass
def __str__( self ):
return str( "%f %f %f %f %f %f 0 0 0" % ( self.pos[0],
self.pos[1],
self.pos[2],
... | in particles:
particle.pos = tuple( random.uniform( 0, comp ) for comp in area_size )
particle.vel = tuple( random.uniform( 0, comp / 100.0 ) for comp in area_size )
return particles
if len(sys.argv) < 2:
sys.stderr.write("please specify particles number\n")
| sys.exit(1)
particles_num = int(sys.argv[1])
particles = create_random_particles( particles_num, ( 10, 10, 10 ) )
for particle in particles:
print( particle )
|
voltaire/minecraft-site | app/run.py | Python | bsd-3-clause | 111 | 0 | #!/usr/b | in/env python
from app import app
if __name__ == "__main__":
app.run(debug=T | rue, host='0.0.0.0')
|
savanu/servo | components/style/gecko/regen_atoms.py | Python | mpl-2.0 | 8,113 | 0.002465 | #!/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 http://mozilla.org/MPL/2.0/.
import re
import os
import sys
from io import BytesIO
GECKO_DIR = os.path.dirname(__file__.repl... | *mut _) }}'
| ' }};')
MACRO = '''
#[macro_export]
macro_rules! atom {{
{}
}}
'''
def write_atom_macro(atoms, file_name):
def get_symbols(func):
return '\n'.join([ATOM_TEMPLATE.format(name=atom.ident,
link_name=func(atom),
t... |
JeremyRubin/bitcoin | test/functional/feature_nulldummy.py | Python | mit | 7,178 | 0.004319 | #!/usr/bin/env python3
# Copyright (c) 2016-2020 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test NULLDUMMY softfork.
Connect to a single node.
Generate 2 blocks (save the coinbases for later).
G... | block = create_block(tmpl=tmpl, ntime=self.lastblocktime + 1)
for tx in txs:
tx.rehash()
block.vtx.append(tx)
block.hashMerkleRoot = block.calc_merkle_root()
witness and add_witness_commitment(block)
block.rehash()
block.solve()
assert_equal(Non... | elf.lastblockhash = block.hash
self.lastblocktime += 1
self.lastblockheight += 1
else:
assert_equal(node.getbestblockhash(), self.lastblockhash)
if __name__ == '__main__':
NULLDUMMYTest().main()
|
111pontes/ydk-py | cisco-ios-xe/ydk/models/cisco_ios_xe/_meta/_tailf_netconf_monitoring.py | Python | apache-2.0 | 3,575 | 0.015944 |
import re
import collections
from enum import Enum
from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLI... | ' : _MetaInfoClass('RestHttpIdentity',
False,
[
],
| 'tailf-netconf-monitoring',
'rest-http',
_yang_ns._namespaces['tailf-netconf-monitoring'],
'ydk.models.cisco_ios_xe.tailf_netconf_monitoring'
),
},
'CliSshIdentity' : {
'meta_info' : _MetaInfoClass('CliSshIdentity',
False,
[
... |
box/flaky | test/test_multiprocess_string_io.py | Python | apache-2.0 | 1,556 | 0 | from io import StringIO
from unittest import TestCase
from | genty import genty, genty_dataset
@genty
class TestMultiprocessSt | ringIO(TestCase):
_unicode_string = 'Plain Hello'
_unicode_string_non_ascii = 'ńőń ȁŝćȉȉ ŝƭȕƒƒ'
def setUp(self):
super().setUp()
from flaky.multiprocess_string_io import MultiprocessingStringIO
self._string_io = StringIO()
self._mp_string_io = MultiprocessingStringIO()
... |
scpeters/catkin_tools | catkin_tools/jobs/utils.py | Python | apache-2.0 | 6,578 | 0.001976 | # Copyright 2014 Open Source Robotics Foundation, 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... | continue
dirs_to_check.add(path)
# For each | directory which may be empty after cleaning, visit them
# depth-first and count their descendants
dir_descendants = dict()
for path in sorted(dirs_to_check, key=lambda k: -len(k.split(os.path.sep))):
# Get the absolute path to all the files currently in this directory
fi... |
koduj-z-klasa/python101 | docs/pyqt/todopw/baza_z5.py | Python | mit | 2,242 | 0 | # -*- coding: utf-8 -*-
from peewee import *
from datetime import datetime
baza = SqliteDatabase('adresy.db')
class BazaModel(Model): # klasa bazowa
class Meta:
database = baza
class Osoba(BazaModel):
login = CharField(null=False, unique=True)
haslo = CharField()
class Meta:
ord... | treść zadania
'{0:%Y-%m-%d %H:%M:%S}'.format(z.datad), # data dodania
z.wykonane, # bool: cz | y wykonane?
False]) # bool: czy usunąć?
return zadania
def dodajZadanie(osoba, tresc):
""" Dodawanie nowego zadania """
zadanie = Zadanie(tresc=tresc, osoba=osoba)
zadanie.save()
return [
zadanie.id,
zadanie.tresc,
'{0:%Y-%m-%d %H:%M:%S}'.format(zadanie.datad),... |
stanford-rc/shine | lib/Shine/Lustre/Router.py | Python | gpl-2.0 | 3,044 | 0.003614 | # Router.py -- Shine Lustre Router
# Copyright (C) 2010-2013 CEA
#
# This file is part of shine
#
# 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 o... | uter in Shine framework.
"""
TYPE = 'router'
DISPLAY_ORDER = 1
START_ORDER = 1
#
# Text form for different router states.
#
# Could be nearly merged with Target state_text_map if | MOUNTED value
# becomes the same.
STATE_TEXT_MAP = {
None: "unknown",
OFFLINE: "offline",
TARGET_ERROR: "ERROR",
MOUNTED: "online",
RUNTIME_ERROR: "CHECK FAILURE"
}
def longtext(self):
"""
Return the routeur server name.
"""
r... |
cliffano/swaggy-jenkins | clients/python-experimental/generated/openapi_client/model/pipeline_step_impl.py | Python | mit | 3,115 | 0.001284 | # coding: utf-8
"""
Swaggy Jenkins
Jenkins API clients generated from Swagger / Open API specification # noqa: E501
The version of the OpenAPI document: 1.1.2-pre.0
Contact: [email protected]
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
impor... | t] = unset,
startTime: typ | ing.Union[startTime, Unset] = unset,
state: typing.Union[state, Unset] = unset,
_instantiation_metadata: typing.Optional[InstantiationMetadata] = None,
**kwargs: typing.Type[Schema],
) -> 'PipelineStepImpl':
return super().__new__(
cls,
*args,
_cla... |
xandors/dino | dino/__main__.py | Python | apache-2.0 | 941 | 0.001063 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
dino.__main__
~~~~~~~~~~~~~~~~~~~~~
The main entry point for the command line interface.
Invoke as ``dino`` (if installed)
or ``python -m dino`` (no install required).
"""
from __future__ import absolute_import, unicode_literals
import logging
import sys
from dino.lo... | ome useful functionality here or import from a submodule."""
# configure root logger to print to STDERR
configure_stream(level='DEBUG')
# launch the command line interface
logger.debug('Booting up command line interface')
# ...oops, it wasn't implemented yet!
logger.error('Please implement the... | mmand line interface!')
raise NotImplementedError('Dino Dependency Injection CLI not implemented yet')
if __name__ == '__main__':
# exit using whatever exit code the CLI returned
sys.exit(cli())
|
pisun2/python | static.py | Python | apache-2.0 | 711 | 0.007032 | python manage.py collectstatic
python manage.py runserver --nostatic
urlpatterns += patterns('',
(r'^static/suit/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.DJANGO_SUIT_TEMPLAT | E}),
)
urlpatterns += patterns('',
(r'^static/admin/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.DJANGO_ADMIN_TEMPLATE}),
)
SITE_PATH = os.path.dirname(__file__)
REPO_ROOT = os.path.normpath(os.path.join(S | ITE_PATH, '..'))
MEDIA_ROOT = os.path.join(REPO_ROOT, 'public/media')
DJANGO_SUIT_TEMPLATE = os.path.join(REPO_ROOT, 'static/suit')
DJANGO_EDITOR = os.path.join(REPO_ROOT, 'static/django_summernote')
DJANGO_ADMIN_TEMPLATE = os.path.join(REPO_ROOT, 'static/admin')
|
zatricion/Streams | ExamplesElementaryOperations/ExamplesOpNoState.py | Python | mit | 4,241 | 0.006602 | """This module contains examples of the op() function
where:
op(f,x) returns a stream where x is a stream, and f
is an operator on lists, i.e., f is a function from
a list to a list. These lists are of lists of arbitrary
objects other than streams and agents.
Function f must be stateless, i.e., for any lists u, v:
f(u... | ON STREAMS
# The input stream for these examples
x = Stream('x')
print 'x is the input stream.'
print 'a is a stream consisting of the squares of the input'
print 'b is the stream consisting of values that exceed 6'
print 'c is the stream consisting of the third powers of the input'
pr... | e stream consisting of values that are multiples of 3 divided by 3'
print 'newa is the same as a. It is defined in a more succinct fashion.'
print 'newb has squares that exceed 6.'
print ''
# The output streams a, b, c, d obtained by
# applying the list operators f, g, h, r to
# stream x.
a... |
darrenwatt/steam_tracker | create_hour_per_day_chart.py | Python | gpl-2.0 | 1,342 | 0.003726 | import os
import plotly.plotly as py
from plotly.graph_objs import *
import config
py.sign_in(config.plotly_user, config.plotly_pass)
| dates = []
count_dates = []
c | ounts = []
hours = []
with open(os.path.normpath(config.filename), 'r') as f:
rows = f.readlines()
# get summary of dates in file
for line in rows:
lines = line.strip().split(',')
just_date = lines[0].split(' ')
dates.append(just_date[0])
bins = sorted(list(set(dates)))
# coun... |
jawilson/home-assistant | tests/components/hassio/test_handler.py | Python | apache-2.0 | 7,540 | 0.000928 | """The tests for the hassio component."""
import aiohttp
import pytest
from homeassistant.components.hassio.handler import HassioAPIError
async def test_api_ping(hassio_handler, aioclient_mock):
"""Test setup with API ping."""
aioclient_mock.get("http://127.0.0.1/supervisor/ping", json={"result": "ok"})
... | , aioclient_mock):
"""Test setup with API generic info."""
aioclient_mock.get(
"http://127.0.0.1/info",
json={
"result": "ok",
"data": {"supervisor": "222", "homeassistant": "0.110.0", "hassos": None},
},
)
data = await hassio_handler.get_info()
asser... | = 1
assert data["hassos"] is None
assert data["homeassistant"] == "0.110.0"
assert data["supervisor"] == "222"
async def test_api_info_error(hassio_handler, aioclient_mock):
"""Test setup with API Home Assistant info error."""
aioclient_mock.get(
"http://127.0.0.1/info", json={"result": "e... |
googleapis/python-container | samples/generated_samples/container_v1_generated_cluster_manager_set_network_policy_sync.py | Python | apache-2.0 | 1,448 | 0.000691 | # -*- coding: utf-8 -* | -
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for SetNetworkPolicy
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may requi... |
rahlk/WarnPlan | warnplan/commons/tools/axe/where2.py | Python | mit | 10,028 | 0.028022 | """
# A Better Where
WHERE2 is a near-linear time top-down clustering alogithm.
WHERE2 updated an older where with new Python tricks.
## Standard Header Stuff
"""
from __future__ import division,print_function
import sys
sys.dont_write_bytecode = True
from lib import *
from nasa93 import *
"""
## Dimensionali... | ap
WHERE2 finds everyone's else's distance from the poles
and divide the data.dat on the mean point of those
distances. This all stops if:
+ Any division has _tooFew_ solutions (say,
less than _sqrt_ of the total number of
solutions).
+ Something has gone horribly wrong and you are
recursin | g _tooDeep_
This code is controlled by the options in [_The_ settings](settingspy). For
example, if _The.pruning_ is true, we may ignore
some sub-tree (this process is discussed, later on).
Also, if _The.verbose_ is true, the _show_
function prints out a little tree showing the
progress (and to print indents in that ... |
whitzhu/kolibri | kolibri/logger/permissions.py | Python | mit | 989 | 0.004044 | from kolibri.auth.permissions.base import BasePermissions
class AnonymousUsersCanWriteAnonymousLogs(BasePermissions):
"""
Permissions class that allows anonymous users to create logs with no associated user.
"""
def user_can_create_object(self, user, obj):
return user.is_anonymous() and not o... | (self, user, obj):
# this one is a bit worrying, since anybody could update anonymous logs, but at least only if they have the ID
# (and this is needed, in order to allow a ContentSessionLog to be updated within a session -- in theory,
# we could add date checking in here to not allow further up... | return False
def readable_by_user_filter(self, user, queryset):
return queryset.none()
|
scottkmaxwell/papa | tests/executables/echo_client.py | Python | mit | 429 | 0 | import sys
import socket
from papa.utils import cast_string, send_with_retry | , recv_with_retry
__author__ = 'Scott Maxwell'
if len(sys.argv) != 2:
sys.stderr.write(' | Need one port number\n')
sys.exit(1)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', int(sys.argv[1])))
send_with_retry(sock, b'howdy\n')
data = recv_with_retry(sock)
sys.stdout.write(cast_string(data))
sock.close()
|
DavidMcDonald1993/ghsom | parameter_tests_edges.py | Python | gpl-2.0 | 7,042 | 0.013206 |
# coding: utf-8
# In[1]:
import os
from shutil import copyfile
import subprocess
from save_embedded_graph27 import main_binary as embed_main
from spearmint_ghsom import main as ghsom_main
import numpy as np
import pickle
from time import time
def save_obj(obj, name):
with open(name + '.pkl', 'wb'... | ng fo e_sg
p = parameter_se | ttings[j]
#ghsom parameters
params = {'w': 0.0001,
'eta': 0.0001,
'sigma': 1,
'e_sg': p,
'e_en': 0.8}
#create directory
dir_string_p = os.path.join(dir_string, str(p))
if not os.path.isd... |
jgruhl/djtokeninput | lib/djtokeninput/__init__.py | Python | mit | 111 | 0 | #!/usr/bin/env pyth | on
from djtokeninput.field | s import TokenField
from djtokeninput.widgets import TokenWidget
|
frankcash/censorship-analyser | dnscompare.py | Python | bsd-3-clause | 3,151 | 0.008569 | # -*- coding: utf-8 -*-
from ooni.utils import log
from twisted.python import usage
from twisted.internet import defer
from ooni.templates import dnst
class UsageOptions(usage.Options):
optParameters = [
['target', 't', None, 'Specify a single hostname to query.'],
['expec... | estException'] = 'unexpected results'
@defer.inlineCallbacks
def test_control_results(self):
"""
Googles 8.8.8.8 server is queried, in order to generate
control data.
"""
results = yield self.performALookup(self.hostname, ("8.8.8.8", 53) | )
if results:
self.report['control_results'] = results
|
robhowley/treetl | tests/test_parent_data_param.py | Python | mit | 1,534 | 0.006519 |
import unittest
class TestParentDataParams(unittest.TestCase):
def setUp(self):
from treetl import Job
self.expected_results = { jn: i+1 for i, jn in enumerate([ 'JobA', 'JobB', 'JobC', 'JobD' ]) }
self.actual_results = { }
def update_actual_results(job):
self.actua... | LoadToDict(Job):
def load(self, **kwargs):
update_actual_results(self)
class JobA(LoadToDict):
def transform(self, **kwargs):
self.transformed_data = 1
class JobB(LoadToDict):
def transform(self, **kwargs):
self.transf... | class JobC(LoadToDict):
def transform(self, a_data=None, b_data=None, **kwargs):
self.transformed_data = a_data + b_data
@Job.dependency(a_data=JobA, c_data=JobC)
class JobD(LoadToDict):
def transform(self, a_data=None, c_data=None, **kwargs):
s... |
nwalters512/the-blue-alliance | helpers/event_simulator.py | Python | mit | 15,162 | 0.001649 | from collections import defaultdict
import copy
import datetime
import json
from appengine_fixture_loader.loader import load_fixture
from google.appengine.ext import ndb
from helpers.event_details_manipulator import EventDetailsManipulator
from helpers.match_helper import MatchHelper
from helpers.match_manipulator im... |
teams.add(team)
if match.has_been_played:
if alliance == match.winning_alliance:
team_wins[team] += 1
elif match.winning_alliance == '':
team_ties[team... | else:
team_losses[team] += 1
rankings = []
for team in sorted(teams):
wins = team_wins[team]
losses = team_losses[team]
ties = team_ties[team]
rankings.append({
'team_key': team,
'record': {
... |
dssg/wikienergy | disaggregator/build/pandas/pandas/tools/plotting.py | Python | mit | 116,674 | 0.000917 | # being a bit too dynamic
# pylint: disable=E1101
import datetime
import warnings
import re
from math import ceil
from collections import namedtuple
from contextlib import contextmanager
from distutils.version import LooseVersion
import numpy as np
from pandas.util.decorators import cache_readonly, deprecate_kwarg
im... | ['h', 'r', 'home'],
'keymap.pan': ['p'],
'keymap.save': ['s'],
'keymap.xscale': ['L', 'k'],
'keymap.yscale': ['l'],
'keymap.zoom': ['o'],
'l | egend.fancybox': True,
'lines.antialiased': True,
'lines.linewidth': 1.0,
'patch.antialiased': True,
'patch.edgecolor': '#EEEEEE',
'patch.facecolor': '#348ABD',
'patch.linewidth': 0.5,
'toolbar': 'toolbar2',
'xtick.color': '#555555',
'xtick.direction': 'in',
'xtick.majo... |
fridex/fabric8-analytics-worker | alembic/versions/e2762a61d34c_upstream_url_can_be_null.py | Python | gpl-3.0 | 1,411 | 0.001417 | """Upstream URL can be null
Revision ID: e2762a61d34c
Revises: f5c853b83d41
Create Date: 2017-07-31 08:41:39.811488
"""
# revision identifiers, used by Alembic.
revision = 'e2762a61d34c'
down_revision = 'f5c853b83d41'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrad... | ,
existing_type=sa.VARCHAR(length=256),
nullable=False)
op.alter_column('api_requests', 'request_digest',
existing_type=sa.VARCHAR(length=128),
nullable=True)
op.alter_column('monitored_upstreams', 'url',
| existing_type=sa.VARCHAR(length=255),
nullable=True)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column('monitored_upstreams', 'url',
existing_type=sa.VARCHAR(length=255),
... |
robinson96/GRAPE | stashy/stashy/admin/users.py | Python | bsd-3-clause | 3,086 | 0.00324 | from ..helpers import ResourceBase, FilteredIterableResource
from ..errors import ok_or_error, response_or_error
from ..compat import update_doc
class | Users(ResourceBase, FilteredIterableResource):
@response_or_error
def add(self, name, password, displayName, emailAddress, addToDefaultGroup=True):
"""
Add a user, returns a dictionary containing information about the newly created user
"""
| data = dict(name=name,
password=password,
displayName=displayName,
emailAddress=emailAddress,
addToDefaultGroup=addToDefaultGroup)
return self._client.post(self.url(), data)
@ok_or_error
def delete(self, user):
... |
Carreau/sphinx_numfig | setup.py | Python | bsd-3-clause | 1,529 | 0.001308 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')
requirem | ents = [
# TODO: put package requirements here
]
test_requirements = [
# TODO: p | ut package test requirements here
]
setup(
name='sphinx_numfig',
version='0.1.0',
description='Python Boilerplate contains all the boilerplate you need to create a Python package.',
long_description=readme + '\n\n' + history,
author='Matthias Bussonnier',
author_email='bussonniermatthias@gmail.... |
rouault/mapnik | tests/python_tests/ogr_test.py | Python | lgpl-2.1 | 4,110 | 0.009978 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from nose.tools import eq_,assert_almost_equal,raises
from utilities import execution_path, run_all
import os, mapnik
def setup():
# All of the paths used are relative, if we run the tests
# from another directory we need to chdir()
os.chdir(execution_path('.'... | ints an annoying error: ERROR 1: Invalid Point object. Missing 'coordinates' member.
#def test_handling_of_null_features():
# ds = mapnik.Ogr(file='../data/json/null_feature.geojson',layer_by_index=0)
# fs = ds.all_features()
# eq_(len(fs),1)
# OGR plugin extent parameter
def test_ogr_... | rc.shp',layer_by_index=0,extent='-1,-1,1,1')
e = ds.envelope()
eq_(e.minx,-1)
eq_(e.miny,-1)
eq_(e.maxx,1)
eq_(e.maxy,1)
def test_ogr_reading_gpx_waypoint():
ds = mapnik.Ogr(file='../data/gpx/empty.gpx',layer='waypoints')
e = ds.envelope()
eq_(e.minx,... |
ccxt/ccxt | python/ccxt/binancecoinm.py | Python | mit | 1,253 | 0.000798 | # -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.binance import binance
class binancecoinm(binance):
def describe(self):
return self.deep_extend(super(binancecoinm... | spot/en',
],
},
'options': {
'defaultType': 'delivery',
'leverageBrackets': None,
},
})
def transfer_in(self, code, amount, params={}):
# transfer from spot wallet to coinm futures wallet
return self.futures... | mount, 4, params)
|
seerjk/reboot06 | 01/exec04.py | Python | mit | 231 | 0 | deposit = 10000
year = 0
interests = 0.0325
# in | terests = 0.10
money = deposit
total_income = 2 * deposit
while money < total_income:
year += 1
money = money*(1+inte | rests)
# print money
print "Need %d years." % year
|
MITPERG/oilsands-mop | run.py | Python | mit | 74 | 0.013514 | # | !/usr/bin/env python
from app impor | t app
app.run(debug=True, port=5000) |
zsh2401/PYCLT | pyclt/res/__init__.py | Python | gpl-3.0 | 211 | 0.015075 | #!/usr/bin/python3
# -*- coding:utf-8 -*-
from pyclt.res.languages import *
import json
import os
def getText(language_type):
'''获取语言字符'' | '
if language_type | =="zh_cn":
return zh_cn()
|
ifduyue/sentry | src/sentry/integrations/__init__.py | Python | bsd-3-clause | 350 | 0 | from __future__ import absolute_import
from .analytics import * # NOQA
from .base import * # | NOQA
from .manager import IntegrationManager # NOQA
default_manager = IntegrationManager()
all = default_manager.all
get = d | efault_manager.get
exists = default_manager.exists
register = default_manager.register
unregister = default_manager.unregister
|
GhostshipSoftware/avaloria | src/utils/dummyrunner/memplot.py | Python | bsd-3-clause | 3,601 | 0.006109 | """
Script that saves memory and idmapper data over time.
Data will be saved to game/logs/memoryusage.log. Note that
the script will append to this file if it already exists.
Call this module directly to plot the log (requires matplotlib and numpy).
"""
import os, sys
import time
sys.path.insert(0, os.path.dirname(os... | l = INTERVAL
self.db.starttime = time.time()
def at_repeat(self):
pid = os.getpid()
rmem = float(os.popen('ps -p %d -o %s | tail -1' % (pid, | "rss")).read()) / 1000.0 # resident memory
vmem = float(os.popen('ps -p %d -o %s | tail -1' % (pid, "vsz")).read()) / 1000.0 # virtual memory
total_num, cachedict = _idmapper.cache_size()
t0 = (time.time() - self.db.starttime) / 60.0 # save in minutes
with open(LOGFILE, "a") as f:
... |
adhoc-dev/odoo-argentina | l10n_ar_account_withholding/models/account_move.py | Python | agpl-3.0 | 1,785 | 0 | from odoo import models, fields
class AccountMove(models.Model):
_inherit = "account.move"
def _get_tax_factor(self):
tax_factor = super()._get_tax_factor()
doc_letter = self.l10n_latam_document_type_id.l10n_ar_letter
# if we receive B invoices, then we take out 21 of vat
# th... | da error
try:
self.env.context.invoice_date = invoice_date
self.env.context.invoice_company = self.compa | ny_id
except Exception:
pass
return super().get_taxes_values()
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
def _compute_price(self):
# ver nota en get_taxes_values
invoice = self.move_id
invoice_date = invoice.invoice_date or fields.... |
jor-/matrix-decomposition | matrix/__init__.py | Python | agpl-3.0 | 1,947 | 0.003082 | # *** submodules *** #
from matrix import constants, decompositions, errors, approximation, nearest
# *** functions *** #
from matrix.calculate import (is_positive_semidefinite, is_positive_definite, is_invertible,
decompose, solve)
# *** constants *** #
from matrix.constants import (... | for sparse matrices. """
# *** version *** #
from ._version import get_versions
__ | version__ = get_versions()['version']
del get_versions
# *** logging *** #
import logging
logger = logging.getLogger(__name__)
del logging
# *** deprecated *** #
def __getattr__(name):
deprecated_names = ['decomposition', 'positive_definite_matrix',
'positive_semidefinite_matrix', 'APP... |
google/telluride_decoding | test/regression_data_test.py | Python | apache-2.0 | 3,840 | 0.001563 | # Copyright 2020 Google 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 writing, ... | ain_data.discover_feature_shapes(test_file)
print('Telluride features:', features)
self.assertIn('eeg', features)
self.assertEqual(features['eeg'].shape, [63])
self.assertIn('intensity', features)
self.assertEqual(features['intensity'].shape, [1])
self.assertEqual(brain_data.count_tfrecords(tes... | r = os.path.join(
flags.FLAGS.test_srcdir, '__main__',
'test_data/')
def test_data_ingestion(self):
cache_dir = os.path.join(self._test_data_dir, 'jens_memory')
tmp_dir = self.create_tempdir().full_path
tf_dir = os.path.join(tmp_dir, 'jens_memory')
num_subjects = 1 # Only 1 of 22 su... |
PeteTheAutomator/ACServerManager | session/migrations/0013_auto_20160904_1252.py | Python | mit | 858 | 0.001166 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('session', '0012_auto_20160904_1130'),
]
oper | ations = [
migrations.AlterField(
model_name='serversetting',
name='minorating_grade',
field=models.CharField(default=b'ABCN', help | _text=b"Minorating Grade required to join this server's sessions (driver proficiency - see http://www.minorating.com/Grades for details)", max_length=8, choices=[(b'A', b'A - exemplary'), (b'AB', b'AB - clean racer (or better)'), (b'ABC', b'ABC - rookie (or better)'), (b'ABCN', b'ABCN - rookie or new/unlisted racers (o... |
ish/wsgiapptools | wsgiapptools/flash.py | Python | bsd-3-clause | 3,252 | 0.002153 | """
"Flash" messaging support.
A "flash" message is a message displayed on a web page that is removed next
request.
"""
__all__ = ['add_message', 'get_messages', 'get_flash',
'flash_middleware_factory']
import itertools
import webob
from wsgiapptools import cookies
ENVIRON_KEY = 'wsgiapptools.flash'
C... | self.request = webob.Request(environ)
self.flashes = []
def add_message(self, message, type=None):
"""
Add a new flas | h message.
Note: this can be called multiple times to set multiple messages. The
messages can be retrieved, using get_messages below, and will be returned
in the order they were added.
"""
if type is None:
type = ''
self.flashes.append('%s:%s'% (type, message... |
hjanime/bcbio-nextgen | bcbio/rnaseq/variation.py | Python | mit | 3,793 | 0.001318 | import os
from bcbio.utils import file_exists
import bcbio.pipeline.datadict as dd
from bcbio.ngsalign.postalign import dedup_bam
from bcbio.distributed.transaction import file_transaction
from bcbio import broad, bam
def rnaseq_gatk_variant_calling(data):
data = dd.set_deduped_bam(data, dedup_bam(dd.get_work_bam... | "-R", ref_file,
"-I", deduped_bam,
"-o", tx_split_bam,
"-rf", "ReassignOneMappingQuality",
"-RMQF", "255",
"-RMQT", "60",
"-rf", "UnmappedRead",
"-U", "ALLOW_N_CIGAR_READS"] + quality_flag... | g(data))
data = dd.set_split_bam(data, split_bam)
return data
def gatk_rnaseq_calling(data):
"""
use GATK to perform variant calling on RNA-seq data
"""
broad_runner = broad.runner_from_config(dd.get_config(data))
ref_file = dd.get_ref_file(data)
split_bam = dd.get_split_bam(data)
o... |
felixcarmona/coveragit | run.py | Python | mit | 128 | 0 | #!/usr/bin/ | env python
from coveragit.application.console import Application
if __name__ == "__main__":
Application( | ).run()
|
USGSDenverPychron/pychron | pychron/extraction_line/extraction_line_manager.py | Python | apache-2.0 | 34,407 | 0.000872 | # ===============================================================================
# Copyright 2011 Jake Ross
#
# 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... | Bool,
on_trait_change,
Str,
Int,
Dict,
File,
Float,
Enum,
)
from pychron.canvas.canvas_editor import CanvasEditor
from pychron.core.file_listener import FileListener
from pychron.core.ui.gui import invoke_in_main_thread
from pychron.core.wait.wait_group import WaitGroup
from pychron.envisag... | tractionLineExplanation,
)
from pychron.extraction_line.extraction_line_canvas import ExtractionLineCanvas
from pychron.extraction_line.graph.extraction_line_graph import ExtractionLineGraph
from pychron.extraction_line.sample_changer import SampleChanger
from pychron.globals import globalv
from pychron.hardware.core.i... |
iancze/Starfish | Starfish/spectrum.py | Python | bsd-3-clause | 9,193 | 0.000979 | import h5py
import numpy as np
from dataclasses import dataclass
from nptyping import NDArray
from typing import Optional
@dataclass
class Order:
"""
A data class to hold astronomical spectra orders.
Parameters
----------
_wave : numpy.ndarray
The full wavelength array
_flux : numpy.n... | [o.sigma for o in self.orders]
return np.asarray(sigmas)
# Unmasked properties
@property
def _waves(self) -> np.ndarray:
_waves = [o._wave for o in self.orders]
return np.asarray(_waves)
@property
def _fluxes(self) -> np.ndarray:
_fluxes = [o._flux for o in self.or... | in self.orders]
return np.asarray(_sigmas)
@property
def masks(self) -> np.ndarray:
"""
np.ndarray: The full 2-dimensional boolean masks
"""
waves = [o.wave for o in self.orders]
return np.asarray(waves)
@property
def shape(self):
"""
num... |
iulian787/spack | var/spack/repos/builtin/packages/bash-completion/package.py | Python | lgpl-2.1 | 1,869 | 0.00214 | # 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)
from spack import *
class BashCompletion(AutotoolsPackage):
"""Programmable completion functions | for ba | sh."""
homepage = "https://github.com/scop/bash-completion"
url = "https://github.com/scop/bash-completion/archive/2.3.tar.gz"
git = "https://github.com/scop/bash-completion.git"
version('develop', branch='master')
version('2.7', sha256='dba2b88c363178622b61258f35d82df64dc8d279359f599e3b... |
lavish205/olympia | src/olympia/compat/views.py | Python | bsd-3-clause | 4,194 | 0.000238 | import json
import re
from django import http
from django.db.models import Count
from django.db.transaction import non_atomic_requests
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from olympia import amo
from olympia.addons.decorators import owner_or_unlisted_reviewer
fro... | fields = [field.name for field in CompatReport._meta.get_fields()]
for key, value in data:
if key in fields:
setattr(report, key, value)
else:
return http.HttpResponseBadRequest()
r | eport.save()
return http.HttpResponse(status=204)
@non_atomic_requests
def reporter(request):
query = request.GET.get('guid')
if query:
qs = None
if query.isdigit():
qs = Addon.objects.filter(id=query)
if not qs:
qs = Addon.objects.filter(slug=query)
... |
grahamking/lintswitch | setup.py | Python | gpl-3.0 | 1,119 | 0 | """To install: sudo python setup.py install
"""
import os
from setuptools import setup, find_packages
def read(fname):
"""Utility function to read the README file."""
return open(os.path.join(os.path.dirname(__file__), fname)).read()
VERSION | = __import__('lintswitch').__version__
setup(
name='lintswitch',
version=VERSION,
author='Graham King',
author_email='[email protected]',
description='Lint your Python in real-time',
long_description=read('README.md'),
packages=find_packages(),
package_data={'lintswitch': ['index.html']}... | hamking/lintswitch',
install_requires=['setuptools'],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Operating System :: OS Independent',
... |
felixonmars/app | lib/vendor/php-rql/docs/scripts/validate_examples.py | Python | gpl-2.0 | 5,917 | 0.003042 | import os
import sys
import yaml
import re
from subprocess import Popen, PIPE, call
from random import randrange
from threading import Thread
import SocketServer
import struct
import pdb
sys.path.insert(0, '/usr/local/lib/python2.6/dist-packages/rethinkdb')
import ql2_pb2 as p
# tree of YAML documents defining docume... | test_case[lang]
else:
test_case = None
if 'validate' in example and not example['validate']:
test_case = None
skip_validation = True
else:
skip | _validation = False
# Check for an override of this test case
if lang in command:
if isinstance(command[lang], bool) and not command[lang]:
test_case = None
elif isinstance(command[lang], dict):
over... |
alexlo03/ansible | lib/ansible/modules/network/avi/avi_trafficcloneprofile.py | Python | gpl-3.0 | 4,161 | 0.000961 | #!/usr/bin/python
#
# @author: Gaurav Rastogi ([email protected])
# Eric Anderson ([email protected])
# module_check: supported
#
# Copyright: (c) 2017 Gaurav Rastogi, <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
ANSIB... | method for object update is HTTP | PUT.
- Setting to patch will override that behavior to use HTTP PATCH.
version_added: "2.5"
default: put
choices: ["put", "patch"]
avi_api_patch_op:
description:
- Patch operation to use when using avi_api_update_method as patch.
version_added: "2.5"
... |
yasserglez/programming-problems | cracking_the_coding_interview/chapter_04/first_common_ancestor.py | Python | mit | 1,764 | 0 | # Interview Question 4.7
class Node(object):
def __init__(self, value):
self.value = value
self.parent = Node
self._left = self._right = | None
@property
def left(self):
return self._left
@left.setter
def left(self, node):
self._left = node
self._left.parent = self
@property
def right(self):
return self._right
@right.setter
def | right(self, node):
self._right = node
self._right.parent = self
def is_ancestor(self, other):
if self is other:
return True
else:
is_ancestor = False
if self.left is not None:
is_ancestor = self.left.is_ancestor(other)
... |
stvstnfrd/edx-platform | common/lib/xmodule/xmodule/assetstore/tests/test_asset_xml.py | Python | agpl-3.0 | 3,718 | 0.001345 | """
Test for asset XML generation / parsing.
"""
import unittest
import pytest
from contracts import ContractNotRespected
from lxml import etree
from opaque_keys.edx.locator import CourseLocator
from path import Path as path
from six.moves import zip
from xmodule.assetstore import AssetMetadata
from xmodule.modules... | ml(a | sset)
asset_md.from_xml(asset)
def test_export_all_assets_to_xml(self):
"""
Export all AssetMetadatas to XML and verify the structure and fields.
"""
root = etree.Element("assets")
AssetMetadata.add_all_assets_as_xml(root, self.course_assets)
# If this line d... |
Dishwishy/beets | beets/ui/__init__.py | Python | mit | 40,331 | 0 | # This file is part of beets.
# Copyright 2015, Adrian Sampson.
#
# 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, ... | irst option is the default; mark it.
show_letter = '[%s]' % found_letter.upper()
is_default = True
else:
show_letter = found_letter.upper()
is_default = False
# Colorize the letter shortcut.
show_letter = colorize('action_default' if is_default el... | o the word.
capitalized.append(
option[:index] + show_letter + option[index + 1:]
)
display_letters.append(found_letter.upper())
first = False
# The default is just the first option if unspecified.
if require:
default = None
elif default is None:
... |
ArtyomSliusar/StorageOfKnowledge | storageofknowledge/manage.py | Python | gpl-3.0 | 364 | 0.002747 | #!/usr/bin/env python
import os
import sys
import dotenv
dotenv | .read_dotenv()
if __name__ == "__main__" | :
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'storageofknowledge.settings')
os.environ.setdefault('DJANGO_CONFIGURATION', 'Settings')
from configurations.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
i3visio/osrframework | osrframework/wrappers/pending/bebee.py | Python | agpl-3.0 | 4,625 | 0.004758 | # !/usr/bin/python
# -*- coding: cp1252 -*-
#
##################################################################################
#
# Copyright 2016-2017 Félix Brezo and Yaiza Rubio (i3visio, [email protected])
#
# This program is part of OSRFramework. You can redistribute it and/or modify
# it under the ter... | ###### | ###
# Strings that will imply that the query number is not appearing
self.notFoundText = {}
#self.notFoundText["phonefy"] = []
self.notFoundText["usufy"] = ['<link rel="canonical" href="https://.bebee.com/bees/search">']
#self.notFoundText["searchfy"] = []
##############... |
iamahuman/angr | angr/knowledge_plugins/cfg/cfg_model.py | Python | bsd-2-clause | 15,139 | 0.003567 | # pylint:disable=no-member
import pickle
import logging
from collections import defaultdict
import networkx
from ...protos import cfg_pb2, primitives_pb2
from ...serializable import Serializable
from ...utils.enums_conv import cfg_jumpkind_to_pb, cfg_jumpkind_from_pb
from ...errors import AngrCFGError
from .cfg_node ... | pend(node)
model.graph.add_node(node)
if len(model._nodes_by_addr[node.block_id]) > 1:
if once("cfg_model_parse_from_cmessage many nodes at addr"):
l.warning("Importing a CFG with more than one node for a given address is currently unsupported. "
... | node at a given address is unsupported, grab the first one
src = model._nodes_by_addr[edge_pb2.src_ea][0]
dst = model._nodes_by_addr[edge_pb2.dst_ea][0]
data = { }
for k, v in edge_pb2.data.items():
data[k] = pickle.loads(v)
data['jumpkind'] = ... |
GzkV/bookstore_project | store/migrations/0001_initial.py | Python | mit | 839 | 0.002384 | # -*- coding: utf-8 -*-
# Generated by Django 1 | .9 on 2016-01-26 02:11
from __future__ import unicode_literals
import datetime
from django.db im | port migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Book',
fields=[
('id', models.AutoField(auto_created=True, primary_key=... |
CraigHarris/gpdb | src/test/tinc/tincrepo/mpp/models/test/sql_related/test_sql_tc_42.py | Python | apache-2.0 | 1,931 | 0.001554 | """
Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved.
This program and the accompanying materials are made available under
the terms of the 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
... | ific language governing permissions and
limitations under the License.
"""
import unittest2 as unittest
from mpp.models.mpp_tc import _MPPMetaClassType
from mpp.models.mpp_tc import MPPDUT
from mpp.models import SQLTestCase, SQLTestCaseException
from mpp.models.sql_tc import __gpdbSQLTestCase__, __hawqSQLTestCase__
... | MockMPPMetaClassTypeGPDB42(_MPPMetaClassType):
_MPPMetaClassType.DUT = MPPDUT('gpdb', '4.2')
@unittest.skip('mock')
class MockSQLTestCaseGPDB42(SQLTestCase):
__metaclass__ = MockMPPMetaClassTypeGPDB42
def test_do_stuff(self):
(product, version) = self.get_product_version()
self.assertEqual... |
Liamc0950/EcosystemSimulator | utils.py | Python | gpl-2.0 | 5,066 | 0.010265 | import pygame, sys, random, math
from pygame.locals import *
import organisms
import globalVars
class Graphics:
def __init__(self):
self.screen = pygame.display.set_mode((1080, 820))
pygame.display.set_caption('Ecosystem Simulator')
class GUI:
def __init__(self):
self.sliderX = 150
... | >= 50:
self.sliderX += delta
globalVars.simSpeed = self.sliderX - 50
def act(self):
self.sliderDrag()
self.mouseX = pygame.mouse.get_pos()[0]
self.render()
class HUD:
def __init__(self, world):
#World
self.world = wo... | vent.get()
if pygame.mouse.get_pressed()[0] == True:
for veg in self.world.vegetation:
if self.mouseClicked(veg):
self.target = veg
return
for prey in self.world.prey:
if self.mouseClicked(prey):
... |
txtbits/daw-python | primeros ejercicios/Ejercicios entradasalida/ejercicio2.py | Python | mit | 470 | 0.002128 | # Escribir un programa que pregunte al usuario dos números y luego muestre la suma, el producto | y la media de los dos números
numero = raw_input('Elige un numero ')
numero2 = raw_input('Elige otro numero ')
numero = int(numero)
numero2 = int(numero2)
print 'La suma de los numeros es: ', numero + numero2
print 'El producto de los numeros es: ', numero * numero2
print 'La media de los numeros es: ', (numero+numero2... | a finalizar')
|
yongfuyang/vnpy | vn.trader/ctaAlgo/strategyAtrRsi2.py | Python | mit | 12,056 | 0.003283 | # encoding: UTF-8
"""
一个ATR-RSI指标结合的交易策略,适合用在股指的1分钟和5分钟线上。
注意事项:
1. 作者不对交易盈利做任何保证,策略代码仅供参考
2. 本策略需要用到talib,没有安装的用户请先参考www.vnpy.org上的教程安装
3. 将IF0000_1min.csv用ctaHistoryData.py导入MongoDB后,直接运行本文件即可回测策略
"""
from ctaBase import *
from ctaTemplate import CtaTemplate
import talib
import numpy as np
#####################... | 均线的窗口数
rsiLength = 5 # 计算RSI的窗口数
rsiEntry = 16 # RSI的开仓信号
trailingPercent = 1.0 # 百分比移动止损
initDays = 10 # 初始化数据所用的天数
fixedSize = 1 # risk
useTrailingStop = False # 是否使用跟踪止损
profitLock = 30 # 利润锁定
trailingStop = 20 # 跟踪止损
# 策略变量... | 需要缓存的数据的大小
bufferCount = 0 # 目前已经缓存了的数据的计数
highArray = np.zeros(bufferSize) # K线最高价的数组
lowArray = np.zeros(bufferSize) # K线最低价的数组
closeArray = np.zeros(bufferSize) # K线收盘价的数组
atrCount = 0 # 目前已经缓存了的ATR的计数
atrArray = np.zeros(bufferSize) # ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.