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 |
|---|---|---|---|---|---|---|---|---|
kobejean/tensorflow | tensorflow/python/training/checkpoint_utils.py | Python | apache-2.0 | 15,013 | 0.005728 | # Copyright 2016 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... | cense.
# ========================== | ====================================================
"""Tools to work with checkpoints."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
from tensorflow.python import pywrap_tensorflow
from tensorflow.python.framework import ops
from tensorflo... |
tripzero/soletta | data/gdb/libsoletta.so-gdb.py | Python | apache-2.0 | 29,075 | 0.002511 | # This file is part of the Soletta Project
#
# Copyright (C) 2015 Intel Corporation. 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/license... | de_type_get_port_in")
get_port_out = gdb.parse_and_eval("sol_flow_node_type_get_port_out")
p_type = type.address
ports_in = self._ports_description_to_string(tdesc["ports_in"], lambda idx: get_port_in(p_type, idx))
ports_out = self._ports_description_to_string(tdesc["port... | options = self._options_description_to_string(tdesc["options"])
return "%s=%s" \
"\n name=\"%s\"," \
"\n category=\"%s\"," \
"\n description=\"%s\"," \
"\n ports_in={%s}," \
"\n ports_out={%s}," \
"\n ... |
zwChan/VATEC | ~/eb-virt/Lib/site-packages/wheel/test/complex-dist/complexdist/__init__.py | Python | apache-2.0 | 23 | 0 | def ma | in() | :
return
|
fhirschmann/penchy | penchy/util.py | Python | mit | 6,303 | 0.000476 | """
This module provides miscellaneous utilities.
.. moduleauthor:: Fabian Hirschmann <fabian@hirschmann.email>
.. moduleauthor:: Michael Markert <markert.michael@googlemail.com>
:copyright: PenchY Developers 2011-2012, see AUTHORS
:license: MIT License, see LICENSE
"""
from __future__ import print_function
impo... |
else:
return default_value
@contextmanager
def disable_write_bytecode():
| """
Contextmanager to temporarily disable writing bytecode while executing.
"""
old_state = sys.dont_write_bytecode
sys.dont_write_bytecode = True
yield
sys.dont_write_bytecode = old_state
def default(value, replacement):
"""
Check if ``value`` is ``None`` and then return ``replace... |
mptei/smarthome | lib/logic.py | Python | gpl-3.0 | 4,430 | 0.001806 | #!/usr/bin/env python
# vim: set encoding=utf-8 tabstop=4 softtabstop=4 shiftwidth=4 expandtab
#########################################################################
# Copyright 2011-2013 Marcus Popp marcus@popp.mx
#########################################################################
# ... | _logic(logic)
# item hook
if hasattr(logic, 'watch_item'):
if isinstance(logic.watch_item, | str):
logic.watch_item = [logic.watch_item]
items = []
for entry in logic.watch_item:
items += self._sh.match_items(entry)
for item in items:
item.add_logic_trigger(logic)
def __iter__(self):
for log... |
apple/swift-lldb | packages/Python/lldbsuite/test/commands/breakpoint/basic/TestBreakpointCommand.py | Python | apache-2.0 | 12,042 | 0.002076 | """
Test lldb breakpoint command add/list/delete.
"""
from __future__ import print_function
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
import side_effect
class BreakpointCommandTestCase(TestBase):
NO_DEBUG_INFO_TESTCASE = True
... | nCmd("run", RUN_SUCCEEDED)
self.runCmd("breakpoint delete")
self.runCmd("process continue")
self.expect("process status", PROCESS_STOPPED,
patter | ns=['Process .* exited with status = 0'])
def breakpoint_command_sequence(self):
"""Test a sequence of breakpoint command add, list, and delete."""
exe = self.getBuildArtifact("a.out")
self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
# Add three breakpoints on the same line. Th... |
ThiefMaster/indico | bin/maintenance/update_header.py | Python | mit | 8,843 | 0.003279 | # This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
import os
import re
import subprocess
import sys
from datetime import date
import click
import yaml
from... | xit(1)
config['end_year'] = end_year
return config
def gen_header(data):
if data['start_ | year'] == data['end_year']:
data['dates'] = data['start_year']
else:
data['dates'] = '{} - {}'.format(data['start_year'], data['end_year'])
return '\n'.join(line.rstrip() for line in data['header'].format(**data).strip().splitlines())
def _update_header(file_path, config, substring, regex, dat... |
trevor/calendarserver | txdav/carddav/datastore/test/__init__.py | Python | apache-2.0 | 695 | 0 | # -*- test-case-name: txdav.carddav.datastore.test -*-
##
# Copyright (c) 2010-2014 Apple 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/l... | enses/LICENSE-2.0
#
# Unless required by applica | ble 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.
##
"""
AddressBook store tests.... |
wulczer/ansible | v2/ansible/executor/playbook_iterator.py | Python | gpl-3.0 | 4,905 | 0.018756 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) an... | first_host is None:
| self._first_host = host
self._host_entries[host.get_name()] = PlaybookState(parent_iterator=self)
def get_next_task(self, peek=False):
''' returns the next task for host[0] '''
return self._host_entries[self._first_host.get_name()].next(peek=peek)
def get_next_task_for_host(self, hos... |
stelfrich/openmicroscopy | components/tools/OmeroWeb/omeroweb/webclient/controller/impexp.py | Python | gpl-2.0 | 1,024 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#
#
# Copyright (c) 2008-2011 University of Dundee.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or... | /www.gnu.org/licenses/>.
#
| # Author: Aleksandra Tarkowska <A(dot)Tarkowska(at)dundee(dot)ac(dot)uk>, 2008.
#
# Version: 1.0
#
from webclient.controller import BaseController
class BaseImpexp(BaseController):
def __init__(self, conn, **kw):
BaseController.__init__(self, conn)
|
rapidpro/ureport | ureport/polls/migrations/0070_install_triggers.py | Python | agpl-3.0 | 285 | 0 | # Generated by Django 3.2.6 on 2021-10-19 | 09:14
from django.db import migrations
from ureport.sql import InstallSQL
class Migratio | n(migrations.Migration):
dependencies = [
("polls", "0069_pollquestion_color_choice"),
]
operations = [InstallSQL("polls_0070")]
|
Tojaj/librepo | examples/python/download_package.py | Python | lgpl-2.1 | 1,388 | 0.005764 | #!/usr/bin/env python3
"""
librepo - download a package
"""
import os
import sys
import shutil
from pprint import pprint
import librepo
DESTDIR = "downloaded_metadata"
PROGRESSBAR_LEN = 40
finished = False
def callback(data, total_to_download, downloaded):
"""Progress callback"""
global finished
| if total_to_download != downloaded:
finished = False
if total_to_download <= 0 or finished == True:
return
completed = int(downloaded / (total_to_download / PROGRESSBAR_LEN))
print("%30s: [%s%s] %8s/%8s\r" % (data, '#'*completed, '-'*(PROGRESSBAR_LEN-completed), int(downloaded), int(tot... | if total_to_download == downloaded and not finished:
print()
finished = True
return
if __name__ == "__main__":
pkgs = [
("ImageMagick-djvu", "Packages/i/ImageMagick-djvu-6.7.5.6-3.fc17.i686.rpm"),
("i2c-tools-eepromer", "Packages/i/i2c-tools-eepromer-3.1.0-1.fc17.i686.rpm"... |
gmimano/commcaretest | corehq/apps/users/management/commands/ptop_fast_reindex_users.py | Python | bsd-3-clause | 433 | 0.004619 | from corehq.apps.users.models import CommCareUser
from corehq.apps.hqcase.management.commands.ptop_fast_reindexer import PtopReindexer
from corehq.pillows.user import UserPillow
CHUNK_SIZE = 500
POOL_SIZE = 15
class Command(PtopReindexer):
help = "Fast r | einde | x of user elastic index by using the domain view and reindexing users"
doc_class = CommCareUser
view_name = 'users/by_username'
pillow_class = UserPillow
|
Samweli/inasafe | safe/gui/tools/wizard/step_kw25_classification.py | Python | gpl-3.0 | 6,796 | 0 | # coding=utf-8
"""
InaSAFE Disaster risk assessment tool by AusAid -**InaSAFE Wizard**
This module provides: Keyword Wizard Step: Classification Selector
Contact : ole.moller.nielsen@gmail.com
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Pu... | f.impact_funct | ion_manager\
.vector_hazards_classifications_for_layer(
subcategory_id,
layer_geometry_id,
layer_mode_id,
hazard_category_id)
else:
# There are no classifications for exposures defined... |
davidgardenier/frbpoppy | tests/monte_carlo/goodness_of_fit.py | Python | mit | 11,050 | 0 | from weighted_quantiles import median
from scipy.stats import ks_2samp
import numpy as np
import os
import matplotlib.pyplot as plt
from frbpoppy import unpickle, TNS, poisson_interval, pprint
from tests.rates.alpha_real import EXPECTED
from tests.convenience import plot_aa_style, rel_path
from simulations import Simu... | norm_mask['run'] | = run
k = norm_mask.keys()
v = norm_mask.values()
norm_uuid = group.loc[group[k].isin(v).all(axis=1), :].uuid
norm_uuid = norm_uuid.values[0]
rate_diff, n_det = self.rate(pop, survey_name, norm_uuid, run)
# Get rate weighti... |
CERNDocumentServer/invenio | modules/websubmit/lib/functions/Print_Success_SRV.py | Python | gpl-2.0 | 1,933 | 0.008795 | # This file is part of Invenio.
# Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010, 2011, 2017 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# Licens | e, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of ... | ftware Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
__revision__ = "$Id$"
from invenio.config import CFG_SITE_URL, CFG_SITE_RECORD
from invenio.websubmit_functions.Shared_Functions import ParamFromFile
## Description: function Print_Success_SRV
## This function d... |
wxgeo/geophar | wxgeometrie/sympy/physics/quantum/tests/test_innerproduct.py | Python | gpl-2.0 | 1,468 | 0 | from sympy import I, Integer
from sympy.physics.quantum.innerproduct import InnerProduct
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.state import Bra, Ket, StateBase
def test_innerproduct():
k = Ket('k')
b = Bra('b')
ip = InnerProduct(b, k)
assert isinstance(ip, InnerPr... | Bra, FooState):
@classmethod
def dual_class(self):
return FooKet
class BarState(StateBase):
pass
class BarKet(Ket, BarState):
@classmethod
def dual_class(self):
return BarBra
class BarBra(Bra, BarState):
@classmethod
def dual_class(self):
return BarKet
def tes... | rt InnerProduct(Dagger(f), f).doit() == Integer(1)
|
almey/policycompass-services | apps/datasetmanager/__init__.py | Python | agpl-3.0 | 69 | 0 | default_app | _config = ' | apps.datasetmanager.apps.datasetmanagerConfig'
|
locationlabs/confab | confab/jinja_filters.py | Python | apache-2.0 | 2,518 | 0.001191 | """
Allows custom jinja filters.
"""
### Built-in filters ###
def select(value, key):
"""
Select a key f | rom a dictionary.
If ``value`` is not a dictionary or ``key`` does not exist in it,
the ``value`` is returned as is.
"""
return value.get(key, value) if isinstance(value, dict) else value
def rotate(list_, pivot):
"""
Rotate a list around a pivot.
"""
try:
pos = list_.index(p... | st_
else:
return list_[pos:] + list_[:pos]
def map_format(sequence, format):
"""
Apply format string on elements in sequence.
:param format: format string. can use one positional format argument, i.e. '{}' or '{0}',
which will map to elements in the sequence.
"""
re... |
wood-galaxy/FreeCAD | src/Mod/Path/PathScripts/PathProfileEdges.py | Python | lgpl-2.1 | 32,805 | 0.003475 | # -*- coding: utf-8 -*-
# ***************************************************************************
# * *
# * Copyright (c) 2016 sliptonic <shopinthewoods@gmail.com> *
# * ... | obj.addProperty("App::PropertyLength", "LeadOutLineLen", "End Point", QtCore.QT_TRANSLATE_NOOP("App::Property","length of straight segment of toolpath that comes in at angle to last part edge"))
obj.addProperty("App::PropertyVector", "EndPoint", "End Point", QtCore.QT_TRANSLATE_NOOP("App::Property","The end | point of this path"))
# Profile Properties
obj.addProperty("App::PropertyEnumeration", "Side", "Profile", QtCore.QT_TRANSLATE_NOOP("App::Property","Side of edge that tool should cut"))
obj.Side = ['Left', 'Right', 'On'] # side of profile that cutter is on in relation to direction of profile
... |
fmance/deep-medical-ir | ranking/unjudged.py | Python | gpl-3.0 | 594 | 0.023569 | import sys
sys.path.insert(0, "../utils/")
import utils
def unjudged(qrelsFile, resultsFile):
qrels = utils.readQrels(qrelsFile)
results = utils.readResults(resultsFile)
unjudged = {}
for qid in results.keys():
qrelIds = | set([did for (did, _) in qrels[qid]])
resIds = set([did for (did, _, _) in results[qid][:10]])
unjudged[qid] = len(resIds - qrelIds)
print "%d -> %d" % (qid, unjudged[qid])
print "--------------------"
totalUnjudged = sum(unjudged.values())
return float(totalUnju | dged)/(len(results.keys()) * 10)
print "unjudged=%.2f" % unjudged(sys.argv[1], sys.argv[2])
|
hazelcast/hazelcast-python-client | hazelcast/protocol/codec/multi_map_lock_codec.py | Python | apache-2.0 | 1,157 | 0.002593 | from hazelcast.serialization.bits import *
from hazelcast.protocol.builtin import FixSizedTypesCodec
from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer
from hazelcast.protocol.builtin import StringCodec
from hazelcast.protocol.builtin import DataCodec
# hex: 0x021... | T_TTL_OFFSET + LONG_SIZE_IN_BYTES
_REQUEST_INITIAL_FRAME_SIZE = _REQUEST_REFERENCE_ID_OFFSET + LONG_SIZE_IN_BYTES
def encode_request(name, key, thread_id, ttl, reference_id):
buf = create_initial_buffer(_REQUEST_INITIAL_FRAME_SIZE, _REQUEST_MESSAGE_TYPE)
FixSizedTypesCodec.encode_long(buf, _REQUEST_THREAD_ID_... | ference_id)
StringCodec.encode(buf, name)
DataCodec.encode(buf, key, True)
return OutboundMessage(buf, True)
|
ahmad88me/PyGithub | github/Project.py | Python | lgpl-3.0 | 10,167 | 0.003836 | ############################ Copyrights and license ############################
# #
# Copyright 2018 bbi-yggy <yossarian@blackbirdinteractive.com> #
# ... | github.ProjectColumn.ProjectColumn,
self._request | er,
self.columns_url,
None,
{"Accept": Consts.mediaTypeProjectsPreview},
)
def create_column(self, name):
"""
calls: `POST /projects/:project_id/columns <https://developer.github.com/v3/projects/columns/#create-a-project-column>`_
:param name: str... |
razzius/PyClassLessons | instructors/course-2015/functions_gens_and_ducks/examples/in_class/warm_up/calc_tax.py | Python | mit | 300 | 0.023333 | def print_15perc_to | tal_tax(bill):
'''return the amount of money to pay in tax in US dollars
'''
bill = float(bill)
total_tax = str( bill * .15 )
return "please graciously pay at least the amount of {} in total tax ".format(total_tax)
print print_15perc_total_tax(79)
| |
Noeud/KirkByers_Course | Week2/IPaddValidity_hex_bin.py | Python | unlicense | 1,174 | 0.007666 | #!/usr/bin/env python
import fileinput
class NotValidIP(Exception):
pass
class NotValidIPLength(Exception):
pass
while True:
try:
| ip_addr = input("Enter a network IP address: ")
ip_addr_split = ip_addr.split('.')
len1 = len(ip_addr_split)
ip_addr_split = ip_addr_split[:3]
ip_addr_split.append('0')
i=0
for element in ip_addr_split:
ip_addr_split[i] = int(element)
i = i... | or element < 0):
raise NotValidIP
if (len1!=3 and len1!=4):
raise NotValidIPLength
print("The network IP address now is: %s" % ip_addr_split)
break
except ValueError:
print('Not a good value')
except NotValidIP:
print('this is not a valid IP a... |
uclouvain/osis | infrastructure/shared_kernel/entite/dtos.py | Python | agpl-3.0 | 1,467 | 0.000682 | # ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The cor... | # see http://www.gnu.org/licenses/.
#
# ##############################################################################
import attr
from osis_common.dd | d import interface
@attr.s(frozen=True, slots=True)
class EntiteUclDTO(interface.DTO):
sigle = attr.ib(type=str)
intitule = attr.ib(type=str)
|
nert-gu/Xposition | src/wiki/plugins/redlinks/mdx/redlinks.py | Python | gpl-3.0 | 3,427 | 0.000876 | import html
from urllib.parse import urljoin
from urllib.parse import urlparse
import wiki
from django.urls import resolve
from django.urls.exceptions import Resolver404
from markdown.extensions import Extension
from markdown.postprocessors import AndSubstitutePostprocessor
from markdown.treeprocessors import Treeproc... | lf, el): # noqa: max-compl | exity 11
href = el.get("href")
if not href:
return
# The autolinker turns email links into links with many HTML entities.
# These entities are further escaped using markdown-specific codes.
# First unescape the markdown-specific, then use html.unescape.
href =... |
chrisfranklin/badasschat | badasschat/socketio/transports.py | Python | bsd-3-clause | 11,277 | 0.000709 | import gevent
import urllib
import urlparse
from geventwebsocket import WebSocketError
from gevent.queue import Empty
class BaseTransport(object):
"""Base class for all transports. Mostly wraps handler class functions."""
def __init__(self, handler, config, **kwargs):
"""Base transport class.
... | return ret
return [payload]
def do_exchange(self, socket, request_method):
if not socket.connection_established:
# Runs only the first time we get a Socket opening
self.start_response("200 OK", [
("Connection", "close"),
])
| self.write("1::") # 'connect' packet
return
elif request_method in ("GET", "POST", "OPTIONS"):
return getattr(self, request_method.lower())(socket)
else:
raise Exception("No support for the method: " + request_method)
class JSONPolling(XHRPollingTransport):
def... |
gileno/curso-citi | djangoecommerce/settings.py | Python | cc0-1.0 | 4,345 | 0.001151 | """
Django settings for djangoecommerce project.
Generated by 'django-admin startproject' using Django 1.9.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
impo... | n_max_age=500)
DATABASES['default'].update(db_from_env)
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROX | Y_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Allow all host headers
ALLOWED_HOSTS = ['*']
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
# auth
LOGIN_REDIRECT_URL = 'accounts:index'
LOGIN_URL = 'login'
AUTH_USER_MODEL = 'accounts.User'
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.Mo... |
1905410/Misago | misago/threads/signals.py | Python | gpl-2.0 | 4,750 | 0.000632 | from django.contrib.auth import get_user_model
from django.db import transaction
from django.db.models.signals import pre_delete
from django.dispatch import Signal, receiver
from misago.categories.models import Category
from misago.categories.signals import delete_category_content, move_category_content
from misago.co... | = Signal(providing_args=["user"])
"""
Signal handlers
"""
@receiver(merge_thread)
def merge_threads_posts(sender, **kwargs):
other_thread = kwargs['other_thread']
other_thread.post_set.update(category=sender.category, thread=sender)
@receiver(merge_post)
def merge_posts | (sender, **kwargs):
other_post = kwargs['other_post']
for user in sender.mentions.iterator():
other_post.mentions.add(user)
@receiver(move_thread)
def move_thread_content(sender, **kwargs):
Post.objects.filter(thread=sender).update(category=sender.category)
PostEdit.objects.filter(thread=sende... |
chriscauley/django-devserver | devserver/models.py | Python | bsd-3-clause | 1,050 | 0.004762 | from django.core import exceptions
from devserver.logger import GenericLogger
MODULES = []
def load_modules():
global MODULES
MODULES = []
from devserver import settings
for path in settings.DEVSERVER_MODULES:
try:
name, class_name = path.rsplit('.', 1)
except ValueEr... | module' % path
try:
module = __import__(name, {}, {}, [''])
except ImportError, e:
raise exceptions.ImproperlyConfigured, 'Error importing devserver module %s: "%s"' % (name, e)
try:
cls = getattr(module, clas | s_name)
except AttributeError:
raise exceptions.ImproperlyConfigured, 'Error importing devserver module "%s" does not define a "%s" class' % (name, class_name)
try:
instance = cls(GenericLogger(cls))
except:
raise # Bubble up problem loading panel
M... |
Phil-LiDAR2-Geonode/pl2-geonode | geonode/catalogue/backends/geonetwork.py | Python | gpl-3.0 | 1,161 | 0 | #########################################################################
#
# Copyright (C) 2012 OpenPlans
#
| # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... | ic License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
from geonode.catalogue.backends.generic import CatalogueBackend \
as ... |
shopkick/flawless | flawless/client/client.py | Python | mpl-2.0 | 9,588 | 0.002607 | #!/usr/bin/env python
#
# Copyright (c) 2011-2013, Shopkick Inc.
# All rights reserved.
#
# 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/.
#
# ---
# Author: John Egan <jw... | clude some limits on max string length & number of variables to keep things from getting
# out of hand
frame_locals = dict((k, _myre | pr(k, v)) for k, v in
list(tb.tb_frame.f_locals.items())[:MAX_LOCALS] if k != "self")
if "self" in tb.tb_frame.f_locals and hasattr(tb.tb_frame.f_locals["self"], "__dict__"):
frame_locals.update(dict(("self." + k, _myrepr(k, v)) for k, v in
... |
michaelflowersky/pressmess | blog/processors.py | Python | bsd-3-clause | 1,181 | 0.005085 | # -*- coding: utf-8 -*-
#
# PressMess processors.py.
# This file contains template processor functions.
# Copyright (C) 2013 Michał Kwiatkowski <michaelflowersky at gmail dot com>
# This file is released under the BSD license, see the COPYING file
from django.conf import settings
def disqus(request):
"""
Hand... | ON, META_LANGUAGE and META_KEYWORDS
to template context.
"""
return {
'meta_author': settings.META_AUTHOR,
'meta_description_index': settings.META_DESCRIPTION_INDEX,
'meta_description_tags': settings.META_DESC | RIPTION_TAGS,
'meta_language': settings.META_LANGUAGE,
'meta_keywords': settings.META_KEYWORDS,
} |
zwChan/VATEC | ~/eb-virt/Lib/site-packages/pip/_vendor/requests/packages/chardet/sjisprober.py | Python | apache-2.0 | 3,764 | 0.000531 | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Con... | self._mContextAnalyzer.reset()
def get_charset_name(self):
return self._mContextAnalyzer.get_charset_name()
def feed(self, aBuf):
| aLen = len(aBuf)
for i in range(0, aLen):
codingState = self._mCodingSM.next_state(aBuf[i])
if codingState == constants.eError:
if constants._debug:
sys.stderr.write(self.get_charset_name()
+ ' prober hit error ... |
OCA/stock-logistics-workflow | delivery_total_weight_from_packaging/wizard/__init__.py | Python | agpl-3.0 | 38 | 0 | from . impor | t choose_delivery_pack | age
|
JohnGarbutt/TaskFlow | setup.py | Python | apache-2.0 | 1,330 | 0 | #!/usr/bin/env python
import os
import setuptools
def read_requires(base):
path = os.path.join('tools', base)
requires = []
if not os.path.isfile(path):
return requires
with open(path, 'rb') as h:
for line in h.read.splitlines():
line = line.strip()
if len(line... | tus :: 4 - Beta',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX :: Linux',
| 'Programming Language :: Python :: 2.6', ],
)
|
sametmax/Django--an-app-at-a-time | ignore_this_directory/django/conf/locale/sq/formats.py | Python | mit | 688 | 0 | # This | file is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Dja | ngo date format syntax,
# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'd F Y'
TIME_FORMAT = 'g.i.A'
# DATETIME_FORMAT =
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'j F'
SHORT_DATE_FORMAT = 'Y-m-d'
# SHORT_DATETIME_FORMAT =
# FIRST_DAY_OF_WEEK =
# The *_INPUT_FORMATS strings u... |
pschanely/gunicorn | gunicorn/app/pasterapp.py | Python | mit | 5,258 | 0.004755 | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import logging
import os
import pkg_resources
import sys
import ConfigParser
from paste.deploy import loadapp, loadwsgi
SERVER = loadwsgi.SERVER
from gunicorn.app.base import Application
fr... | dwsgi.loadcontext(SERVER, self.cfgurl, relative_to=self.relpath)
gc, lc = cx.global_conf.copy(), cx.local_conf.copy()
cfg = {}
host, port = lc.pop('host', ''), lc.pop('port', '')
if host and port:
cfg['bind'] = '%s:%s' % (host | , port)
elif host:
cfg['bind'] = host
cfg['workers'] = int(lc.get('workers', 1))
cfg['umask'] = int(lc.get('umask', 0))
cfg['default_proc_name'] = gc.get('__file__')
for k, v in gc.items():
if k not in self.cfg.settings:
continue
... |
ahmadiga/min_edx | cms/djangoapps/contentstore/management/commands/tests/test_reindex_library.py | Python | agpl-3.0 | 6,713 | 0.004171 | """ Tests for library reindex command """
import ddt
from django.core.management import call_command, Comm | andError
import mock
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.django import modulestore
fro | m xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from common.test.utils import nostderr
from xmodule.modulestore.tests.factories import CourseFactory, LibraryFactory
from opaque_keys import InvalidKeyError
from contentstore.management.commands.reindex_library import Command as ReindexCommand
from c... |
magnastrazh/NEUCOGAR | nest/serotonin/research/C/nest-2.10.0/examples/nest/gap_junction/two_neurons.py | Python | gpl-2.0 | 2,414 | 0.008285 | # -*- coding: utf-8 -*-
#
# two_neurons.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or... | tStatus(vm, 'events')[0]['times']
V_vm = nest.GetStatus(vm, 'events')[0]['V_m']
V = [[] for i in range(2)]
times = [[] for i in range(2)]
for i in range(len(senders_vm)):
V[senders_vm[i]-1].append(V_vm[i])
times[senders_vm[i]-1].append(times_vm[i])
V = numpy.array(V)
times = numpy.array(times)
pylab.figure(1)
pyl... | 'r-')
pylab.plot(times[0,:],V[1,:],'g-')
pylab.xlabel('time (ms)')
pylab.ylabel('membrane potential (mV)')
pylab.show() |
KrozekGimVic/2013-Fraktali | main.py | Python | mit | 2,613 | 0.001914 | from tkinter import *
from PIL import Image, ImageTk
from mandelbrot import *
from julia_set import *
class App(object):
def __init__(self, master):
# CANVAS
self.ulx, self.uly, self.drx, self.dry, self.def_width = default_settings()[
:5]
self.image = ImageTk.PhotoImage(make_f... | IntVar(value=50)
self.iterslider = Scale(master, from_=0, to=2000, variable=sel | f.iterval,
orient=HORIZONTAL, length=250)
self.iterslider.grid(row=1, column=1)
self.iterslider.bind('<ButtonRelease-1>', self.update_image)
def press(self, event):
self.sx, self.sy = event.x, event.y
def release(self, event):
self.ex, self.ey = ... |
jabbalaci/jabbapylib | tests/distance/test_dist.py | Python | gpl-3.0 | 358 | 0.00838 | from jabbapylib. | distance.dist import lev_dist, ham_dist, similarity
def test_lev_dist():
assert lev_dist('ag-tcc', 'cgctca') == 3
assert lev_dist('GUMBO', 'GAMBOL') == 2
assert lev_dist('Google', 'Yahoo!') == 6
def test_ham_dist():
assert ham_dist('toned', 'roses') == 3
def test_similarity():
| assert similarity('toned', 'roses') == 2
|
uny11/SE-Bigdata | bigdata.py | Python | gpl-3.0 | 43,107 | 0.008287 | # Copyright (C) 2017, Isaac Porta "uny11"
#
# This file is part of SE-Bigdata.
#
# SE-Bigdata 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 ve... | artido en la base'
print('\n')
print('Vamos a enviar el archivo '+Back.BLACK+Fore.GREEN+'"bigdata.sqlite"'+Style.RESET_ALL+' al servidor | .')
print('Este archivo es |
smithfarm/ceph-auto-aws | susecon2015/init_lib.py | Python | bsd-3-clause | 9,277 | 0.013905 | #
# init_lib.py
#
# functions for initialization
#
from aws_lib import SpinupError
import base64
from boto import vpc, ec2
from os import environ
from pprint import pprint
import re
import sys
import time
from yaml_lib import yaml_attr
def read_user_data( fn ):
"""
Given a filename, returns the file's co... | "subnet_id": kwargs['subnet_id'],
"instance_type": kwargs['instance_type'],
"private_ip_address": kwargs['private_ip_address']
}
# Master or minion?
if kwargs['master']:
our_kwargs['user_data'] = kwargs['user_data']
else:
# perform token substitution in user-data... | _subst( u, '@@DELEGATE@@', kwargs['delegate_no'] )
u = template_token_subst( u, '@@ROLE@@', kwargs['role'] )
u = template_token_subst( u, '@@NODE_NO@@', kwargs['node_no'] )
our_kwargs['user_data'] = u
# Make the reservation.
reservation = ec.run_instances( ami_id, **our_kwargs )
# ... |
TeachForAustria/Naschmarkt | migrationscript/config.py | Python | gpl-3.0 | 1,043 | 0 | """
This is the config file for the Migration
There are 3 things to configure.
- the old Database to migrate from
- the new Database to save the migration
- FTP connection to save the files
"""
# Old Database.
# This is where the Data is taken from
dbOld = {
'host': "", # host ip
'port': ... | 'password': "", # password
'database': "" # name of the database
}
# New Database.
# This is where the Data will be stored
dbNew = {
'host': "", # host ip
'port': 0, # port
'user': "", # username
'password': "", # password
'database': "" # name of... | ctory': "" # directory where to save the files to
}
# Every post with these tags will not be migrated.
# e.g. ['TFAktuell', 'AMS']
remove_tags = []
|
addisclinic/mobile-dispatch-server | sana/mrs/views.py | Python | bsd-3-clause | 4,834 | 0.004758 | import urllib
import telnetlib
import logging
import cjson
from models import BinaryResource
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django import forms
from django.contrib.auth import authenticate, login
from sana.mrs.openmrs import sendToOpenMRS
from sana.mrs.util i... | }
except Exception, e:
et, val, tb = sys.exc_info()
trace = traceback.format_tb(tb)
error = "Exception : %s %s %s" % (et, val, trace[0])
for tbm in trace:
logging.error(tbm)
logging.error("Got exception while fetching notification list... | s" % e)
response = {
'status': 'FAILURE',
'data': "Problem while getting notification list: %s" % e,
}
else:
logging.error('User not authenticated')
response = {
'status': 'FAILURE',
'data': 'User not authenticated',
... |
yuxng/DA-RNN | lib/networks/gru2d.py | Python | mit | 2,570 | 0.003502 | import tensorflow as tf
class GRU2DCell(tf.contrib.rnn.RNNCell):
"""Gated Recurrent Unit cell (cf. http://arxiv.org/abs/1406.1078)."""
def __init__(self, num_units, channels):
self._num_units = num_units
self._channels = channels
@property
def state_size(self):
return self._nu... | s_rstate = tf.concat(3, [inputs, tf.mul(r, state)])
| # define the variables
init_biases_1 = tf.constant_initializer(0.0)
kernel_1 = self.make_var('weights', [3, 3, self._num_units + self._channels, self._num_units])
biases_1 = self.make_var('biases', [self._num_units], init_biases_1)
# 2D convolution... |
sikegame/udacity-project-4 | main.py | Python | apache-2.0 | 1,600 | 0.000625 | #!/usr/bin/env python
| """
main.py -- Udacity conference server-side Python App Engine
HTTP controller handlers for memcache & task queue access
$Id$
created by wesc on 2014 may 2 | 4
"""
__author__ = 'wesc+api@google.com (Wesley Chun)'
import webapp2
from google.appengine.api import app_identity
from google.appengine.api import mail
from conference import ConferenceApi
class SetAnnouncementHandler(webapp2.RequestHandler):
def get(self):
"""Set Announcement in Memcache."""
... |
chrishan/twitter-bot | twitter-bot/twitter-bot.py | Python | bsd-3-clause | 2,563 | 0.003512 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import simplejson as json
import tweepy
import bitly
import urllib2
import sqlite3
from local_settings import TwitterKey, BitlyKey
logging.basicConfig(filename='log.txt', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
def run():
... | cute("SELECT * FROM tweet_table WHERE reddit_id = '%s'" % postid)
if len(query.fetchall()) == 0 and num_comments > 5:
title = entry['title']
score = entry['score']
downs = entry['downs']
ups = entry['ups']
permalink = shortapi.... | %s comments:%d score:%d]' % (url, permalink, author, num_comments, score)
status = title[:(135 - len(status))] + status
status = status.encode('utf-8')
logging.debug(status)
bot.update_status(status)
cur.execute("INSERT INTO tweet_table VA... |
Kami/sgrstats.com | sgrstats/stats/templatetags/tags.py | Python | apache-2.0 | 1,515 | 0.009901 | from django.template import Library, Node, TemplateSyntaxError
fro | m stats.views import get_next_rank_title_and_exp_points
register = Library()
class SetVariable(Node):
def __init__(self, varname, nodelist):
self.varname = varname
self.nodelist = nodelist
def render(self,context):
context[self.varname] = self.nodelist.render(context)
... | en):
"""
Set value to content of a rendered block.
{% setvar var_name %}
....
{% endsetvar
"""
try:
# split_contents() knows not to split quoted strings.
tag_name, varname = token.split_contents()
except ValueError:
raise TemplateSyntaxError, "%r tag ... |
Etxea/gestioneide | cambridge/urls.py | Python | gpl-3.0 | 7,898 | 0.018232 | # -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the h... | dge.views import *
from cambridge.forms import *
from cambridge.models import *
urlpatterns = [
url(r'^list/$',login_required(RegistrationListView.as_view()), name="cambridge_list"),
url(r'^list/all$',login_required(RegistrationListViewAll.as_v | iew()), name="cambridge_list_all"),
url(r'^list/exam/(?P<exam_id>\d+)/$',login_required(RegistrationListViewExam.as_view()), name="cambridge_list_exam"),
url(r'^excel/$',login_required(RegistrationExcelView.as_view()), name="cambridge_excel"),
url(r'^excel/exam/(?P<exam_id>\d+)/$',login_required(Registratio... |
dterei/Scraps | perf/syscall-latency.py | Python | bsd-3-clause | 1,275 | 0.017255 | # perf script event handlers, generated by perf script -g python
# Licensed under the terms of the GNU GPL License version 2 |
# The common_* event handler fields are the most useful fields common to
# all events. They don't necessarily correspond to the 'commo | n_*' fields
# in the format files. Those fields not available as handler params can
# be retrieved using Python functions of the form common_*(context).
# See the perf-trace-python Documentation for the list of available functions.
import os
import sys
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/pyt... |
LarryHillyer/PoolHost | PoolHost/nfl/division/forms.py | Python | gpl-3.0 | 1,479 | 0.025693 | from django import forms
from django.forms import ModelForm
from django.db import models
from app.models import NFL_Division
from app.models import NFL_Conference_Choices
class NFL_DivisionForm_ | Create(ModelForm):
name = forms.CharField(max_length = 100,
widget = forms.TextInput({
'class':'form-control',
'placeholder': 'Enter Division Name'}))
conference_id = forms.ChoiceField(choices = NFL_Confere... | ddenInput())
class Meta:
model = NFL_Division
fields = ['name', 'conference_id']
class NFL_DivisionForm_Edit(ModelForm):
id = forms.IntegerField(widget = forms.HiddenInput())
name = forms.CharField(max_length = 100,
widget = forms.TextInput({
... |
MiracleWong/PythonBasic | PyH/demo.py | Python | mit | 635 | 0.031496 | from pyh import *
list=[[1,'Lucy',25],[2,'Tom',30],[3,'Lily',20]]
page = PyH('Test')
page<<div(style="text-align:center")<<h4('Test table')
mytab = page << table(border="1",cellpadding="3",cellspacing="0",style="margin:auto")
tr1 = mytab << tr(bgcolor="lightgrey")
tr1 << th('id') + th('name')+t | h('age')
for i in range(len(list)):
tr2 = mytab << tr()
for j in range(3):
tr2 << td(list[i][j])
if list[i][j]=='Tom':
tr2.attributes['bgcolor']='yellow'
if list[i][j]=='Lily':
tr2[1].attributes['style']='color:red'
pag | e.printOut('/Users/miraclewong/github/PythonBasic/PyH/demo.html') |
esikachev/scenario | sahara/utils/openstack/heat.py | Python | apache-2.0 | 2,155 | 0 | # Copyright (c) 2013 Mirantis 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 writ... | ctx = context.current()
heat_url = base.url_for(ctx.service_catalog, 'orchestration')
return heat_client.Client('1', heat_url, token=ctx.auth_token,
cert_file= | CONF.heat.ca_file,
insecure=CONF.heat.api_insecure)
def get_stack(stack_name):
heat = client()
for stack in heat.stacks.list():
if stack.stack_name == stack_name:
return stack
raise ex.NotFoundException(_('Failed to find stack %(stack)s')
... |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247972723/pango/WrapMode.py | Python | gpl-2.0 | 659 | 0.009105 | # encoding: utf-8
# module pango
# from /usr/lib/python2.7/dist-packages/gtk-2.0/pango.so
# by generator 1.135
# no doc
# imports
import gobject as __gobject
import gobject._gobject as __gob | ject__gobject
class WrapMode(__gobject.GEnum):
# no doc
def __init__(self, *args, **kwargs): # real signature unknown
pass
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""list of weak references to the object (if defined)"""
__di | ct__ = None # (!) real value is ''
__enum_values__ = {
0: 0,
1: 1,
2: 2,
}
__gtype__ = None # (!) real value is ''
|
sputnick-dev/weboob | modules/entreparticuliers/module.py | Python | agpl-3.0 | 2,203 | 0 | # -*- coding: utf-8 -*-
# Copyright(C) 2015 Bezleputh
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opt... | NSE = 'AGPLv3+'
VERSION = '1.1'
BROWSER = EntreparticuliersBrowser
def search_city(self, pattern):
return self.browser.search_city(pattern)
def search_housings(self, query):
cities = [c.id for c in que | ry.cities if c.backend == self.name]
if len(cities) == 0:
return list([])
return self.browser.search_housings(query.type, cities, query.nb_rooms,
query.area_min, query.area_max,
query.cost_min, query.cos... |
pzia/keepmydatas | misc/testmagic.py | Python | mit | 344 | 0.014535 | #!/usr/bin/pyth | on |
import magic
import sys
m = magic.open(magic.MIME_TYPE)
m.load()
for f in sys.argv[1:]:
try :
print(f, m.file(f))
except :
print("Except with %s" % f)
|
mablae/weblate | weblate/trans/tests/test_machine.py | Python | gpl-3.0 | 10,441 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2015 Michal Čihař <michal@cihar.com>
#
# This file is part of Weblate <http://weblate.org/>
#
# 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... | def assertTranslate | (self, machine, lang='cs', word='world', empty=False):
translation = machine.translate(lang, word, None, None)
self.assertIsInstance(translation, list)
if not empty:
self.assertTrue(len(translation) > 0)
@httpretty.activate
def test_glosbe(self):
httpretty.register_u... |
hanks/Second_Hackson_Demo | BeaconCharityServer/app-server/models.py | Python | mit | 1,796 | 0.002227 | # coding: utf-8
from __future__ import division
class CharityItem(object):
def __init__(self, name, short_desc, long_desc, image_name, detail_image_name, rating, major, minor, objective_money, actual_money):
self.name = name
self.short_desc = short_desc
| self.long_desc = long_desc
self.image_name = image_name
self.detail_image_name = detail_image_name
self.ratin | g = rating
self.minor = minor
self.major = major
self.objective_money = objective_money
self.actual_money = actual_money
def to_dict(self):
return {
"name": self.name,
"short_desc": self.short_desc,
"long_desc": self.long_desc,
... |
rht/zulip | zerver/webhooks/opsgenie/tests.py | Python | apache-2.0 | 7,350 | 0.002041 | from zerver.lib.test_classes import WebhookTestCase
class OpsGenieHookTests(WebhookTestCase):
STREAM_NAME = "opsgenie"
URL_TEMPLATE = "/api/v1/external/opsgenie?&api_key={api_key}&stream={stream}"
WEBHOOK_DIR_NAME = "opsgenie"
def test_acknowledge_alert(self) -> None:
| expected_topic = "Integration1"
expected_message = """
[OpsGenie alert for Integration1](https://app.opsgenie.com/alert/V2#/show/052652ac-5d1c-464a-812a-7dd18bbfba8c):
* **Type**: Acknowledge
* **Message**: test alert
* **Tags**: `tag1`, `tag2`
""".strip()
self.check_webhook(
"acknowledg... | content_type="application/x-www-form-urlencoded",
)
def test_addnote_alert(self) -> None:
expected_topic = "Integration1"
expected_message = """
[OpsGenie alert for Integration1](https://app.opsgenie.com/alert/V2#/show/052652ac-5d1c-464a-812a-7dd18bbfba8c):
* **Type**: AddNote
* **Not... |
dibaunaumh/fcs-skateboard | fcs_aux/mies/__init__.py | Python | agpl-3.0 | 47 | 0 | # TO | DO separate into different package modul | es
|
markgw/jazzparser | lib/nltk/cluster/__init__.py | Python | gpl-3.0 | 4,217 | 0.000474 | # Natural Language Toolkit: Clusterers
#
# Copyright (C) 2001-2010 NLTK Project
# Author: Trevor Cohn <tacohn@cs.mu.oz.au>
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
"""
This module contains a number of basic clustering algorithms. Clustering
describes the task of discovering groups of si... | ith random initial means and the most commonly occurring
output means are chosen.
The GAAC clusterer starts with each of the M{N} vectors as singleton clusters.
It then iteratively merges pairs of clusters which have the closest centroids.
This continues until there is only one cluster. The order of merges gives rise
... | wer than later merges. The
membership of a given number of clusters M{c}, M{1 <= c <= N}, can be found by
cutting the dendrogram at depth M{c}.
The Gaussian EM clusterer models the vectors as being produced by a mixture
of k Gaussian sources. The parameters of these sources (prior probability,
mean and covariance matr... |
JohnyEngine/CNC | heekscnc/nc/cad_iso_read.py | Python | apache-2.0 | 8,450 | 0.011006 | ################################################################################
# iso_read.py
#
# Simple ISO NC code parsing
#
# Hirutso Enni, 2009-01-13
""" use this script to backplot nc files to *.scr file for autocad,bricscad,
draftsight,progecad,ares commander, etc....
usage: python cad_iso_read.py temp.... | self.set_mode(units=1.0)
elif (word == ' | G81' or word == 'g81'):
self.drill = True
self.no_move = True
self.path_col = "feed"
self.col = "feed"
elif (word == 'G82' or word == 'g82'):
self.drill = True;
self.no_move = True
self.path_col = "feed"
self.col = "... |
kane-chen/headFirstPython | src/com/lasho/headfirst/chap4/module_import_test.py | Python | gpl-3.0 | 231 | 0.012987 | '''
Creat | ed on 2014-1-21
@author: Administrator
'''
#import class/method
from athelets import get_data_filelist, get_data_in_file
james = get_data_in_file('james2.txt')
print(james.name);
print(get_data_filelist(['jame | s2.txt']));
|
andela-ggikera/regex | findall.py | Python | mit | 700 | 0.001453 | """Findall regex operations in python.
findall(string[, pos[, endpos]])
Returns a list:
not like search and match which retu | rns objects
Otherwise, it returns an empty list.
"""
import re
# look for every word in a string
pattern = re.compile(r"\w+")
result = pattern.findall("hey bro")
print result
patt = re.compile(r"a*b")
# returns ['ab', 'ab', 'ab', 'b']
res = patt.findall("abababb")
print res
# match a group of words onto a tuple
p = ... | +) (\w+)")
rv = p.findall("Hello world, i lived")
print rv
# Using unicode characters
print re.findall(ur"\w+", u"这是一个例子", re.UNICODE)
# using named groups inside pattern itself
patt = re.compile(r"(?P<word>\w+) (?P=word)")
|
COIN-L4D/L4D-intranet | server/intranet/views.py | Python | gpl-3.0 | 1,951 | 0.003588 | from django.shortcuts import redirect, get_object_or_404, render
from django.views.generic import TemplateView, View
from django.http import HttpResponse
from django.views.decorators.clickjacking import xframe_options_exempt
import json
from .models import Page, CurrentGame, VisiblePage
from .game import Manager
clas... |
return super(ClosedView, self).dispatch(*args, **kwargs)
class IntranetBaseView(View):
""" View accesible only if a game is running """
def dispatch(self, *args, **kwargs):
if not Manager().is_started():
return redirect('closed')
return super(IntranetBaseView, self).dispat... | me = 'intranet/denied.html'
class PageView(IntranetBaseView):
""" Base view for intranet page (those used in iframe) """
def fetch_url_name(self, **kwargs):
self.url_name = kwargs['url_name']
return self.url_name
def fetch_page(self):
self.page = get_object_or_404(Page, url_name=s... |
beeva-fernandocerezal/rasa_nlu | rasa_nlu/utils/__init__.py | Python | apache-2.0 | 3,329 | 0.003004 | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import os
import errno
from typing import List
from typing import Optional
from typing import Text
def relative_normpath(f, path):
# type: (Optional[Text], Text) ->... | # type: (Text) -> None
"""Creates a directory and its super paths. Succeeds even if the path already exists."""
try:
os.makedirs(dir_path)
except OSError as e:
# be happy if someone already created the path
if e.errno != errno.EEXIST:
raise
def create_dir_for_file(f... | .makedirs(os.path.dirname(file_path))
except OSError as e:
# be happy if someone already created the path
if e.errno != errno.EEXIST:
raise
def recursively_find_files(resource_name):
# type: (Optional[Text]) -> List[Text]
"""Traverse directory hierarchy to find files.
`res... |
xuy/readinglists | md_gen/parse.py | Python | mit | 1,942 | 0.009269 | import re
import string
import sys
sys.path.append('/Users/exu/PlayGround/readinglists/')
from key.keys import *
from amazon.api import AmazonAPI
from html2text import html2text
pattern = re.compile("https?://.*amazon.com/gp/product/([0-9]+)/.*")
amazon = AmazonAPI(AMAZON_ACCESS_KEY_ID, AMAZON_SECRET_ACCESS_KEY, AMAZ... | title = title
return new_title
def sanitize_text(t):
s = html2text(t)
s = string.replace(s, "'", "’")
s = string.replace(s, "**", "*")
return s
if __name__ == '__main__':
import os.path
import cPickle
pickle_file = 'products.pickle'
products = None
if os.path.isfile(pickl... | else:
products = read_file()
f = open(pickle_file, "wb")
cPickle.dump(products, f)
for product in products:
title = normalize_title(product[0])
uprint(title)
print '=' * len(title)
review = sanitize_text(product[1])
uprint(review)
print
|
uclouvain/osis_louvain | base/forms/education_group_admission.py | Python | agpl-3.0 | 2,239 | 0.000894 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | GNU General Public License for more details.
#
# A copy of this license - GNU General Public License - is available
# at the root of the | source code of this program. If not,
# see http://www.gnu.org/licenses/.
#
##############################################################################
from ckeditor.fields import RichTextFormField
from django import forms
from base.models.admission_condition import CONDITION_ADMISSION_ACCESSES
class UpdateLi... |
anryko/ansible | lib/ansible/modules/cloud/amazon/cloudwatchlogs_log_group_info.py | Python | gpl-3.0 | 4,728 | 0.00423 | #!/usr/bin/python
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... | gion, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)
logs = boto3_conn(module, conn_type='client', resource='logs', region=region, endpoint=ec2_url, **aws_connect_kwargs)
| desc_log_group = describe_log_group(client=logs,
log_group_name=module.params['log_group_name'],
module=module)
final_log_group_snake = []
for log_group in desc_log_group['logGroups']:
final_log_group_snake.append(camel_di... |
Nowis75/crazyflie-pc-client-leapmotion | lib/leapmotion/__init__.py | Python | gpl-2.0 | 1,076 | 0.000929 | # -*- coding: utf-8 -*-
#
# || ____ _ __
# +------+ / __ )(_) /_______________ _____ ___
# | 0xBC | / __ | / / __/ ___/ ___/ __ `/_ / / _ \
# +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
# || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
#
# Copyright (C) 2011-2013 Bitcraze AB
#
# Crazyflie Nano Quadcopter Client |
#
# 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 in the hope that it will be usef... |
rjleveque/tsunami_benchmarks | nthmp_currents_2015/problem2/maketopo.py | Python | bsd-3-clause | 2,646 | 0.027967 |
"""
Module to create topo and qinit data files for this example.
"""
from clawpack.geoclaw import topotools
from pylab import *
def maketopo_hilo():
x = loadtxt('x.txt')
y = loadtxt('y.txt')
z = loadtxt('z.txt')
# modify x and y so that cell size is truly uniform:
dx = 1. / (3.*3600.) # 1... | ze=(12,8))
topo1 = topotools.Topography()
topo1.read('flat.tt2',2)
contourf(topo1.x,topo1.y,topo1.Z,linspace(-30,20,51), extend='both')
topo2 = topotools.Topography()
topo2.read('hilo_flattened.tt2', | 2)
contourf(topo2.x,topo2.y,topo2.Z,linspace(-30,20,51), extend='both')
colorbar()
x1 = 204.9
x2 = 204.955
y1 = 19.715
y2 = 19.755
axis([x1,x2,y1,y2])
gca().set_aspect(1./cos(y1*pi/180.))
ticklabel_format(format='plain',useOffset=False)
contour(topo2.x,topo2.y,topo2.Z,[0.],colors... |
dlazz/ansible | lib/ansible/module_utils/network/aci/msc.py | Python | gpl-3.0 | 13,894 | 0.002159 | # -*- coding: utf-8 -*-
# This code is part of Ansible, but is an independent component
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own lic... | and comp | are entries '''
# Both objects are the same object
if subset is superset:
return True
# Both objects are identical
if subset == superset:
return True
# Both objects have a different type
if type(subset) != type(superset):
return False
for key, value in subset.item... |
relic7/prodimages | python/regex_matcherator_naturectr.py | Python | mit | 1,999 | 0.010505 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
patterns = [r'^.*?/bc_jpg_makerDrop/(crop_fullsize_pad_center)/?.*?/(\d{9}(.*?))\.(.*?)$',
r'^.*?/bc_jpg_makerDrop/(crop_fullsize_pad_anchor)/?.*?/(\d{9}(.*?))\.(.*?)$',
r'^.*?/bfly_jpg_makerDrop/(crop_fullsize_center)/?.*?/(\d{9}(.*?))\.(.*?)$',
... | t/Post_Complete/Complete_to_Load/nature_center/bfly_jpg_makerDrop/crop_fullsize_anchor/336470402.jpg"]*10
def matches_pattern(str, patterns):
for pattern in patterns:
if pattern.match(str):
return pattern.match(str), pattern
return False
def regex_matcherator(strings,patterns):
impo... | pile, patterns))
for s in strings:
if matches_pattern(s, compiled_patterns):
print matches_pattern(s, compiled_patterns)[1].pattern
print '--'.join(s.split('/')[-2:])
print matches_pattern(s, compiled_patterns)[0].groups()
print '\n'
r = regex_matcherator... |
miyakogi/m2r | dodo.py | Python | mit | 448 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Doit task definitions."""
DOIT_CONFIG = {
'default_tasks': [
'flake8',
'docs',
],
'continue': True,
'verbosity': 1,
'num_process' | : 2,
'par_type': 'thread',
}
def task_flake8():
return {
'actions': ['flake8 m2r tests'],
}
def task_docs():
return {
'actions': ['sphinx-build -q -W -E -n -b html docs docs/_build/html'],
}
| |
ZettaIO/pswingw2py | pswingw2/__init__.py | Python | mit | 334 | 0 | """Convenient imports"""
from pswingw2.client import send_simple_message # noqa
from pswingw2.client import send # n | oqa
from pswingw2.client import send_single # noqa
from pswingw2.client import send_batch # noqa
from pswingw2.client import Client # noqa
from pswingw2.config_defaults import get_sim | ple_config as config # noqa
|
muneebalam/scrapenhl2 | docs/source/conf.py | Python | mit | 4,961 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# scrapenhl2 documentation build configuration file, created by
# sphinx-quickstart on Sun Oct 1 17:47:07 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
#... | e name of the Pygm | ents (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation ... |
YannChemin/wxGIPE | proc_modis_qc.py | Python | unlicense | 23,032 | 0.039293 | ###############################################################################
# $Id$
#
# Project: Sub1 project of IRRI
# Purpose: Quality Assessment extraction from MODIS
# Author: Yann Chemin, <yann.chemin@gmail.com>
#
###############################################################################
# Copyright (c... | as N
from osgeo import gdalnumeric
from osgeo import gda | l
from osgeo import gdal_array
from osgeo.gdalconst import *
# For icons, pngs, etc coming from images.py
from wx import ImageFromStream, BitmapFromImage, EmptyIcon
import cStringIO
import images
# Define satellite bands
# Based on Landsat channels
qc = ''
# Define output file name
output = ''
# Define list of MODI... |
uclouvain/OSIS-Louvain | program_management/forms/custom_xls.py | Python | agpl-3.0 | 3,162 | 0.002847 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | uired=False, label=_('Active'))
quadrimester = forms.BooleanField(required=False, label=_('Quadrimester'))
session_derogation = forms.BooleanField(required=False, label=_('Session derogation'))
volume = forms.BooleanField(required=False, labe | l=_('Volume'))
teacher_list = forms.BooleanField(required=False, label=_('Tutors (scores responsibles included)'))
proposition = forms.BooleanField(required=False, label=_('Proposals'))
english_title = forms.BooleanField(required=False, label=_('Title in English'))
language = forms.BooleanField(required... |
global-humanitarians-unite/ghu | ghu_web/ghu_main/models.py | Python | apache-2.0 | 3,814 | 0.00236 | from django.conf import settings
from django.db import models
from django.db.models import Q
from django.core.exceptions import ValidationError
from ordered_model.models import OrderedModel
from django.contrib.auth.models import User, Group
from django.conf import settings
# Useful for attempting full-text search on f... | ormat(self.title, self.slug)
class PageTemplate(models.Model):
| name = models.CharField(max_length=256, verbose_name='User-friendly title')
template = models.CharField(max_length=256, verbose_name='Template to execute')
def __str__(self):
return '{} ({})'.format(self.name, self.template)
class Toolkit(models.Model):
slug = models.SlugField(unique=True)
tit... |
Motwani/firefox-ui-tests | .travis/create_venv.py | Python | mpl-2.0 | 3,764 | 0.000797 | #!/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/.
"""
The script can be used to setup a virtual environment for running Firefox UI Tests.
It will a... | zip_path = download(VIRTUALENV_URL % {'VERSION': VIRTUALENV_VERSION},
os.path.join(here, 'virtualenv.zip'))
try:
with zipfile.ZipFile(zip_path, 'r') as f:
f.extractall(here)
print 'Creating new virtual environment'
cmd_args = [sys.executable, script_path... | th)
except OSError:
pass
shutil.rmtree(os.path.dirname(script_path), ignore_errors=True)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--python',
dest='python',
metavar='BINARY',
he... |
GreedyOsori/Chat | jaeeun/server.py | Python | mit | 3,583 | 0.00653 | # -*- coding:utf-8 -*-
from socket import socket
import threading
import json
# id : [사용자 이름]
# action : [create | join | send_msg | broadcast | out ]
# action_value : [action에 따른 수행 값]
class Server :
def __init__(self):
self.server_sock = socket()
self.clients = []
self.rooms = {} ... | alue
msg = json.dumps(response)
for client in self.clients:
if client != client_sock :
client.send(msg)
elif action == 'exit':
if hasattr(client_sock, 'room'):
self.room | s[client_sock.room].remove(client_sock)
client_sock.close()
elif action == 'out' : #방장이 나가면 방장위임문제도 생기네~~
pass
else :
pass # 잘못된 protocol
def run(self, ip, port, backlog=10):
self.server_sock.bind((ip, port))
self.serv... |
kotejante/light-distribution-platform | libs/couchdb/tools/replication_helper_test.py | Python | lgpl-2.1 | 1,676 | 0.00179 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2008 Jan lehnardt <jan@apache.org>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
"""Simple functional test for the replication notification trigger"""
imp... | """
# set things up
database = 'replication_notification_test'
server_a = client.Server('http://localhost:5984')
server_b = client.Server('http://localhost:5985')
# server_c = client.Server('http://localhost:5986')
db_a = set_up_database(server_a, database)
db_b = set_up_database(server_b,... | add doc to node a
print 'Inserting document in to database "a"'
db_a[docId] = doc
# wait a bit. Adjust depending on your --wait-threshold setting
time.sleep(5)
# read doc from node b and compare to a
try:
db_b[docId] == db_a[docId] # == db_c[docId]
print 'SUCCESS at reading it... |
strummerTFIU/TFG-IsometricMaps | LAStools/ArcGIS_toolbox/scripts_production/lastilePro.py | Python | mit | 4,971 | 0.009254 | #
# lastilePro.py
#
# (c) 2013, martin isenburg - http://rapidlasso.com
# rapidlasso GmbH - fast tools to catch reality
#
# uses lastile.exe to compute a tiling for a folder
# worth of LiDAR files with a user-specified tile
# size (and an optional buffer)
#
# LiDAR input: LAS/LAZ/BIN/TXT/SHP/BIL/ASC/DTM... | number of arguments
argc = len(sys.argv)
### report arguments (for debug)
#gp.AddMessage("Arguments:")
#for i in range(0, argc):
# gp.AddMessage("[" + str(i) + "]" + sys.argv[i])
### get the path to LAStools
lastools_path = os.path.dirname(os.path.dirname(os.path.dirname(sys.argv[0])))
### make sure t... | " + lastools_path)
gp.AddMessage("This would work: C:\\software\\lastools")
sys.exit(1)
### complete the path to where the LAStools executables are
lastools_path = lastools_path + "\\bin"
### check if path exists
if os.path.exists(lastools_path) == False:
gp.AddMessage("Cannot find .\\last... |
birdchan/project_euler | problems/022/run.py | Python | mit | 762 | 0.023622 |
import csv
def get_name_score(name):
score = 0
for ch in name:
score += ord(ch.lower()) - ord('a') + 1
return score
def find_total_name_scores_from_file(filename):
# read/parse from file
names = []
with open(filename, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
... | e_score
return total_score
###################################################
if __name__ == '__main__':
file | name = "p022_names.txt"
print find_total_name_scores_from_file(filename)
|
HeinerTholen/Varial | varial/test/test_histotoolsbase.py | Python | gpl-3.0 | 2,422 | 0.012386 | from ROOT import TH1I, gROOT, kRed, kBlue
import unittest
import tempfile
import shutil
import os
from varial.extensions.cmsrun import Sample
from varial.wrappers import HistoWrapper
from varial.history import History
from varial import analysis
from varial import settings
from varial import diskio
class TestHistoTo... | name = "tt",
is_data = True,
lumi = 3.,
legend = "pseudo data",
input_files = ["none"],
)
analysis.all_samples["ttgamma"] = Sample(
name = "ttgamma",
lumi = 4.,
legend = "tt gamma",
input_files = ["none"],
... | |
willseward/django-dynamic-preferences | dynamic_preferences/managers.py | Python | bsd-3-clause | 4,981 | 0.001004 | import collections
from .settings import preferences_settings
from .exceptions import CachedValueNotFound, DoesNotExist
class PreferencesManager(collections.Mapping):
"""Handle retrieving / caching of preferences"""
def __init__(self, model, registry, **kwargs):
self.model = model
self.re... | = self.create_db_pref(
section=section, name=name, value=pref_obj.default)
return pref
def update_db_ | pref(self, section, name, value):
try:
db_pref = self.queryset.get(section=section, name=name)
db_pref.value = value
db_pref.save()
except self.model.DoesNotExist:
return self.create_db_pref(section, name, value)
return db_pref
def create_db_... |
pavlenk0/my-catalog | catalog/migrations/0007_auto_20170316_1730.py | Python | bsd-3-clause | 649 | 0.001541 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-16 15:30
from __future__ import unicode_literals
from django.db imp | ort migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalog', '0006_auto_20170316_1444'),
]
operations = [
migrations.AlterField(
model_name='book',
name='isbn',
field=models.CharField(help_text='''13 Character\n
... | ://www.isbn-international.org/content/what-isbn">ISBN number</a>''',
max_length=13, verbose_name='ISBN'),
),
]
|
PyCon/pc-bot | pycon_bot/modes/base.py | Python | bsd-3-clause | 12,485 | 0.004806 | from __future__ import division
import importlib
import re
import time
class SkeletonMode(object):
"""Skeleton (base) mode.
This mode can take two commands:
- change to another mode
- print help
It is also able to send messages to the channel.
This mode must superclass all... | r to a non-voter. If no user is specified,
then print the list of all non-voters.
|
Exception: If we're just starting the meeting, then set anyone
who has not reported in to be a non-voter."""
# this is a special command if we're in the "reporting in" phase;
# set as a non-voter everyone who hasn't reported in yet
# note: also adds as a non-voter... |
hickerson/bbn | fable/fable_sources/libtbx/command_line/find_files.py | Python | mit | 3,114 | 0.019268 | from __future__ import division
from libtbx.path import walk_source_tree
from libtbx.str_utils import show_string
from libtbx.utils import Sorry
from libtbx.option_parser import option_parser
from fnmatch import fnmatch
import re
import sys, os
def read_lines_if_possible(file_path):
try: f = open(file_path, "r")
e... | ption("-f", "--file_names_only",
action="store_true",
default=False,
help="with -g/--grep: show file names only, not the matching lines")
.option("-q", "--quote",
action="store_true",
default=False,
help="quote file names")
).process(args=args)
fn_patterns = command_line.args... | = ["*"]
tops = co.top
if (tops is None):
tops = ["."]
for top in tops:
if (not os.path.isdir(top)):
raise Sorry("Not a directory: %s" % show_string(top))
for file_path in walk_source_tree(top=top):
file_name = os.path.basename(file_path)
for fn_pattern in fn_patterns:
if (fnm... |
meidli/yabgp | yabgp/message/attribute/atomicaggregate.py | Python | apache-2.0 | 1,948 | 0 | # Copyright 2015 Cisco Systems, 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... | value = 0
return struct.pack('!B', cls.FLAG) + str | uct.pack('!B', cls.ID) \
+ struct.pack('!B', value)
|
operepo/ope | laptop_credential/winsys/tests/test_fs/test_fs.py | Python | mit | 1,100 | 0.030909 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os, sys
import tempfile
from winsys._compat import unittest
import uuid
import win32file
from winsys.tests.test_fs import utils
from winsys import fs
class TestFS (unittest.TestCase):
filenames = ["%d" % i for i in range (5)]
def setUp (se... | )
self.assertEquals (fs_version, os_version, "%s differs from %s" % (fs_version, os_version))
#
# All the other module-level functions are hand-offs
# to the correspondi | ng Entry methods.
#
if __name__ == "__main__":
unittest.main ()
if sys.stdout.isatty (): raw_input ("Press enter...")
|
PeterLauris/aifh | vol1/python-examples/lib/aifh/train.py | Python | apache-2.0 | 13,698 | 0.003066 | """
Artificial Intelligence for Humans
Volume 1: Fundamental Algorithms
Python Version
http://www.aifh.org
http://www.jeffheaton.com
Code repository:
https://github.com/jeffheaton/aifh
Copyright 2013 by Jeff Heaton
Licensed under the Apache License, Version 2.0 (the "License");
... | thm works by randomly changing a v | ector of doubles. This is the long term memory
of the Machine Learning algorithm. While this happens a temperature is slowly decreased. When this
t |
bewiwi/puppetboard | puppetboard/default_settings.py | Python | apache-2.0 | 1,121 | 0.005352 | import os
PUPPETDB_HOST = 'localhost'
PUPPETDB_PORT = 8080
PUPPETDB_SSL_VERIFY = True
PUPPETDB_KEY = None
PUPPETDB_CERT = None
PUPPETDB_TIMEOUT = 20
SECRET_KEY = os.urandom(24)
DEV_LI | STEN_HOST = '127.0.0.1'
DEV_LISTEN_PORT = 5000
DEV_COFFEE_LOCATION = 'coffee'
UNRESPONSIVE_HOURS = 2
ENABLE_QUERY = True
LOCALISE_TIMESTAMP = True
LOGLEVEL = 'info'
REPORTS_COUNT = 10
OFFLINE_MODE = False
ENABLE_CATALOG = Fa | lse
GRAPH_FACTS = ['architecture',
'domain',
'lsbcodename',
'lsbdistcodename',
'lsbdistid',
'lsbdistrelease',
'lsbmajdistrelease',
'netmask',
'osfamily',
'puppetversion',
... |
n00bsys0p/altcoin-abe | test/test_btc200.py | Python | agpl-3.0 | 98,158 | 0.00272 | # Copyright(C) 2014 by Abe developers.
# test_btc200.py: test Abe loading through Bitcoin Block 200.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, o... | == '47304402201f27e5 | 1caeb9a0988a1e50799ff0af94a3902403c3ad4068b063e7b4d1b0a76702206713f69bd344058b0dee55a9798759092d0916dbbc3e592fee43060005ddc17401'.decode('hex')
def test_tx_in_value(b182t1):
assert b182t1['in'][0]['value'] == 3000000000
def test_tx_in_prev_out(b182t1):
assert b182t1['in'][0]['o_hash'] == 'a16f3ce4dd5deb92d98e... |
openstax/openstax-cms | pages/tests.py | Python | agpl-3.0 | 9,623 | 0.002286 | from django.test import TestCase
from django.core.management import call_command
from wagtail.tests.utils import WagtailTestUtils, WagtailPageTests
from wagtail.core.models import Page
from pages.models import (HomePage,
HigherEducation,
ContactUs,
... | s.get(id=homepage.id)
self.assertEqual(retrieved_page.title, "Hello World")
def test_allowed_subpages(self):
self.assertAllowedSubpageTypes(HomePage, {
HigherEducation,
ContactUs,
AboutUsPage,
GeneralPage,
NewsIndex,
Press | Index,
BookIndex,
Supporters,
MapPage,
Give,
TermsOfService,
AP,
FAQ,
Support,
GiveForm,
Accessibility,
Licensing,
CompCopy,
AdoptForm,
InterestForm,
... |
jorik041/weevely3 | core/sessions.py | Python | gpl-3.0 | 7,336 | 0.004635 | from core import messages
from core.weexceptions import FatalException
from mako import template
from core.config import sessions_path, sessions_ext
from core.loggers import log, stream_handler
from core.module import Status
import os
import yaml
import glob
import logging
import urlparse
import atexit
import ast
prin... | atile:
# Register dump at exit and return
atexit.register(self._session_save_atexit)
self.update(sessiondb)
return
log.warn(
mes | sages.sessions.error_loading_file_s %
(dbpath, 'no url or password'))
raise FatalException(messages.sessions.error_loading_sessions)
class SessionURL(Session):
def __init__(self, url, password, volatile = False):
if not os.path.isdir(sessions_path):
os.makedirs(sessions_p... |
rusty1s/embedded_gcnn | lib/layer/chebyshev_gcnn.py | Python | mit | 1,356 | 0 | from six.moves import xrange
import tensorflow as tf
from .var_layer import VarLayer
from ..tf import rescaled_laplacian
def conv(features, adj, weights):
K = weights.get_shape()[0].value - 1
# Create and rescale normalized laplacian.
lap = rescaled_laplacian(adj)
Tx_0 = features
output = tf.m... | f).__init__(
weight_shape=[degree + 1, in_channels, out_channels],
bias_shape=[out_channels],
**kwargs)
def _call(self, inputs):
batch_size = len(inputs)
outputs = []
for i in xrange(batch_size):
output = conv(inputs[i], self. | adjs[i], self.vars['weights'])
if self.bias:
output = tf.nn.bias_add(output, self.vars['bias'])
output = self.act(output)
outputs.append(output)
return outputs
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.