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 |
|---|---|---|---|---|---|---|---|---|
hlin/django-auth-krb | setup.py | Python | mit | 1,133 | 0 | #!/usr/bin/env python
from setuptools import setup, find_packages
from django_auth_krb import get_version
setup(
name="django_auth_krb",
version=get_version(),
description="Django kerberos authentication backend",
long_description=open('README.rst').read(),
url="https://github.com/hlin/django-auth... | nse",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Software Development :: Libraries :: Python Modules",
],
keywords=["django", "kerberos", "krb5", "authentication", "auth"],
packages | =find_packages(exclude='tests'),
include_package_data=True,
install_requires=[
'Django>=1.10.1',
],
zip_safe=False,
)
|
ThunderGemios10/The-Super-Duper-Script-Editor | ui_fontgenerator.py | Python | gpl-3.0 | 13,740 | 0.003712 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'qt\ui\fontgen.ui'
#
# Created: Mon Jun 03 01:17:17 2013
# by: PyQt4 UI code generator 4.8.5
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except A... | QtGui.QApplication.UnicodeUTF8))
self.btnNew.setAutoDefault(False)
self.btnNew.setObjectName(_fromUtf8("btnNew"))
self.horizontalLayout_2.addWidget(self.btnNew)
self.btnSave = QtGui.QPushButton(FontGenerator)
self.btnSave.setText(QtGui.QApplication.translate("FontGenerator", "&S... | map(_fromUtf8(":/disk.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.btnSave.setIcon(icon2)
self.btnSave.setShortcut(QtGui.QApplication.translate("FontGenerator", "Ctrl+S", None, QtGui.QApplication.UnicodeUTF8))
self.btnSave.setAutoDefault(False)
self.btnSave.setObjectName(_fromUtf8("... |
TaskEvolution/Task-Coach-Evolution | taskcoach/tests/disttests/win32/sendinput/setup.py | Python | gpl-3.0 | 959 | 0 | '''
Task Coach - Your friendly task manager
Copyright (C) 2004-2013 Task Coach developers <[email protected]>
Task Coach 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 Licens... | from distutils.core import setup, Extension
setup(name='sendinput',
ext_modules=[Extension('sendinput', ['sendinput.c'],
| define_macros=[('_WIN32_WINNT', '0x0502')])])
|
Designist/pybuilder | src/main/python/pybuilder/errors.py | Python | apache-2.0 | 3,860 | 0.002332 | # -*- coding: utf-8 -*-
#
# This file is part of PyBuilder
#
# Copyright 20 | 11-2015 PyBuilder Team
#
# | 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
# distribute... |
OPM/ResInsight | ThirdParty/Ert/python/ecl/util/util/version.py | Python | gpl-3.0 | 3,470 | 0.011816 | from ecl import EclPrototype
def cmp_method(method):
def cmp_wrapper(self, other):
if not isinstance(other, Version):
other = Version(other[0], other[1], other[2])
return method(self, other)
return cmp_wrapper
class Version(object):
def __init__(self, major, minor, micro... | self.git_commit
class EclVersion(Version):
_build_time = EclPrototype("char* ecl_version_get_build_time()", bind = False)
_git_commit = EclPrototype("char* ecl_version_get_git_commit()", bind = False)
_major_version = EclPrototype("int ecl_version_get_major_version()", bind = False)
_minor_version = E... | on_get_minor_version()", bind = False)
_micro_version = EclPrototype("char* ecl_version_get_micro_version()", bind = False)
_is_devel = EclPrototype("bool ecl_version_is_devel_version()", bind = False)
def __init__(self):
major = self._major_version( )
minor = self._minor_version( )
... |
kelvindk/Video-Stabilization | boost_1_42_0/tools/regression/src/regression.py | Python | gpl-3.0 | 36,064 | 0.027091 | #!/usr/bin/python
# Copyright MetaCommunications, Inc. 2003-2007
# Copyright Redshift Software, Inc. 2007
#
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
import glob
import optparse
import os
import os.path
impo... | ptions',
help="options to pass to the regression test" )
opt.add_o | ption( '--bjam-toolset',
help="bootstrap toolset for 'bjam' executable" )
opt.add_option( '--pjl-toolset',
help="bootstrap toolset for 'process_jam_log' executable" )
opt.add_option( '--platform' )
#~ Source Options:
opt.add_option( '--user',
help="Bo... |
stefanbraun-private/pyVisiToolkit | src/trend/datasource/trendExpression.py | Python | gpl-3.0 | 10,667 | 0.023156 | #!/usr/bin/env python
# encoding: utf-8
"""
trend.datasource.trendExpression.py
Evaluate trenddata expressions
Copyright (C) 2017 Stefan Braun
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, eithe... | y of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
DEBUGGING = True
import datetime
import misc.timezone as timezone
from trend.datasource.trendInterpolation import Interpolation
from operator import itemgetter
import collections
import sys
class Variable(ob... | _int, value_type_int):
self._interpolation = Interpolation(projectpath_str, dms_dp_str, interpolation_type_int)
self._var_name_str = var_name_str
self._value_type_int = value_type_int
def get_interpolation(self):
return self._interpolation
def get_var_name(self):
return self._var_name_str
def get_value(... |
anhstudios/swganh | data/scripts/templates/object/weapon/melee/2h_sword/crafted_saber/shared_sword_lightsaber_two_handed_s6_gen2.py | Python | mit | 501 | 0.043912 | #### NOTICE: THIS FILE IS AUT | OGENERATED
#### MODIFICATIO | NS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Weapon()
result.template = "object/weapon/melee/2h_sword/crafted_saber/shared_sword_lightsaber_two_handed_s6_gen2.iff"
result.attribute_template_id = 10
result.stfName(... |
tcp813/tolo | settings/constants.py | Python | mit | 18 | 0.055556 | ZOOM_NORMAL = 1.0 | ||
mruddy/bitcoin | test/functional/mempool_accept.py | Python | mit | 16,115 | 0.004034 | #!/usr/bin/env python3
# Copyright (c) 2017-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 mempool acceptance of raw transactions."""
from decimal import Decimal
import math
from test_fra... | outputs=[{node.getnewaddress(): 0.3}, {node.getnewaddress(): 49}],
))['hex']
txid_in_block = node.sendrawtransaction(hexstring=raw_tx_in_block, maxfeerate=0)
node.generate(1)
self.mempool_size = | 0
self.check_mempool_result(
result_expected=[{'txid': txid_in_block, 'allowed': False, 'reject-reason': 'txn-already-known'}],
rawtxs=[raw_tx_in_block],
)
self.log.info('A transaction not in the mempool')
fee = Decimal('0.000007')
raw_tx_0 = node.signra... |
abhikeshav/ydk-py | cisco-ios-xr/ydk/models/cisco_ios_xr/_meta/_Cisco_IOS_XR_controller_optics_oper.py | Python | apache-2.0 | 95,722 | 0.016203 |
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... | pticsOper.OpticsPorts.OpticsPort.OpticsDwdmCarrrierChannelMap.DwdmCarrierMapInfo',
False,
[
_MetaInfoClassMember('frequency', ATTRIBUTE, 'str' , None, None,
[(0, 32)], [],
''' Frequency
''',
'frequency'... | 3647)], [],
''' G694 channel number
''',
'g694_chan_num',
'Cisco-IOS-XR-controller-optics-oper', False),
_MetaInfoClassMember('itu-chan-num', ATTRIBUTE, 'int' , None, None,
[(0, 4294967295)], [],
... |
Eric89GXL/scipy | scipy/optimize/minpack.py | Python | bsd-3-clause | 33,497 | 0.000269 | from __future__ import division, print_function, absolute_import
import threading
import warnings
from . import _minpack
import numpy as np
from numpy import (atleast_1d, dot, take, triu, shape, eye,
transpose, zeros, product, greater, array,
all, where, isscalar, asarray, inf, a... | def fsolve(func, x0, args=(), fprime=None, full_output=0,
col_deriv=0, xtol=1.49012e-8, maxfev=0, band=None,
epsfcn=None, factor=100, diag=None):
"""
Find the roots of a function.
|
Return the roots of the (non-linear) equations defined by
``func(x) = 0`` given a starting estimate.
Parameters
----------
func : callable ``f(x, *args)``
A function that takes at least one (possibly vector) argument,
and returns a value of the same length.
x0 : ndarray
... |
london-python-project-nights/romaine | test_data/steps/some_steps.py | Python | mit | 444 | 0 | from romaine.steps import Give | n, When, Then, Step, And
@Given('step_1')
def step_1():
pass
@When('step_2')
def step_2():
pass
@Then('step_3')
def step_3():
pass
@And('step_4')
def step_4():
pass
@Step('step_5')
def step_5():
pass
@Given('Given step_6')
def step_6():
pass
@When('When step_7')
def step_7():
p... | ep_8')
def step_8():
pass
@And('And step_9')
def step_9():
pass
|
jjcamp/mdgt | mdgt/launcher.py | Python | mit | 3,287 | 0.000304 | import argparse
import configparser
import sys
from io import StringIO
from pathlib import Path
from .mdgt import consolePrint, jsonPrint, listProvs
from .provider import Provider
from .webserve import serve as webserve
def setup_parser():
'''Initialize the argument parser.
Returns:
ArgumentParser in... | lable providers and exit.")
# These arguments affect the output and are exclusive
outputGroup = parser.add_mutually_exclusive_group()
outputGroup.add_argument('-c', '--console', action='store_true',
help="Output console-formatted text (default).")
outputGroup.add_argument('... | , '--json', action='store_true',
help="Output json.")
outputGroup.add_argument('-pd', '--provider-dir', nargs='?', const=None,
help="Directory that contains provider files.")
outputGroup.add_argument('-w', '--webserver', nargs='?', const=8181,
... |
valeros/platformio | scripts/mbed_to_package.py | Python | apache-2.0 | 4,191 | 0.000477 | # Copyright 2014-2016 Ivan Kravets <[email protected]>
#
# Licensed under the Apach | e 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 under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific langu... |
EnTeQuAk/dotfiles | sublime-text-3/Packages/HTML-CSS-JS Prettify/src/py/utils/env_utils.py | Python | unlicense | 2,798 | 0.000357 | # 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/.
"""Various utility functions used by this plugin"""
import subprocess
from os import environ, devnull
from os.path impor... | "
node = get_pref("node_path").get(PLATFORM)
return expanduser(node)
def run_command(args):
"""Runs a command in a shell and returns the output"""
popen_args = {
"stdout": subprocess.PIPE,
"stderr": subprocess.PIPE,
"env": environ,
}
if PLATFORM == "win | dows":
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
popen_args["startupinfo"] = startupinfo
popen_args["stdin"] = open(devnull, 'wb')
stdout, stderr = subprocess.Popen(args, **popen_args).communicate()
if stderr:
if b"Expe... |
kennknowles/python-rightarrow | tests/samples/literal_int.py | Python | apache-2.0 | 8 | 0 | 3 | 48593 | 0
|
BlogForever/crawler | bibcrawl/model/objectitem.py | Python | mit | 888 | 0.006757 | """Super class of comment and post item"""
from scrapy.item import Item
class ObjectItem(Item):
"""Extends Scrapy Item interface to be usable with the standard object
attribute notation.
>>> from scrapy.item import Field
>>> cl | ass I(ObjectItem):
... myField = Field()
>>> i = I()
>>> i.myField = 1
>>> i.myField
1
>>> try:
... i.notAField
... except KeyError:
... pass
... else:
... fail
"""
def __setattr__(self, key, value):
"""Sets a fild of the item using object attribute notation.... | value)
def __getattr__(self, key):
"""Gets a fild of the item using object attribute notation."""
# This is enough because __getattr__ is a fallback...
return self[key]
|
OCA/hr | hr_employee_ppe/models/hr_personal_equipment_request.py | Python | agpl-3.0 | 786 | 0 | # Copyright 2021 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class HrPersonalEquipmentRequest(models.Model):
_inherit = "hr.personal.equipment.request"
contains_ppe = fields.Boolean(compute="_compute_contains_ppe")
def _compute_contains_p... | f action_view_ppe_report(self):
report = self.env["ir.actions.report"]._get_report_from_name(
"hr_employee_ppe.hr_employee_ppe_report_template"
)
return report.report_action(self) | |
memnonila/art | art/asgi.py | Python | mit | 146 | 0 | impo | rt os
import channels.asgi
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'art.settings')
channel_layer = channels.asgi.get_channel_lay | er()
|
207leftovers/cs207project | pype/driver.py | Python | mit | 130 | 0.007692 | #!/usr/bin/env python3
#import pype
impo | rt sys
from pype. | pipeline import *
for fname in sys.argv[1:]:
Pipeline(source=fname)
|
mbakker7/ttim | ttim/aquifer.py | Python | mit | 8,387 | 0.007512 | import numpy as np
import matplotlib.pyplot as plt
import inspect # Used for storing the input
class AquiferData:
def __init__(self, model, kaq, z, Haq, Hll, c, Saq, Sll, poraq, porll,
ltype, topboundary, phreatictop, kzoverkh=None, model3d=False):
'''kzoverkh and model3d only need to be ... | ]))[0, 0]
layernumber = self.layernumber[modellayer]
ltype = self.ltype[modellayer]
return layernumber, ltype, modellayer
class Aquifer(AquiferData):
def __init__(self, model, kaq, z, Haq, Hll, c, Saq, Sll, poraq, porll,
ltype, topboundary, phreatictop, kzover... | poraq, porll, ltype, topboundary, phreatictop, kzoverkh, model3d)
self.inhomlist = []
self.area = 1e300 # Needed to find smallest inhomogeneity
def __repr__(self):
return 'Background Aquifer T: ' + str(self.T)
def initialize(self):
AquiferData.initialize(self... |
isandlaTech/cohorte-demos | spellchecker/python/repo/spellchecker/spell_dictionary_EN.py | Python | apache-2.0 | 1,902 | 0.003155 | #!/usr/bin/python
#-- Content-Encoding: UTF-8 --
"""
This bundle provides a component that is a simple implementation of the
Dictionary service. It contains some English words.
:authors: Shadi Abras, Thomas Calmant
:copyright: Copyright 2013, isandlaTech
:license: Apache Software License 2.0
"""
# iPOPO decorators
f... | English dictionary
@Property("_language","language","EN")
class SpellDictionary(object):
"""
Implementation of a spell dictionary, for French language.
"""
def __init__(self):
"""
Declares | members, to respect PEP-8.
"""
self.dictionary = None
@Validate
def validate(self, context):
"""
The component is validated. This method is called right before the
provided service is registered to the framework.
"""
_logger.info("SpellDictionary EN vali... |
mtzirkel/leakyskiff | quiz/multichoice/migrations/0001_initial.py | Python | mit | 1,525 | 0.002623 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-12-02 05:16
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrati | ons.CreateModel(
name='MCAnswer',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_na | me='ID')),
('correct', models.BooleanField(default=False)),
],
),
migrations.CreateModel(
name='MCChoice',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('cho... |
openstack/vitrage | vitrage/tests/unit/datasources/test_transformer_base.py | Python | apache-2.0 | 1,151 | 0 | # Copyright 2017 - Nokia
#
# 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, sof... | est(base.BaseTest):
def _validate_base_vertex_props(self,
vertex,
| expected_name,
expected_datasource_name):
self.assertFalse(vertex[VProps.VITRAGE_IS_PLACEHOLDER])
self.assertEqual(expected_datasource_name, vertex[VProps.VITRAGE_TYPE])
self.assertEqual(expected_name, vertex[VProps.NAME])
|
mirror/vbox | src/VBox/ValidationKit/tests/benchmarks/tdBenchmark1.py | Python | gpl-2.0 | 3,405 | 0.015565 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id$
"""
VirtualBox Validation Kit - Test that runs various benchmarks.
"""
__copyright__ = \
"""
Copyright (C) 2010-2014 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free softwa... | , but WITHOUT ANY WARRANTY of any kind.
The contents of this file may alternatively be used under the terms
of the Common Development and Distribution License Version 1.0
(CDDL) only, as it comes in the "COPYING.CDDL" file of the
VirtualBox OSE distribution, in which case the provisions of the
CDDL are applicable inst... | "
# Standard Python imports.
import os;
import sys;
# Only the main script needs to modify the path.
try: __file__
except: __file__ = sys.argv[0];
g_ksValidationKitDir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))));
sys.path.append(g_ksValidationKitDir);
# Validation Kit imports.
... |
hovel/pybbm | pybb/signals.py | Python | bsd-2-clause | 3,815 | 0.003145 | # coding=utf-8
from __future__ import unicode_literals
from django.contrib.au | th.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_save, post_delete, pre_save
from pybb.models import Post, Category, Topic, Forum, create_or_check_slug
from pybb.subscription import notify_topic_subscribers, notify_forum_subscribers
from py... | aults, compat
from pybb.permissions import perms
def topic_saved(instance, **kwargs):
if kwargs['created']:
notify_forum_subscribers(instance)
def post_saved(instance, **kwargs):
# signal triggered by loaddata command, ignore
if kwargs.get('raw', False):
return
if getattr(instance, '... |
nish10z/CONCUSS | lib/pattern_counting/double_count/color_count.py | Python | bsd-3-clause | 2,244 | 0 | #
# This file is part of CONCUSS, https://github.com/theoryinpractice/concuss/,
# and is Copyright (C) North Carolina State University, 2015. It is licensed
# under the three-clause BSD license; see LICENSE.
#
from collections import Counter
from count_combiner import CountCombiner
class ColorCount(CountCombiner):... | nt, we simply add all the entries in totals.
"""
def __init__(self, p, coloring, table_hints, td, execdata_file=None):
"""Create tables for keeping track of the separate counts"""
super(ColorCount, self).__init__(p, coloring, table_hints, td)
self.totals = Counter()
self.raw_cou... | rs = None
from lib.pattern_counting.dp import ColorDPTable
self.table_type = ColorDPTable
def table(self, G):
"""Make an appropriate DPTable, given the hints specified"""
return self.table_type(G, reuse=self.table_hints['reuse'])
def before_color_set(self, colors):
"""C... |
google-research/federated | compressed_communication/aggregators/stdev_weights.py | Python | apache-2.0 | 3,289 | 0.005473 | # 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, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A tff.aggregator for tracking th... | f.aggregators.UnweightedAggregationFactory):
r"""Aggregator reporting the standard deviation of client weights as a metric.
The created tff.templates.AggregationProcess sums values placed at CLIENTS,
and outputs the sum placed at SERVER.
The process has empty state and returns the standard deviation over clie... |
rodrigocnascimento/django-teste | product/migrations/0010_auto_20170324_1304.py | Python | mit | 1,504 | 0.001995 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-24 16:04
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_depende... | default=False,
),
migrations.AddField(
model_name='sale',
name='product',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCAD | E, to='product.Product'),
),
migrations.AddField(
model_name='sale',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
|
sdrogers/ms2ldaviz | ms2ldaviz/add_topic_dict_beer3.py | Python | mit | 579 | 0.032815 | import pickle
import numpy as np
import sys
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ms2ldaviz.settings")
import django
django.setup()
import jsonpickle
from basi | cviz.models import Experiment,Mass2Motif
if __name__ == '__main__':
with open('/Users/simon/git/lda/notebooks/beer3.dict','r') as f:
lda = pickle.load(f)
experiment = Experiment.objects.get(name='beer3')
for m2m in lda['topic_metadata']:
motif = Mass2Motif.objects.get(name = m2m,experiment=exp | eriment)
motif.metadata = jsonpickle.encode(lda['topic_metadata'][m2m])
motif.save()
|
LBenzahia/cltk | cltk/corpus/old_norse/runes.py | Python | mit | 8,337 | 0.003377 | """
Sources:
- Viking Language 1 by Jessie L. Byock 2013
Unicode: 16A0–16FF
"""
from enum import Enum, auto
__author__ = ["Clément Besnier <[email protected]>", ]
POINT = "᛫"
SEMI_COLUMN = "\u16EC"
class AutoName(Enum):
def _generate_next_value_(name, a, b, d):
return name
class RunicAlphabetNa... | OUNGER_FUTHARK = [
Rune(RunicAlphabetName.short_twig_younger_futhark, "\u16A0", "f", "f", "fehu"),
Rune(RunicAlphabetName.short_twig_younger_futhark, "\u16A2", "u", "u", "uruz"),
Rune(RunicAlphabetName.short_twig_younger_futhark, "\u16A6", "θ", "þ", "þuriaz"),
Rune(RunicAlphabetName.short_twig_younger_f... | wig_younger_futhark, "\u16B1", "r", "r", "raido"),
Rune(RunicAlphabetName.short_twig_younger_futhark, "\u16B4", "k", "k", "kaunan"),
Rune(RunicAlphabetName.short_twig_younger_futhark, "\u16BD", "h", "h", "haglaz"),
Rune(RunicAlphabetName.short_twig_younger_futhark, "\u16BF", "n", "n", "naudiz"),
Rune(R... |
PereBal/advanced-algorithms | nqueens/controller.py | Python | mit | 2,927 | 0.000342 | import os
import json
from base import BaseController
from nqueens.models import Piece, Panel, Meta
class NQueensController(BaseController):
def __init__(self, view):
super(NQueensController, self)
self._piece_data = None
self._piece_cache = None
self.view = view
@classmethod... | .view.notify({
'func': 'update_panel',
'data': {
'pieces': {},
}
})
res = s | elf.run(panel, pieces, idx=0, ci=0)
if res:
self.view.notify({
'func': 'update_panel',
'data': {
'pieces': panel.pieces,
}
})
else:
self.view.notify({
'func': 'display_error',
... |
mrknow/filmkodi | plugin.video.fanfilm/resources/lib/resolvers/sawlive.py | Python | apache-2.0 | 2,023 | 0.009392 | # -*- coding: utf-8 -*-
'''
FanFilm Add-on
Copyright (C) 2015 lambda
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 ... | 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/>.
'''
import re,urllib,urlparse,base64
from resources.lib.libraries import client
from resources.lib.libraries import jsunpack
... | resolve(url):
try:
page = re.compile('//.+?/(?:embed|v)/([0-9a-zA-Z-_]+)').findall(url)[0]
page = 'http://sawlive.tv/embed/%s' % page
try: referer = urlparse.parse_qs(urlparse.urlparse(url).query)['referer'][0]
except: referer = page
result = client.request(page, referer=re... |
habibmasuro/django-wiki | wiki/migrations/0009_auto__add_field_imagerevision_width__add_field_imagerevision_height.py | Python | gpl-3.0 | 18,186 | 0.008083 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
try:
from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
user_orm_label... | els.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields... | 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
... |
aglitke/vdsm | vdsm/vm.py | Python | gpl-2.0 | 198,643 | 0.000252 | #
# Copyright 2008-2013 Red Hat, 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed ... | = 'video'
SOUND_DEVICES = 'sound'
CONTROLLER_DEVICES = 'controller'
GENERAL_DEVICES = 'general'
BALLOON_DEVICES = 'balloon'
REDIR_DEVICES = 'redir'
WATCHDOG_DEVICES = 'watchdog'
CONSOLE_DEVICES = 'console'
SMARTCARD_DEVICES = 'smartcard'
def isVdsmImage(drive):
return all(k in drive.keys() for k in ('volumeID', '... | f _filterSnappableDiskDevices(diskDeviceXmlElements):
return filter(lambda(x): not(x.getAttribute('device')) or
x.getAttribute('device') in ['disk', 'lun'],
diskDeviceXmlElements)
class _MigrationError(RuntimeError):
pass
class MigrationSourceThread(threading.... |
jayme-github/CouchPotatoServer | couchpotato/core/_base/updater/main.py | Python | gpl-3.0 | 14,024 | 0.005134 | from couchpotato.api import addApiView
from couchpotato.core.event import addEvent, fireEvent, fireEventAsync
from couchpotato.core.helpers.encoding import ss
from couchpotato.core.helpers.request import jsonified
from couchpotato.core.logger import CPLog
from couchpotato.core.plugins.base import Plugin
from couchpotat... |
'hash': output.hash[:8],
'date': output.getDate(),
'type': 'git',
| }
except Exception, e:
log.error('Failed using GIT updater, running from source, you need to have GIT installed. %s', e)
return 'No GIT'
return self.version
def check(self):
if self.update_version:
return True
log.info('C... |
HazyTeam/platform_external_wpa_supplicant_8 | wpa_supplicant/examples/p2p-nfc.py | Python | gpl-2.0 | 20,200 | 0.002277 | #!/usr/bin/python
#
# Example nfcpy to wpa_supplicant wrapper for P2P NFC operations
# Copyright (c) 2012-2013, Jouni Malinen <[email protected]>
#
# This software may be distributed under the terms of the BSD license.
# See README for more details.
import os
import sys
import time
import random
import threading
import argparse... | se
return True
def wpas_get_handover_req():
wpas = wpas_connect()
if (wpas == None):
return None
res = wpas.request("NFC_GET_HANDOVER_REQ NDEF P2P-CR").rstrip()
if "FAIL" in res:
return None
return res.decode("hex")
def wpas_get_handover_req_wps():
wpas = wpas_connect()
... | None
return res.decode("hex")
def wpas_get_handover_sel(tag=False):
wpas = wpas_connect()
if (wpas == None):
return None
if tag:
res = wpas.request("NFC_GET_HANDOVER_SEL NDEF P2P-CR-TAG").rstrip()
else:
res = wpas.request("NFC_GET_HANDOVER_SEL NDEF P2P-CR").rstrip()
if "FAIL"... |
samuelmaudo/yepes | yepes/contrib/thumbnails/models.py | Python | bsd-3-clause | 455 | 0.010989 | # -*- codi | ng:utf-8 -*-
from yepes.apps import apps
AbstractConfiguration = apps.get_class('thumbnails.abstract_models', 'AbstractConfiguration')
AbstractSource = apps.get_class('thumbnails.abs | tract_models', 'AbstractSource')
AbstractThumbnail = apps.get_class('thumbnails.abstract_models', 'AbstractThumbnail')
class Configuration(AbstractConfiguration):
pass
class Source(AbstractSource):
pass
class Thumbnail(AbstractThumbnail):
pass
|
dpnova/pynerstat | minerstat/tests/test_minerstat.py | Python | apache-2.0 | 2,307 | 0 | from twisted.trial import unittest
from minerstat.service import MinerStatService
from minerstat.rig import Rig
from minerstat.remote import MinerStatRemoteProtocol, Command
from minerstat.utils import Config
from minerstat.miners.claymore import EthClaymoreMiner
from twisted.internet import task, defer
from mock impor... | yield self.service.startService()
self.service.rig.start.assert_called_with()
yield self.service.stopService()
self.service.rig.stop.assert_called_with()
class MinerStatRemoteProtocolTest(unittest.TestCase):
def setUp(self):
self.config = Config("a", "b", "w", "p")
... |
pass
def test_algo_check(self):
pass
def test_dispatch_remote_command(self):
pass
def test_poll_remote(self):
pass
def test_make_full_url(self):
print(self.prot.make_full_url("foobar"))
class CommandTest(unittest.TestCase):
def test_init(self):
... |
google-research/exoplanet-ml | exoplanet-ml/astrowavenet/astrowavenet_model_test.py | Python | apache-2.0 | 33,881 | 0.002952 | # Copyright 2018 The Exoplanet ML Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | e=tf.float32,
shape=[None, time_series_length, context_num_features],
name="context")
features = {
"autoregressive_input": input_placeholder,
"conditioning_stack": context_placeholder
}
mode = tf.estimator.ModeKeys.TRAIN
hparams = configdict.ConfigDict({
"use_futu... | skip_output_dim": 6,
"preprocess_output_size": 3,
"preprocess_kernel_width": 5,
"num_residual_blocks": 2,
"dilation_rates": [1, 2, 4],
"output_distribution": {
"type": "normal",
"min_scale": 0.001,
"predict_outlier_distribution": False
... |
executablebooks/mdformat | src/mdformat/renderer/_context.py | Python | mit | 22,558 | 0.000576 | from __future__ import annotations
from collections import defaultdict
from collections.abc import Generator, Iterable, Mapping, MutableMapping
from contextlib import contextmanager
import logging
import re
import textwrap
from types import MappingProxyType
from typing import TYPE_CHECKING, Any, NamedTuple
from markd... | stripping the raw HTML and Markdown get unaligned and
# semantic may change.
content = content.lstrip()
return content
def html_inline(node: RenderTreeNode, context: RenderContext) -> str:
return node.conten | t
def _in_block(block_name: str, node: RenderTreeNode) -> bool:
while node.parent:
if node.parent.type == block_name:
return True
node = node.parent
return False
def hardbreak(node: RenderTreeNode, context: RenderContext) -> str:
if _in_block("heading", node):
return ... |
dmerejkowsky/twittback | twittback/types.py | Python | mit | 130 | 0 | import typing
import twittback
TweetSequence = | typing.Sequence[twittback.Tweet]
UserSeque | nce = typing.Sequence[twittback.User]
|
xychu/product-definition-center | pdc/settings.py | Python | mit | 10,354 | 0.000676 | #
# Copyright (c) 2015 Red Hat
# Licensed under The MIT License (MIT)
# http://opensource.org/licenses/MIT
#
"""
Django settings for pdc project.
Generated by 'django-admin startproject' using Django 1.8.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full lis... | mplate.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, "pdc/templates"),
os.path.join(os.path.dirname(kobo.__file__), "hub", "templates"),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.con... |
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'kobo.django.menu.context_processors.menu_context_processor',
],
},
},
]
WSGI_APPLICATION = 'pdc.wsgi.application'
# Database
# https://docs.d... |
wangy1931/tcollector | collectors/etc/zfsiostats_conf.py | Python | lgpl-3.0 | 298 | 0.006711 | #!/usr/bin/env python
def get | _config():
config = {
'collection_interval': 15, # Seconds, how often to collect metric data
'report_capacity_every_x_times': 20 # Avoid reporting capacity info too frequently, 0 di | sables capacity reporting
}
return config
|
sshnaidm/ru | plugin.audio.tuneinradio/resources/lib/tunein.py | Python | gpl-2.0 | 40,322 | 0.002505 | #/*
# *
# * TuneIn Radio for XBMC.
# *
# * Copyright (C) 2013 Brian Hornsby
# *
# * 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... | streams.append(subnode.getAttribute('HREF'))
f.close()
return streams
def __parse_m3u(self, url):
self.log_debug('__parse_m3u')
self.log_debug('url: %s' % url)
streams = []
req = urllib2.Request(url)
f = urllib2.urlopen(req)
for line in f:
... | |
TheTimmy/spack | var/spack/repos/builtin/packages/saws/package.py | Python | lgpl-2.1 | 1,762 | 0 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-64... | received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, M | A 02111-1307 USA
##############################################################################
from spack import *
class Saws(AutotoolsPackage):
"""The Scientific Application Web server (SAWs) turns any C or C++
scientific or engineering application code into a webserver,
allowing one to examine (a... |
openfisca/openfisca-tunisia | openfisca_tunisia/model/revenus/autres_revenus.py | Python | agpl-3.0 | 1,059 | 0 | # -*- coding: utf-8 -*-
from openfisca_tunisia.model.base import *
# Autres revenus
class salaire_etranger(Variable):
value_type = int
label = "Salaires perçus à l'étranger"
entity = Individu
definition_period = YEAR
class pension_etranger_non_transferee(Variable):
value_type = int
label ... | (transférées en Tunisie)"
entity = Individu
definition_period = YEAR
class autres_revenus_etranger(Variable):
value_type = int
label = "Autres revenus perçus à l'étranger"
entity = Individu
definition_period = YEAR
# Revenus exonérés
# Revenus non imposables
# deficit antérieurs non déduits... | duits"
entity = Individu
definition_period = YEAR
|
JoseBlanca/franklin | test/mapping_test.py | Python | agpl-3.0 | 6,577 | 0.002889 | '''
Created on 2010 aza 30
@author: peio
It test the mapping module of franklin
'''
import unittest, os, StringIO
from os.path import join, exists
from tempfile import NamedTemporaryFile
from franklin.utils.misc_utils import TEST_DATA_DIR, NamedTemporaryDir
from franklin.mapping import map_reads_with_gmap, map_read... | work_dir = NamedTemporaryDir()
temp_genome = join(work_dir.name, | 'genome.fa')
os.symlink(join(mappers_dir, 'genome.fa'), temp_genome)
reads_fpath = join(gmap_dir, 'lb_lib1.pl_sanger.sm_sam1.fa')
out_bam_fhand = NamedTemporaryFile(suffix='.bam')
parameters = {'threads':None, 'kmer':13}
map_reads_with_gmap(temp_genome, reads_fpath, out_bam_fha... |
jabbalaci/PrimCom | modules/process.py | Python | gpl-2.0 | 554 | 0 | #!/usr/bin/env python
# encoding: utf-8
"""
# from modules import process
"""
import shlex
from subprocess import PIPE, Popen
def get_exitcode_stdout_ | stderr(cmd):
"""
Execute the external command and get its exitcode, stdout and stderr.
"""
args = shlex.split(cmd)
proc = Popen(args, stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
exitcode = proc.returncode
#
return exitcode, out, err
####################################... | ###################
if __name__ == "__main__":
pass
|
tboyce021/home-assistant | homeassistant/components/transmission/sensor.py | Python | apache-2.0 | 6,100 | 0.000984 | """Support for monitoring the Transmission BitTorrent client API."""
from homeassistant.const import CONF_NAME, DATA_RATE_MEGABYTES_PER_SECOND, STATE_IDLE
from homeassistant.core import cal | lback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity
from .const import (
CONF_LIMIT,
CONF_ORDER,
DOMAIN,
STATE_ATTR_TORRENT_INFO,
SUPPORTED_ORDER_MODES,
| )
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Transmission sensors."""
tm_client = hass.data[DOMAIN][config_entry.entry_id]
name = config_entry.data[CONF_NAME]
dev = [
TransmissionSpeedSensor(tm_client, name, "Down Speed", "download"),
Transmiss... |
daleloogn/deeplearning-turtorial | rnn_ctc/ctc.py | Python | gpl-2.0 | 1,769 | 0.000565 | import theano
import theano.tensor as tt
from activations import share, init_wts
class SoftmaxLayer():
def __init__(self, inpt, in_sz, n_classes, ):
b = share(init_wts(n_classes))
w = share(init_wts(in_sz, n_classes))
self.output = tt.nnet.softmax(tt.dot(inpt, w) + b)
self.params =... | tt.eye(n_labels) + \
tt.eye(n_labels, k=1) + \
tt.eye(n_labels, k=2) * sec_diag.dimshuffle((0, 'x'))
'''
Forward path probabilities
'''
pred_y = inpt[:, labels]
probabilities, _ = theano.scan(
lambda curr, prev: cu | rr * tt.dot(prev, recurrence_relation),
sequences=[pred_y],
outputs_info=[tt.eye(n_labels)[0]]
)
# Final Costs
labels_probab = tt.sum(probabilities[-1, -2:])
self.cost = -tt.log(labels_probab)
self.params = []
self.debug = probabilities.T |
Ondross/statsq | correlation_test.py | Python | mit | 3,096 | 0 | from argparse import ArgumentParser
import matplotlib.pyplot as plt
import random
import correlation as corr
OPTIONS = [-1, 1] # Possible Y values.
def newData(options, n):
return [random.choice(options) for i in range(n)]
def showData(dataA, dataB):
if len(dataA) != len(dataB):
raise ValueError... | calcCorrelation(self):
"""
Calls the binary correlation algorithm and selects the correlation
with the optimal offset.
"""
potential = corr.calcCorrelates(self.dataA, self.dataB)
maxCorrelation = (0, 0)
for correlation in potential:
if abs(correlation... | ):
maxCorrelation = correlation
self.coefficient = maxCorrelation[1]
self.offset = maxCorrelation[0]
if __name__ == "__main__":
parser = ArgumentParser("usage: %prog [options]")
parser.add_argument("-n",
dest="numDatasets",
defaul... |
BackupTheBerlios/freespeak | freespeak/ui/translation_label.py | Python | gpl-2.0 | 6,576 | 0.014294 | # FreeSpeak - a GUI frontend to online translator engines
# freespeak/ui/translation.py
#
## Copyright (C) 2005, 2006, 2007, 2008, 2009 Luca Bruno <[email protected]>
##
## This file is part of FreeSpeak.
##
## FreeSpeak is free software; you can redistribute it and/or modify
## it under the terms of the GNU Ge... | ct ('clicked', self.on_close)
self.close.show ()
def setup_menu (self):
"""
Setup the popup menu
"""
self.action_group = gtk.ActionGroup ('PopupActions')
actions = (
('Close', gtk.STOCK_CLOSE, None, None,
_('Close this translation'), self.on_... | self.ui = gtk.UIManager ()
self.ui.insert_action_group (self.action_group, 0)
self.ui.add_ui_from_string (self.ui_string)
self.menu = self.ui.get_widget ("/PopupMenu")
def drop_child (self):
"""
Drop the event box child, which would be a label or an entry
"""
... |
CloudServer/cinder | cinder/objects/backup.py | Python | apache-2.0 | 5,187 | 0 | # Copyright 2015 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | entObject, base.CinderObject,
base.CinderObjectDictCompat):
# Version 1.0: Initial version
VERSION = '1.0'
fields = {
'id': fields.UUIDField(),
'user_id': fields.UUIDField(),
'project_id': fields.UUIDField(),
'volume_id': fields.UUIDField(),
'host': fi... | lds.StringField(nullable=True),
'availability_zone': fields.StringField(nullable=True),
'container': fields.StringField(nullable=True),
'parent_id': fields.StringField(nullable=True),
'status': fields.StringField(nullable=True),
'fail_reason': fields.StringField(nullable=True),
... |
convexengineering/gplibrary | gpkitmodels/SP/aircraft/tail/tail_boom_flex.py | Python | mit | 1,453 | 0.001376 | " tail boom flexibility "
from numpy import pi
from gpkit import Model, parse_variables, SignomialsEnabled
class TailBoomFlexibility(Model):
""" Tail Boom Flexibility Model
Variables
---------
Fne [-] tail boom flexibility factor
deda [-] wing downwash deriva... | se_variables(__doc__, globals())
| def setup(self, htail, hbending, wing):
mh = htail.mh
mw = wing.mw
Vh = htail.Vh
th = hbending.th
CLhmin = htail.CLhmin
CLwmax = wing.planform.CLmax
Sw = wing.planform.S
bw = wing.planform.b
lh = htail.lh
CM = wing.planform.CM
con... |
tommeagher/pycar14 | project2/baseball_complete.py | Python | mit | 5,984 | 0.012032 | import csv
import operator
import math
from pprint import pprint
#First, let's see what kind of data we have to work with
def calculate_top10 (filename):
#Open the salary csv
salaries_object = open(filename, 'rb')
#Make the file object usable
salary_data = csv.reader(salaries_object)
#Create you... | column to see if it is a string or int
sample_data = salary_data.next()
print '%s is %s' % (sample_data[0], type(sample_data[0]))
#Because we're on the first row of data, we need to
#return to the top before we do anything with this.
#We do this by resetting the pointer in the original file.
s... | mgetter(4), reverse=True)
#Create a list of the top 10%
top_percentile = len(sorted_salaries) * .10
#Round it!
rounded_salaries = math.floor(top_percentile)
#We don't want decimal points (you can't have part of a player)
#so cast to an int
int_salaries = int(rounded_salaries)
#You co... |
benabraham/cz.pycon.org-2017 | pyconcz_2017/speakers/migrations/0022_auto_20170524_2115.py | Python | mit | 566 | 0.001767 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-05-24 19:15
f | rom __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('speakers', '0021_auto_20170524_2024'),
]
operations = [
migrations.AlterField(
model_name='slot',
name='room',
fi... | ]),
),
]
|
vincentlooi/FCIS | fcis/symbols/resnet_v1_101_fcis.py | Python | apache-2.0 | 79,613 | 0.007248 | # --------------------------------------------------------
# Fully Convolutional Instance-aware Semantic Segmentation
# Copyright (c) 2017 Microsoft
# Licensed under The Apache-2.0 License [see LICENSE for details]
# Written by Haozhi Qi, Guodong Zhang, Yi Li
# --------------------------------------------------------
... | fix_gamma=False, eps=self.eps)
scale2a_branch2b = bn2a_branch2b
res2a_branch2b_relu = mx.symbol.Activation(name='res2a_branch2b_relu', data=scale2a_branch2b, act_type='relu')
res2a_branch2c = mx.symbol.Convolution(name='res2a_branch2c', data=res2a_branch2b... | BatchNorm(name='bn2a_branch2c', data=res2a_branch2c, use_global_stats=True,
fix_gamma=False, eps=self.eps)
scale2a_branch2c = bn2a_branch2c
res2a = mx.symbol.broadcast_add(name='res2a', *[scale2a_branch1, scale2a_branch2c])
res2a_relu = mx.symbol.Activ... |
fbessez/Tinder | fb_auth_token.py | Python | mit | 2,140 | 0.002336 | # Used from https://github.com/philipperemy/Deep-Learning-Tinder/blob/master/tinder_token.py
import re
import requests
import robobrowser
MOBILE_USER_AGENT = "Tinder/7.5.3 (iPhone; iOS 10.3.2; Scale/2.00)"
FB_AUTH = "https://www.facebook.com/v2.6/dialog/oauth?redirect_uri=fb464891386855067%3A%2F%2Fauthorize%2F&disp... | ationship_details%2Cuser_friends%2Cuser_work_history%2Cuser_likes&response_type=token%2Csigned_request&default_audience=friends&return_scopes=true&auth_type=rerequest&client_id=464891386855067&ret=login&sdk=ios&logger_id=30F06532-A1B9-4B10-BB28-B29956C71AB1&ext=1470840777&hash=AeZqkIcf-NEW6vBd"
def get_fb_a | ccess_token(email, password):
s = robobrowser.RoboBrowser(user_agent=MOBILE_USER_AGENT, parser="lxml")
s.open(FB_AUTH)
f = s.get_form()
f["pass"] = password
f["email"] = email
s.submit_form(f)
f = s.get_form()
try:
s.submit_form(f, submit=f.submit_fields['__CONFIRM__'])
a... |
davidzchen/tensorflow | tensorflow/python/kernel_tests/cwise_ops_binary_test.py | Python | apache-2.0 | 36,605 | 0.010245 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | dtypes_lib.complex64: 1e-2,
dtypes_lib.float64: 1e-5,
dtypes_lib.complex128: 1e-4
}
def _compareGradientX(self,
x,
y,
np | _func,
tf_func,
numeric_gradient_type=None):
z = np_func(x, y)
zs = list(z.shape)
with self.cached_session():
inx = ops.convert_to_tensor(x)
iny = ops.convert_to_tensor(y)
if x.dtype in (np.float32, np.float64):
out = 1.1 * tf_func(in... |
LK/monopoly-simulator | non_color_property.py | Python | mit | 1,996 | 0.027555 | from prop import Property
from groupofchanges import GroupOfChanges
from constants import *
class NonColorProperty(Property):
# Constants
_UTILITY_MULTIPLIERS = { 1: 4, 2: 10 } # multipliers for owning 1 or 2 utilities
_UTILITY = True
_RAILROAD = False
def __init__(self, name, price, rents, property_group, siz... | ner = state.get_owner(self)
if owner == player:
return GroupOfChanges()
elif owner == state.bank:
return player.buy_or_deny(self, state)
else:
num_owned = owner.property_group_counts[self | .property_group]
rent = self.get_rent(num_owned, roll, state, from_card)
return player.pay(owner, rent, state)
# Returns the rent on this property based on the number of properties in this
# group owned, anding player's roll, and whether they came from a card or not
def get_rent(self, num_owned, roll, state, ... |
Jianlong-Peng/pytools | maestro/makeComplex2.py | Python | gpl-2.0 | 6,208 | 0.01047 | '''
#=============================================================================
# FileName: makeComplex.py
# Desc:
# Author: jlpeng
# Email: [email protected]
# HomePage:
# Created: 2013-06-21 15:12:17
# LastChange: 2013-06-24 09:32:03
# History:
#=======================... | om,ext)
| #complex_st.write(out_name)
#inp_name = "%s_%s_%d.inp"%(base_name,title,ligand_active_atom)
#writeInpFile(inp_name,out_name)
#print " Success, complex has been written to file"
#print " `%s`"%out_name
... |
marcusjdh/Space-Shooter | spaceshooter.py | Python | mit | 5,096 | 0.020801 | """
spaceshooter.py
Author: Marcus Helble
Credit: Liam Abbate, Wilson Rimberg
Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
import ggame
from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from random import... | thrustframe == 4:
self.thrustframe = 1
else:
self.setImage(0)
if self.rxa == 2 and self.rxb == 2:
self.x=self. | x
self.hm = 0
else:
if self.rx == -5:
self.x=self.x-10
self.hm=1
if self.rx == 5:
self.x=self.x+10
self.hm=2
if self.rya == 2 and self.ryb == 2:
self.y=self.y
... |
saukrIppl/seahub | thirdpart/openpyxl-2.3.0-py2.7.egg/openpyxl/drawing/text.py | Python | apache-2.0 | 22,428 | 0.00165 | from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl
from openpyxl.compat import unicode
from openpyxl.descriptors.serialisable import Serialisable
from openpyxl.descriptors import (
Alias,
Typed,
Set,
NoneSet,
Sequence,
String,
Bool,
MinMax,
Integer
)
from ope... | ficeArtExtensionList, allow_none=True)
# uses element group EG_FillProperties
noFill = EmptyTag(namespace=DRAWING_NS)
solidFill = ColorChoiceDescriptor()
gradFill = Typed(expected_type=GradientFillProperties, allow_none=True)
blipFill = Typed(expected_type=BlipFillProperties, allow_none=Tr | ue)
pattFill = Typed(expected_type=PatternFillProperties, allow_none=True)
grpFill = EmptyTag(namespace=DRAWING_NS)
# uses element group EG_EffectProperties
effectLst = Typed(expected_type=EffectList, allow_none=True)
effectDag = Typed(expected_type=EffectContainer, allow_none=True)
# uses eleme... |
wandb/client | wandb/vendor/pygments/styles/paraiso_light.py | Python | mit | 5,645 | 0 | # -*- coding: utf-8 -*-
"""
pygments.styles.paraiso_light
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Paraíso (Light) by Jan T. Sott
Pygments template by Jan T. Sott (https://github.com/idleberg)
Created with Base16 Builder by Chris Kempson
(https://github.com/chriskempson/base16-builder).
:copyright: ... | String.Other: "", # class: 'sx'
String.Regex: "", # class: 'sr'
String.Single: "", # class: 's1'
String.Symbol: "", # class: 'ss'
Generic: "", # class: 'g'
... | RED, # class: 'gd',
Generic.Emph: "italic", # class: 'ge'
Generic.Error: "", # class: 'gr'
Generic.Heading: "bold " + FOREGROUND, # class: 'gh'
Generic.Inserted: GREEN, ... |
vreon/figment | examples/theworldfoundry/tests/test_spatial_stackable.py | Python | mit | 6,050 | 0 | import pytest
def test_look(player, gold):
player.perform("look")
assert player.saw("a gold coin (50)")
def test_get_all_implicit(player, gold):
player.perform("get gold")
assert player.saw("You pick up a gold coin (50).")
pla | yer.forget()
player.perform("look")
assert player.did_not_see("gold coin")
def test_get_all_explicit(player, gold):
player.perform("get all gold")
assert player.saw("You pick up a gold coin (50).")
player.forget()
player.perform("look")
assert player.did_not_see("gold coin")
def test_get... | yer.saw("You pick up a gold coin (50).")
player.forget()
player.perform("look")
assert player.did_not_see("gold coin")
def test_get_all_invalid(player):
player.perform("get all gold")
assert player.saw("You don't see any 'gold' nearby.")
def test_get_subset(player, gold):
player.perform("get... |
dani0805/django_workflow | django_workflow/migrations/0006_transition_description.py | Python | bsd-3-clause | 518 | 0.001931 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-01-08 11:03
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('django_workflow', '0005_auto_20180104_1559'),
]
operations = [
migrations.A... | ='Description'),
| ),
]
|
biokit/biokit | test/rtools/test_tools.py | Python | bsd-2-clause | 434 | 0.016129 | from biokit.rtools import tools
import pytest
import os
skiptravis = pytest.mark.skipif( | "TRAVIS_PYTHON_VERSION" in os.environ,
reason="On travis")
@skiptravis
def test_codecs():
assert 'T' == tools.bool2R(True)
assert 'F' == tools.bool2R(False)
try:
tools.bool2R('ggg')
assert False
except:
assert True
@skiptravis
def test_rcode():
r | = tools.rcode('a=1')
assert r.a == 1
|
emanueldima/b2share | b2share/modules/records/serializers/schemas/marcxml.py | Python | gpl-2.0 | 5,627 | 0.001955 | # -*- coding: utf-8 -*-
#
# This file is part of EUDAT B2Share.
# Copyright (C) 2016 CERN, University of Tuebingen.
#
# B2Share 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... | ype_term=[x['resource_type_general']
for x in o['metadata'].get('resource_types', [])]))
summary = fields.Function(
lambda o: [di | ct(summary=x.get('description'))
for x in o['metadata'].get('descriptions', [])])
study_program_information_note = fields.Function(
lambda o: [dict(program_name=o['metadata'].get('disciplines', []))])
terms_governing_use_and_reproduction_note = fields.Function(
lambda o: dic... |
bchappet/dnfpy | src/test_dnfpy/model/testFieldMap.py | Python | gpl-2.0 | 1,305 | 0.02069 | import unittest
from dnfpy.model.fieldMap import FieldMap
class TestFieldMap(unittest.TestCase):
def setUp(self):
self.uut = FieldMap("uut",size=1,dt=0.1,lat=1,aff=1,tau=0.8,h=0,
th=0.64,model='cnft')
def test_update(self):
self.uut.... | expected = 1 | .375
self.assertEqual(obtained,expected)
def test_update_spike(self):
self.uut.setArg(model='spike')
self.uut.update(0.1)
self.uut.update(0.2)
obtained = self.uut.getData()
expected = 1.375
self.asse... |
jordanemedlock/psychtruths | temboo/core/Library/Foursquare/Users/Badges.py | Python | apache-2.0 | 3,462 | 0.004622 | # -*- coding: utf-8 -*-
###############################################################################
#
# Badges
# Returns badges for a given user.
#
# Python vers | ions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo 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 agre... | # software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
#
#
#############################################################... |
dimka665/range-regex | setup.py | Python | bsd-2-clause | 628 | 0.001592 | import os
from setuptools import find_packages, setup
root = os.path.dirname(os.path.realpath(__file__))
long_description = open(os.path.join(root, 'README.rst')).read()
setup(
name='range-regex',
version='1.0.3',
description='Python numeric range regular expression generat | or',
long_description=long_description,
url='http://github.com/dimka665/range-regex',
author=' | Dmitry Voronin',
author_email='[email protected]',
license='BSD',
# packages=['range_regex'],
packages=find_packages(),
include_package_data=True,
keywords='numeric range regex regular expression generator',
) |
mastizada/kuma | vendor/packages/ipython/IPython/Extensions/ext_rescapture.py | Python | mpl-2.0 | 1,498 | 0.021362 | # -*- coding: utf-8 -*-
""" IPython extension: new prefilters for output grabbing
Provides
var = %magic blah blah
var = !ls
"""
import IPython.ipapi
from IPython.genutils import *
ip = IPython.ipapi.get()
import re
def hnd_magic(line,mo):
""" Handle a = %mymagic blah blah """
#cmd = genutils.make_quote... | x_prefilter_f(self,line):
for pat, handler in ip.meta.re_prefilters:
mo = pat.match(line)
if mo:
return handler(line,mo)
|
raise IPython.ipapi.TryNext
ip.set_hook('input_prefilter', regex_prefilter_f)
|
TheGU/omoma | omoma/omoma_web/templatetags/__init__.py | Python | gpl-3.0 | 666 | 0 | # Copyright | 2011 Sebastien Maccagnoni-Munch
#
# This file is part of Omoma.
#
# Omoma is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3.
#
# Omoma is distributed in the hope that it will be useful,
# but WITHOUT A... | ITNESS 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 Omoma. If not, see <http://www.gnu.org/licenses/>.
"""
Django template tags for Omoma
"""
|
jakevdp/lombscargle | lombscargle/tests/test_lombscargle.py | Python | bsd-3-clause | 5,888 | 0 | import pytest
import numpy as np
from numpy.testing import assert_allclose, assert_equal
from astropy import units
from .. import LombScargle
from ..implementations import lombscargle_slow, lombscargle
METHOD_NAMES = ['auto', 'fast', 'slow', 'scipy', 'chi2', 'fastchi2']
@pytest.fixture
def data(N=100, period=1, th... | er(freq, method=method)
assert_allclose(PLS, expected_PLS)
@pytest.mark.parametrize('method', METHOD_NAMES)
@pytest.mark.parametrize('center_data', [True, False])
@pytest.mark.parametrize('fit_bias', [True, False])
de | f test_object_interface_autopower(data, method, center_data, fit_bias):
t, y, dy = data
if method == 'scipy' and fit_bias:
return
if method == 'scipy':
dy = None
ls = LombScargle(t, y, dy, fit_bias=fit_bias, center_data=center_data)
freq, PLS = ls.autopower(method=method)
expec... |
zyphrus/fetch-django | provider/urls.py | Python | mit | 537 | 0 | from django.conf.urls import url
from provider import view | s
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^new/$', views.new, name='new'),
url(r'^(?P<provider_id>\d+)/$', views.view, name='view'),
url(r'^(?P<provider_id>\d+)/edit/$', views.edit, name='edit'),
url(r'^(?P<provider_id>\d+)/delete/$', views.delete, name='delete'),
# Base P... | ews.base_index, name='base_index'),
url(r'^base/(?P<base_provider_id>\d+)/$',
views.base_view, name='base_view'),
]
|
luotao1/Paddle | python/paddle/fluid/tests/unittests/test_profiler.py | Python | apache-2.0 | 8,547 | 0.000468 | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | event.name.startswith("Runtime API")):
print("Warning: unregister", event.name)
def run_iter(self, exe, main_program, fetch_list):
x = np.random.random((32, 784)).astype("float32")
y = np.random.randint(0, 10, (32, 1)).astype("int64")
outs = exe.run(main_program,
... | x,
'y': y},
fetch_list=fetch_list)
def net_profiler(self,
exe,
state,
tracer_option,
batch_range=None,
use_parallel_executor=False,
use_... |
dsoprea/NsqSpinner | nsq/producer.py | Python | gpl-2.0 | 2,076 | 0.004817 | import logging
import gevent
import nsq.master
import nsq.node_collection
import nsq.connection
_logger = logging.getLogger(__name__)
class Producer(nsq.master.Master):
def __init__(self, node_collection, tls_ca_bundle_filepath=None,
tls_auth_pair=None, compression=False, identify=None,
... | ace our identify values -with- them (so we
# don't lose the values that we set, but can allow them to set everything
# else).
if identify is not None:
identify.up | date(self.identify.parameters)
self.identify.update(identify.parameters)
def publish(self, topic, message):
self.connection_election.elect_connection().pub(topic, message)
def mpublish(self, topic, messages):
self.connection_election.elect_connection().mpub(topic, messages)
|
osborne6/luminotes | controller/test/Test_groups.py | Python | gpl-3.0 | 5,743 | 0.043705 | from Test_controller import Test_controller
import Stub_urllib2
from controller.Groups import Groups
from model.Group import Group
from model.User import User
class Test_groups( Test_contr | oller ):
def setUp( self ):
Test_controller.setUp( self )
Groups.urllib2 = Stub_urllib2
self.group_name = u"my group"
self.group_name2 = u"other group"
self.username = u"mulder"
self.password = u"trustno1"
self.email_address = u"[email protected]"
self.username2 = u"scully"
se... | [email protected]"
self.username3 = u"skinner"
self.password3 = u"trustne1"
self.email_address3 = u"[email protected]"
self.group = Group.create( self.database.next_id( Group ), self.group_name )
self.database.save( self.group, commit = False )
self.group2 = Group.create( self.database.nex... |
junranhe/tf-faster-rcnn | lib/model/config.py | Python | mit | 11,161 | 0.005197 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import os.path as osp
import numpy as np
# `pip install easydict` if you don't have it
from easydict import EasyDict as edict
__C = edict()
# Consumers can get config by:
# from fast_rcnn_config im... | keep after applying NMS to RPN proposals
__C.TEST.RPN_POST_NMS_TOP_N = 300
# Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale)
# __C.TEST.RPN_MIN_SIZE = 16
# Testing mode, default to be 'nms', 'top' is slower but better
# See report for details
__C.TEST.MODE = 'nms'
# Only us... | proposals to select
__C.TEST.RPN_TOP_N = 5000
#
# ResNet options
#
__C.RESNET = edict()
# Option to set if max-pooling is appended after crop_and_resize.
# if true, the region will be resized to a squre of 2xPOOLING_SIZE,
# then 2x2 max-pooling is applied; otherwise the region will be directly
# resized to a squar... |
dmerejkowsky/qibuild | python/qipkg/actions/deploy_package.py | Python | bsd-3-clause | 1,732 | 0.005774 | ## Copyright (c) 2012-2015 Aldebaran Robotics. All rights reserved.
## Use of this source code is governed by a BSD-style license that can be
## found in the COPYING file.
""" Deploy and install a package to a target
"""
import os
import sys
import zipfile
from qisys import ui
import qisys.command
import qisys.parse... | ["ssh", "%s@%s" % (url.user, url.host),
"rm", os.path.basename(pkg_path)]
qisys.command.call(rm_cmd)
def _install_package(url, pkg_name, pkg_path):
import qi
app = qi.Application()
session = qi.Session()
session.connect("tcp://%s:9559" % (url.host))
packag | e_manager = session.service("PackageManager")
package_manager.removePkg(pkg_name)
ret = package_manager.install(
"/home/%s/%s" % (url.user, os.path.basename(pkg_path)))
ui.info("PackageManager returned: ", ret)
|
rnelson/adventofcode | advent2015/day17.py | Python | mit | 2,152 | 0 | #!/usr/bin/env python3
"""
http://adventofcode.com/day/17
Part 1
------
The elves bought too much eggnog again - 150 liters this time. To
fit it all into your refrigerator, you'll need to move it into
smaller containers. You take an inventory of the capacities of
the available containers.
For example, suppose you hav... | s):
if sum(c) == 150:
if len(c) < p2min:
p2min = len(c)
p2sizes[s] += 1
msg = '[Python] Puzzle 17-1: {}'
print(msg.format(p1count))
msg = '[Python] Puzzle 17-2: {}'
print(msg.format(p2 | sizes[p2min]))
if __name__ == '__main__':
main()
|
rven/odoo | addons/calendar/tests/test_event_recurrence.py | Python | agpl-3.0 | 27,194 | 0.001434 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.exceptions import UserError
import pytz
from datetime import datetime, date
from dateutil.relativedelta import relativedelta
from odoo.tests.common import SavepointCase
class TestRecurrentEvents(SavepointCas... | , 0), datetime(2020, 2, 17, 18, 0)),
])
def test_monthly_count_by_date_31(self):
self.event._apply_recurrence_values({
'rrule_type': 'monthly',
'interval': 1,
'month_by': 'date',
'day': 31,
'end | _type': 'count',
'count': 3,
'event_tz': 'UTC',
})
recurrence = self.env['calendar.recurrence'].search([('base_event_id', '=', self.event.id)])
events = recurrence.calendar_event_ids
self.assertEqual(len(events), 3, "It should have 3 events in the recurrence")
... |
robertchase/spindrift | spindrift/mysql/packet.py | Python | mit | 9,220 | 0.000651 | import struct
import spindrift.mysql.charset as charset
from spindrift.mysql.constants import CLIENT, SERVER_STATUS
import spindrift.mysql.util as util
MAX_PACKET_LEN = 2**24-1
NULL_COLUMN = 251
UNSIGNED_CHAR_COLUMN = 251
UNSIGNED_SHORT_COLUMN = 252
UNSIGNED_INT24_COLUMN = 253
UNSIGNED_INT64_COLUMN = 254
def writ... | ._position = 0
def __repr__(self):
return 'n=%s, d=%s' % (self.number, self.data)
def reset(self, sequence):
self.clear()
if sequence is not None:
self.number = sequence
else:
self.increment()
def clear(self):
self.data = b''
self._p... | .number = (self.number + 1) % 256
def read(self, size):
result = self.data[self._position:self._position+size]
self._position += size
return result
def read_all(self):
result = self.data[self._position:]
self._position = None # ensure no subsequent read()
retur... |
eteq/ginga | ginga/qtw/plugins/Header.py | Python | bsd-3-clause | 6,410 | 0.000936 | #
# Header.py -- FITS Header plugin for fits viewer
#
# Eric Jeschke ([email protected])
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
from ginga.misc import Bunch
from ginga.misc.plugins.HeaderBase impo... | return widget
def set_header(self, info, image):
if self._image == image:
# we've already handled this header
return
self.logger.debug("setting header")
| header = image.get_header()
table = info.table
model = HeaderTableModel(self.columns, header)
table.setModel(model)
selectionModel = QtHelp.QItemSelectionModel(model, table)
table.setSelectionModel(selectionModel)
# set column width to fit contents
# NOTE: ... |
potzenheimer/meetshaus | src/meetshaus.blog/meetshaus/blog/browser/migration.py | Python | mit | 8,180 | 0.000489 | # -*- coding: utf-8 -*-
"""Module providing base class migration for blog entry content"""
import lxml
from Acquisition import aq_inner
from Products.CMFCore.utils import getToolByName
from Products.Five.browser import BrowserView
from meetshaus.blog.blogpost import IBlogPost
from plone import api
from plone.portlets.i... | ssage_template.format(len(migrated))
if not_migrated:
msg = warn_message_template.format(len(not_migrated))
api.portal.s | how_message(
message=msg,
request=self.request
)
return len(migrated)
class BlogMigrationFinishedView(BrowserView):
""" Migration done """
def __call__(self):
return self.render()
def render(self):
return self.index()
class GatherAssetsView(Brows... |
tghw/trello-py | trello/search.py | Python | bsd-2-clause | 1,739 | 0.00345 | from .base import ApiBase
import requests
class Search(ApiBase):
__module__ = 'trello'
def __init__(self, apikey, token=None):
self._apikey = apikey
self._token = token
def get(self, query, idBoards=None, idOrganizations=None, idCards=None, modelTypes=None, board_fields=None, bo... | s=None):
resp = requests.get("https://trello.com/1/search/members", params={"key": self._apikey, "token": self._token, "query": query, "limit": limit, "idBoard": idBoard, "idOrganization": | idOrganization, "onlyOrgMembers": onlyOrgMembers}, data=None)
return self.raise_or_json(resp)
|
vlegoff/tsunami | src/secondaires/crafting/editeurs/gldedit/atelier.py | Python | bsd-3-clause | 2,784 | 0.00036 | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# 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
# ... | tice,
# this list of condition | s and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS ... |
google-research/federated | reconstruction/reconstruction_model.py | Python | apache-2.0 | 5,300 | 0.003585 | # Copyright 2020, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | l_non_trainable_variables | (self):
"""An iterable of `tf.Variable` objects, see class comment for details."""
pass
@abc.abstractproperty
def local_trainable_variables(self):
"""An iterable of `tf.Variable` objects, see class comment for details."""
pass
@abc.abstractproperty
def local_non_trainable_variables(self):
... |
timblakely/bigbrain | bigbrain/test.py | Python | apache-2.0 | 1,684 | 0.024347 | import time
from network.cluster_managers import google_compute_cluster_manager as gccm
cm = gccm.GoogleComputeClusterManager()
cm.Initialize('bats','12345','32123')
cm.Heartbeat()
cm.ListInstanceNames()
last = ''
print 'NumInstances: %i' % cm.NumInstances()
for instance in cm.ListInstanceNames():
print ' > %s' ... | :
print ' + %s -> %s' % (a,b)
name = cm.StartNewInstance()
waited = 0
while not cm.IsRunning(name) and not cm.IsFailed(name):
print """Time %3i:
%s
> started: %r
> running: %r
> failed: %r
> status: %s""" % (waited, name, cm.IsStarted(name), cm.IsRunning(name), cm.IsFailed(name), cm.GetStatu... | failed: %r
> status: %s""" % (waited, name, cm.IsStarted(name), cm.IsRunning(name), cm.IsFailed(name), cm.GetStatus(name))
|
ericl1u/eece7398 | eventBasedAnimationClass.py | Python | gpl-3.0 | 1,836 | 0.003268 | # Taken directly from CMU 15112 Course notes:
# http://www.cs.cmu.edu/~112/notes/eventBasedAnimationClass.py
# eventBasedAnimationClass.py
from Tkinter import *
class EventBasedAnimationClass(object):
def onMousePressed(self, event): pass
def onKeyPressed(self, event): pass
def onTimerFired(self): pass
... | # DK: Or you can just use an anonymous lamdba function, like this:
self.root.bind("<Key>", lambda event: self.onKeyPressedWrapper(event)) |
self.onTimerFiredWrapper()
# and launch the app (This call BLOCKS, so your program waits
# until you close the window!)
self.root.mainloop()
# EventBasedAnimationClass(300,300).run()
|
ngageoint/scale | scale/job/execution/container.py | Python | apache-2.0 | 2,514 | 0.003182 | """Defines the methods for handling file systems in the job execution's local container volume"""
from __future__ import unicode_literals
import os
from storage.container import SCALE_ROOT_PATH
SCALE_JOB_EXE_INPUT_PATH = os.path.join(SCALE_ROOT_PATH, 'input_data')
SCALE_JOB_EXE_OUTPUT_PATH = os.path.join(SCALE_ROOT... |
:rtype: string
:raises Exception: If the job execution is still queued
"""
return '%s_output_data' % job_exe.get_cluster_id()
def get_mount_volume_name(job_exe, mount_name):
"""Returns the name of the mount's container volume for the given job execution
:param job_exe: The job execution mo... | related job and job_type fields
:type job_exe: :class:`job.models.JobExecution`
:param mount_name: The name of the mount
:type mount_name: string
:returns: The mount's container volume name
:rtype: string
:raises Exception: If the job execution is still queued
"""
return '%s_mount_%s'... |
quake0day/oj | Simplify Path.py | Python | mit | 708 | 0.055085 | class Solution:
# @param {string} path the original path
# @return {string} the simplified path
def simplifyPath(self, path):
# Write your code here
stack = []
i = 0
res = ""
while i < len(path):
end = i + 1
| while end < len(path) and path[end] != "/":
end += 1
sub = path[i+1 : end]
if len(sub) > 0:
if sub == "..":
if stack != []:
stack.pop()
elif sub != ".":
stack.append(sub)
i = end
if stack == []:
return "/"
... | s
a = Solution()
print a.simplifyPath("/...") |
alefnula/samovar | src/samovar/parsing/__init__.py | Python | bsd-3-clause | 355 | 0 | __author__ = 'Viktor Kerkez <[email protected]>'
__date__ = '19 January 2013'
__copyright__ = 'C | opyright (c) 2013 Viktor Kerkez'
from .token import *
from .style import *
from .lexer import *
from .formatter import *
__all__ = ['Token', 'Lexer', 'RegexLexer', 'Formatte | r', 'ConsoleFormatter',
'Style', 'StyleAdapter', 'ConsoleStyleAdapter']
|
renalreg/radar | fabfile.py | Python | agpl-3.0 | 4,141 | 0.002415 | from contextlib import contextmanager
import binascii
import os
from pathlib import Path
import tempfile
from fabric import task
from pkg_resources import parse_version
DEFAULT_DIST_DIR = "dist"
# run with
# fab -H root@some_host --prompt-for-login-password deploy|build
@contextmanager
def temp(c):
randomstr ... | decode("utf-8") |
tmp = "/tmp/radar-{0}".format(randomstr)
c.run("mkdir {0}".format(tmp))
with c.cd(tmp):
yield tmp
c.run("rm -rf {0}".format(tmp))
@task
def build(c, rev="HEAD"):
archive = tempfile.mktemp(suffix=".tar.gz")
c.local(
'git archive "{rev}" | gzip > "{archive}"'.format(rev=rev, ... |
plotly/python-api | packages/python/plotly/plotly/validators/funnel/hoverlabel/font/_colorsrc.py | Python | mit | 470 | 0.002128 | import _plotly_utils.basevalidators
class ColorsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name="colorsrc", parent_ | name="funnel.hoverlabel.font", **kwargs
):
super(ColorsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name= | parent_name,
edit_type=kwargs.pop("edit_type", "none"),
role=kwargs.pop("role", "info"),
**kwargs
)
|
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/google/appengine/datastore/datastore_v3_pb.py | Python | bsd-3-clause | 282,355 | 0.021179 | #!/usr/bin/env python
#
# Copyright 2007 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 o... | def set_api_settings(self, x):
self.has_api_settings_ = 1
self.api_settings_ = x
def clear_api_settings(self):
if self.has_api_settings_:
self.has_api_settings_ = 0
self.api_settings_ = ""
def ha | s_api_settings(self): return self.has_api_settings_
def MergeFrom(self, x):
assert x is not self
if (x.has_requesting_app_id()): self.set_requesting_app_id(x.requesting_app_id())
if (x.has_requesting_project_id()): self.set_requesting_project_id(x.requesting_project_id())
if (x.has_requesting_versio... |
kk47/Python | django/td2.0/app/models.py | Python | lgpl-3.0 | 4,820 | 0.042087 | # coding: utf-8
from django.db import models
class Room(models.Model):
U_NUMBER = (
(u'世纪互联','世纪互联'),
(u'鹏博士IDC','鹏博士IDC'),
(u'兆维','兆维')
)
jifang = models.CharField(verbose_name="机房名称",max_length=10,choices=U_NUMBER,default=0)
jigui = mode... | ,max_length=2)
configid = models.CharField(verbose_name="Configld",max_length=30)
whoandyou = models.CharField(verbose_name="被谁依赖",max_length=30)
youandwho = models.CharField(verbose_name="依赖于谁",max_length=30)
start_time = models.DateTimeField(verbose_name="起始时间")
end_time = models.DateTimeField(verb... | T)
idmac = models.ForeignKey(Mac,on_delete=models.PROTECT,related_name='Mac__paihao')
idswitch = models.ForeignKey(Switch,on_delete=models.PROTECT)
def __unicode__(self):
return self.ip
class Repair(models.Model):
repair = models.TextField(verbose_name="维修记录",max_length=100)
... |
bloomark/f13x | assign_public_addresses.py | Python | bsd-3-clause | 2,207 | 0.004078 | import hyperdex.client
import smtplib
from bitcoin.core import COIN, b2lx
import bitcoin.wallet
import bitcoin.rpc
try:
from bitcoin.case58 import CBitcoinAddress
except:
from bitcoin.wallet import CBitcoinAddress
from config import SERVER_DB_ADDRESS, MAIL_USERNAME, MAIL_PASSWORD, NAME
c = hyperdex.client.C... | rtaddress(pub_key, label=user['email'])
server.sendmail(EMAIL, EMAIL, "[BTC_KEY] %s assigned to %s" % (pub_key, user['email']))
x.commi | t()
uninitiated_users = list(c.search('users', {'dogecoin_address': ''}))
for user in uninitiated_users:
x = c.begin_transaction()
num = c.count('dogecoin_addresses', {})
if num == 0:
server.sendmail(EMAIL, EMAIL, "[DOGE_KEY] Empty")
break
else:
pub_key = ''
dogecoin_add... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.