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 |
|---|---|---|---|---|---|---|---|---|
Mega-DatA-Lab/mxnet | tests/python/unittest/test_metric.py | Python | apache-2.0 | 1,757 | 0.002277 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | *kwargs):
metric = mx.metric.create(metric, *args, **kwargs)
str_metric = json.dumps(metric.get_config())
metric2 = mx.metric.create(str_metric)
assert metric.get_config() == metric2.get_config()
def test_metrics():
check_metric('acc', axis=0)
check_met | ric('f1')
check_metric('perplexity', -1)
check_metric('pearsonr')
check_metric('nll_loss')
composite = mx.metric.create(['acc', 'f1'])
check_metric(composite)
def test_nll_loss():
metric = mx.metric.create('nll_loss')
pred = mx.nd.array([[0.2, 0.3, 0.5], [0.6, 0.1, 0.3]])
label = mx.nd.... |
adamcharnock/lightbus | lightbus/client/subclients/event.py | Python | apache-2.0 | 12,494 | 0.003764 | import asyncio
import inspect
import logging
from typing import List, Tuple, Callable, NamedTuple
from lightbus.schema.schema import Parameter
from lightbus.message import EventMessage
from lightbus.client.subclients.base import BaseSubClient
from lightbus.client.utilities import validate_event_or_rpc_name, queue_exc | eption_checker, OnError
from lightbus.client.validator import validate_outgoing, validate_incoming
from lightbus.exceptions import (
UnknownApi,
EventNotFound,
Inva | lidEventArguments,
InvalidEventListener,
ListenersAlreadyStarted,
DuplicateListenerName,
)
from lightbus.log import L, Bold
from lightbus.client.commands import (
SendEventCommand,
AcknowledgeEventCommand,
ConsumeEventsCommand,
CloseCommand,
)
from lightbus.utilities.async_tools import run_u... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractShibbsdenCom.py | Python | bsd-3-clause | 714 | 0.029412 | def extractShibbsdenCom(item):
'''
Parser for 'shibbsden.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('GOOD CHILD', 'Reborn as a Good Child', | 'translated'),
('LUCKY CAT', 'I am the Lucky Cat of an MMORPG', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildRele... | x=postfix, tl_type=tl_type)
return False |
ovresko/erpnext | erpnext/patches/v8_0/update_sales_cost_in_project.py | Python | gpl-3.0 | 303 | 0.026403 | from __future__ import unicode_literals
import frappe
def execute():
frappe.reload_doc("projects", "doctype", "project")
frappe.db.sql("""
update `tabProject` p
set total_sales_amount = ifnull((select sum(base_grand_total)
from `tabSales Order` where project=p.name a | nd docstatus=1), 0)
| """) |
sdolemelipone/django-crypsis | crypsis/tables.py | Python | gpl-3.0 | 4,778 | 0.000209 | import logging
from django.utils.html import format_html
import django_tables2 as tables
from django_tables2.rows import BoundPinnedRow, BoundRow
logger = logging.getLogger(__name__)
# A cheat to force BoundPinnedRows to use the same rendering as BoundRows
# otherwise links don't work
# BoundPinnedRow._get_and_ren... | Table(tables.Table):
class Meta:
attrs = {"class": "table table-bordered table-striped table-hover "
"table-condensed"}
# @classmethod
# def set_header_color(cls, color):
# """
# Sets all column headers to h | ave this background colour.
# """
# for column in cls.base_columns.values():
# try:
# column.attrs['th'].update(
# {'style': f'background-color:{color};'})
# except KeyError:
# column.attrs['th'] = {'style': f'background-color:{... |
gam17/QAD | cmd/qad_array_maptool.py | Python | gpl-3.0 | 9,990 | 0.020048 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
QAD Quantum Aided Design plugin ok
classe per gestire il map tool in ambito del comando array
-------------------
begin : 2016-05-31
copyrig... | r version 2 of the License, or *
* (at your option) any later version. *
* | *
***************************************************************************/
"""
from .. import qad_utils
from ..qad_variables import QadVariables
from ..qad_getpoint import QadGetPoint, QadGetPointSelectionModeEnum, QadGetPointDrawModeEnum
from... |
Jwpe/alexandria-server | alexandria_server/permissions/authentication.py | Python | mit | 2,060 | 0.000485 | from django.conf import settings
from django.utils import timezone
from rest_framework import authentication
from rest_framework import exceptions
import datetime
import jwt
from .models import User
def generate_jwt(user):
payload = {
'user': user.pk,
' | exp': timezone.now() + datetime.timedelta(weeks=2),
'iat': timezone.now()
}
return jwt.encode(payload, settings.SECRET_KEY)
def decode_jwt(token):
return jwt.decode(to | ken, settings.SECRET_KEY)
class JWTAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
token = self._get_jwt_from_header(request)
try:
payload = decode_jwt(token)
except jwt.ExpiredSignature:
detail = 'Signa... |
tema-mbt/tema-adapterlib | adapterlib/ToolProtocolHTTP.py | Python | mit | 8,508 | 0.012459 | # -*- coding: utf-8 -*-
# Copyright (c) 2006-2010 Tampere University of Technology
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the r... | elf.username, "Message" : 'CLOSE', "Parameter" : 'Empty'})
http_data = self.__requestreply(http_params)
def __requestreply(self,message ):
""" One http(s) request/reply.
Message: Message to send string.
Returns: Reply string.
"""
http_data = ''
... | if self.protocol == "HTTP":
http_connection = httplib.HTTPConnection(self.host, self.port)
elif self.protocol == "HTTPS":
http_connection = httplib.HTTPSConnection(self.host, self.port)
else:
return ''
... |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247972723/samba/dcerpc/drsuapi/DsReplicaObjMetaData2Ctr.py | Python | gpl-2.0 | 880 | 0.007955 | # encoding: utf-8
# module samba.dcerpc.drsuapi
# from /usr/lib/python2.7/dist-packages/samba/dcerpc/drsuapi.so
# by generator 1.135
""" drsuapi DCE/RPC """
# imports
import dcerpc as __dcerpc
import talloc as __talloc
class DsReplicaObjMetaData2Ctr(__talloc.Object):
# no doc
def __init__(self, *args, **kwar... | ): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pas | s
array = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
count = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
enumeration_context = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
|
lavjain/incubator-hawq | tools/bin/pythonSrc/pychecker-0.8.18/test_input/test33.py | Python | apache-2.0 | 80 | 0.0375 | 'd'
d | ef x():
print j
j = 0
def y():
for x in []:
| print x
|
deepmind/sonnet | sonnet/src/scale_gradient.py | Python | apache-2.0 | 1,288 | 0.002329 | # Copyright 2019 The Sonnet 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 applicable l... |
from sonnet.src import types
impor | t tensorflow as tf
@tf.custom_gradient
def scale_gradient(
t: tf.Tensor, scale: types.FloatLike
) -> Tuple[tf.Tensor, types.GradFn]:
"""Scales gradients for the backwards pass.
Args:
t: A Tensor.
scale: The scale factor for the gradient on the backwards pass.
Returns:
A Tensor same as input, w... |
FlySorterLLC/SantaFeControlSoftware | Examples/ExampleYeastWorkspace.py | Python | gpl-2.0 | 585 | 0.018803 | ##
## This copyrighted software is distributed under the GPL v2.0 license.
## See the LICENSE file for more details.
##
## Yeast workspace configuration file
import numpy as np
import WorkspaceModules.YeastApplicatorPlate
import WorkspaceModules.YeastArena
import WorkspaceModules.YeastArena3x3
YeastWorkspace = { 'b... | 5, 139),
'yeastArena3x3': WorkspaceModules.YeastArena3x3.Ye | astArena3x3(124, 36) }
|
kamalx/edx-platform | common/djangoapps/student/views.py | Python | agpl-3.0 | 88,916 | 0.002553 | """
Student Views
"""
import datetime
import logging
import uuid
import time
import json
import warnings
from collections import defaultdict
from pytz import UTC
from ipware.ip import get_ip
from django.conf import settings
from django.contrib.auth import logout, authenticate, login
from django.contrib.auth.models imp... | omment_common.models import Role
from external_auth.models import ExternalAuthMap
import external_auth.views
from external_ | auth.login_and_register import (
login as external_auth_login,
register as external_auth_register
)
from bulk_email.models import Optout, CourseAuthorization
import shoppingcart
from lang_pref import LANGUAGE_KEY
import track.views
import dogstats_wrapper as dog_stats_api
from util.db import commit_on_succe... |
hglkrijger/WALinuxAgent | tests/ga/test_remoteaccess.py | Python | apache-2.0 | 5,846 | 0.005132 | # Copyright Microsoft 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 or agreed to in writ... | -01-01", remote_access.user_list.users[0].expiration, "Expiration does not match.")
self.assertEquals("testAccount2", remote_access.u | ser_list.users[1].name, "Account name does not match")
self.assertEquals("encryptedPasswordString", remote_access.user_list.users[1].encrypted_password, "Encrypted password does not match.")
self.assertEquals("2019-01-01", remote_access.user_list.users[1].expiration, "Expiration does not match.")
d... |
mmmavis/lightbeam-bedrock-website | bedrock/legal/forms.py | Python | mpl-2.0 | 4,294 | 0.000699 | # coding: utf-8
# 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/.
from django import forms
from lib.l10n_utils.dotlang import _, _lazy
from bedrock.mozorg.forms import... | u'Logo misuse/modification')),
('Distributing modified Firefox/malware', _lazy(u'Distributing modified Firefox/malware')),
),
required=True,
error_messages={
'required': _lazy('Please select a category.'),
},
widget=forms.Select(
attrs={
... | rue',
}
)
)
input_product = forms.ChoiceField(
choices=(
('Firefox', _lazy(u'Firefox')),
('SeaMonkey', _lazy(u'SeaMonkey')),
('Thunderbird', _lazy(u'Thunderbird')),
('Other Mozilla Product/Project', _lazy(u'Other Mozilla Product/Project... |
nomaro/SickBeard_Backup | sickbeard/webserve.py | Python | gpl-3.0 | 155,575 | 0.006421 | # Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard 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 Lice... | Ws):
assert abspath[0] == '/'
raise cherrypy.HTTPRedirect(sickbeard.WEB_ROOT + abspath, *args, **KWs)
class TVDBWebUI:
def __init__(self, config, log=None):
self.config = config
self.log = l | og
def selectSeries(self, allSeries):
searchList = ",".join([x['id'] for x in allSeries])
showDirList = ""
for curShowDir in self.config['_showDir']:
showDirList += "showDir="+curShowDir+"&"
redirect("/home/addShows/addShow?" + showDirList + "seriesList=" + searchList)
... |
F483/gravur | gravur/common/labelbox.py | Python | mit | 232 | 0 | # coding: utf-8
# Copyr | ight (c) 2015 Fabian Barkhau <fabian.barkhau@gmail.com>
# License: MIT (see LICENSE file)
from kivy.uix.label import Label
from gravur.utils import load_widget
@load_widget
class LabelBox(L | abel):
pass
|
tanium/pytan | lib/taniumpy/object_types/saved_action_approval.py | Python | mit | 654 | 0.009174 |
# Copyright (c) 2015 Tanium Inc
#
# Generated from console.wsdl version 0.0.1
#
#
from .base import BaseType
class SavedActionApproval(BaseType):
_soap_tag = 'saved_action_approval'
def __init__(self):
BaseType.__init__(
self,
simple_properties={'id': int,
... | ved_flag': int},
complex_properties={'metadata': MetadataList},
list_properties={},
| )
self.id = None
self.name = None
self.approved_flag = None
self.metadata = None
from metadata_list import MetadataList
|
johnbachman/indra | indra/databases/identifiers.py | Python | bsd-2-clause | 11,854 | 0 | import re
import logging
from indra.resources import load_resource_json
logger = logging.getLogger(__name__)
identifiers_url = 'https://identifiers.org'
# These are just special cases of name spaces where the mapping from INDRA to
# identifiers.org is not a question of simplecapitalization.
identifiers_mappings = ... | clulab/eidos/wiki/JSON-LD#Grounding/',
'WDI': 'https://github.com/clulab/eidos/wiki/JSON-LD#Grounding/',
'FAO': 'https://github.com/ | clulab/eidos/wiki/JSON-LD#Grounding/',
'HUME': ('https://github.com/BBN-E/Hume/blob/master/resource/ontologies'
'/hume_ontology/'),
'CWMS': 'http://trips.ihmc.us/',
'SOFIA': 'http://cs.cmu.edu/sofia/',
}
def get_ns_from_identifiers(identifiers_ns):
""""Return a namespace compatible with I... |
bronikkk/tirpan | tests/test_mir04.py | Python | gpl-3.0 | 46 | 0 | if x() and y() an | d z():
a()
else:
| b()
|
vinoth3v/In | In/comment/page/load_more.py | Python | apache-2.0 | 2,050 | 0.054634 | def action_comment_load_more(context, action, entity_type, entity_id, last_id, parent_id, **args):
try:
entity = IN.entitier.load_single(entity_type, int(entity_id))
if not entity:
return
output = Object()
db = IN.db
connection = db.connection
container_id = IN.commenter.get_container_id(entity)... |
output = {more_id : output}
context.response = In.core.response.PartialRes | ponse(output = output)
except:
IN.logger.debug()
|
jayme-github/CouchPotatoServer | couchpotato/core/plugins/quality/main.py | Python | gpl-3.0 | 8,674 | 0.007033 | from couchpotato import get_session
from couchpotato.api import addApiView
from couchpotato.core.event import addEvent
from couchpotato.core.helpers.encoding import toUnicode
from couchpotato.core.helpers.request import jsonified, getParams
from couchpotato.core.helpers.variable import mergeDicts, md5, getExt
from couc... | 'label': 'TeleCine', 'alternative': ['telecine'], 'allow': [], 'ext':['avi', 'mpg', 'mpeg']},
| {'identifier': 'ts', 'size': (600, 1000), 'label': 'TeleSync', 'alternative': ['telesync', 'hdts'], 'allow': [], 'ext':['avi', 'mpg', 'mpeg']},
{'identifier': 'cam', 'size': (600, 1000), 'label': 'Cam', 'alternative': ['camrip', 'hdcam'], 'allow': [], 'ext':['avi', 'mpg', 'mpeg']}
]
pre_releases = ['c... |
wbap/Hackathon2015 | Nishida/WBAI_open_code/lstm/lstm.py | Python | apache-2.0 | 1,640 | 0.028571 | #coding:utf-8
import numpy as np
from chainer import Variable, FunctionSet
import chainer.functions as F
class LSTM(FunctionSet):
def __init__(self,f_n_units, n_units):
super(LSTM, self).__init__(
l1_x = F.Linear(f_n_units, 4*n_units),
l1_h = F.Linear | (n_units, 4*n_units),
l6 = F.Linear(n_units, f_n_units)
)
# パ | ラメータの値を-0.08~0.08の範囲で初期化
for param in self.parameters:
param[:] = np.random.uniform(-0.08, 0.08, param.shape)
def forward_one_step(self, x_data, y_data, state, train=True,dropout_ratio=0.0):
x ,t = Variable(x_data,volatile=not train),Variable(y_data,volatile=not train)
h1_in... |
DG-i/openshift-ansible | roles/lib_openshift/library/oc_adm_registry.py | Python | apache-2.0 | 94,103 | 0.001551 | #!/usr/bin/env python
# pylint: disable=missing-docstring
# flake8: noqa: T001
# ___ ___ _ _ ___ ___ _ _____ ___ ___
# / __| __| \| | __| _ \ /_\_ _| __| \
# | (_ | _|| .` | _|| / / _ \| | | _|| |) |
# \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____
# | \ / _ \ | \| |/ _ \_ _| | __| \_ ... | rator='.',
backup=False):
self.content = content
self._separator = separator
self.filename = filename
self.__yaml_dict = content
self.content_type = content_type
self.backup = backup
| self.load(content_type=self.content_type)
if self.__yaml_dict is None:
self.__yaml_dict = {}
@property
def separator(self):
''' getter method for separator '''
return self._separator
@separator.setter
def separator(self, inc_sep):
''' setter method for... |
pedrox/meld | meld/vcview.py | Python | gpl-2.0 | 35,046 | 0.005364 | ### Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org>
### Copyright (C) 2010-2012 Kai Willadsen <kai.willadsen@gmail.com>
### This program is free software; you can redistribute it and/or modify
### it under the terms of the GNU General Public License as published by
### the Free Software Foundation; either v... | efix(files)
else:
workdir = os.path.dirname(files[0]) or "."
return workdir
def cleanup_temp():
temp_location = tempfile.gettempd | ir()
# The strings below will probably end up as debug log, and are deliberately
# not marked for translation.
for f in _temp_files:
try:
assert os.path.exists(f) and os.path.isabs(f) and \
os.path.dirname(f) == temp_location
os.remove(f)
except:
... |
googlefonts/nototools | nototools/unicode_data.py | Python | apache-2.0 | 57,418 | 0.000871 | #!/usr/bin/env python
# -*- coding: utf-8 -*-#
# Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE... | if not _data_is_loaded:
_load_property_value_aliases_txt()
_load_unicode_data_ | txt()
_load_scripts_txt()
_load_script_extensions_txt()
_load_blocks_txt()
_load_derived_age_txt()
_load_derived_core_properties_txt()
_load_bidi_mirroring_txt()
_load_indic_data()
_load_emoji_data()
_load_emoji_sequence_data()
_load_unicod... |
heprom/pymicro | pymicro/core/tests/test_samples.py | Python | mit | 19,023 | 0.00021 | import unittest
import os
import numpy as np
import math
from tables import IsDescription, Int32Col, Float32Col
from py | micro.core.samples import SampleData
from BasicTools.Containers.ConstantRectilinearMesh import ConstantRectilinearMesh
import BasicTools.Containers.UnstructuredMeshCreationTools as UMCT
from config import PYMICRO_EXAMPLES_DATA_DIR
class TestGrainData(IsDescription):
"""
Description class speci | fying structured storage for tests
"""
idnumber = Int32Col() # Signed 64-bit integer
volume = Float32Col() # float
center = Float32Col(shape=(3,)) # float
class TestDerivedClass(SampleData):
""" Class to test the datamodel specification mechanism, via definition
of classes deriv... |
xyos/horarios | horarios/helpers.py | Python | mit | 5,854 | 0.005296 | import json
import logging
import httplib
import urllib2
from django.core.exceptions import ValidationError
from django.conf import settings
siaUrl=settings.SIA_URL
import re
import string
def sanitize_search_term(term):
# Replace all puncuation with spaces.
allowed_punctuation = set(['&', '|', '"', "'"])
... | []
for tok | en in tokens:
# Remove all surrounding whitespace.
token = token.strip()
if token in ['', "'"]:
continue
if token[0] != "'":
# Surround single letters with &'s
token = spaces_surrounding_letter_re.sub(r' & \1 & ', token)
# Specify '&' be... |
mozilla/popcorn_maker | vendor-local/lib/python/whoosh/filedb/filewriting.py | Python | bsd-3-clause | 21,271 | 0.000705 | # Copyright 2007 Matt Chaput. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the... | s
def __init__(self, limitmb=128, **kwargs):
SortingPool.__init__(self, **kwargs)
self.limit = limitmb * 1024 * 1024
self.currentsize = 0
def add(self, item):
# item = (fieldname, text, docnum, weight, valuestring)
size = (28 + 4 * 5 # tuple = 28 + 4 * length
... | + 18 # docnum = long = 18
+ 16 # weight = float = 16
+ 21 + len(item[4] or '')) # valuestring
self.currentsize += size
if self.currentsize > self.limit:
self.save()
self.current.append(item)
def iter_postings(self):
# This is ju... |
dmilith/SublimeText3-dmilith | Packages/Debugger/modules/libs/pywinpty/tests/test_import.py | Python | mit | 909 | 0.0011 | import sublime
import unittest
import os
import sys
class TestImport(unittest.TestCase):
mpath = None
@classmethod
def setUpClass(cls):
basedir = os.path.dirname(__file__)
mpath = os.path.normpath(os.path.join(
basedir, "..", "st3_{}_{}".format(sublime.platform(), sublime.arc... | classmethod
def tearDownClass(cls):
if not cls.mpath:
return
mpath = cls.mpath
if mpath in sys.path:
| sys.path.remove(mpath)
if "winpty" in sys.modules:
del sys.modules["winpty"]
|
rmak/splunk-sdk-python | examples/handlers/handler_urllib2.py | Python | apache-2.0 | 1,492 | 0.002681 | #!/usr/bin/env python
#
# Copyright 2011 Splunk, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"): you | may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR ... | ing permissions and limitations
# under the License.
"""Example of a urllib2 based HTTP request handler."""
from pprint import pprint
from StringIO import StringIO
import sys
import urllib2
import splunk.client as client
import utils
def request(url, message, **kwargs):
method = message['method'].lower()
d... |
kanarelo/reportlab | tests/test_lib_utils.py | Python | bsd-3-clause | 5,924 | 0.006752 | #Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
"""Tests for reportlab.lib.utils
"""
__version__=''' $Id$ '''
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses, printLocation
setOutDir(__name__)
import os, time, sys
import reportlab
import unittest
from reportlab.lib impo... | l_open_and_read('data:text/plain;,Hello%20World')
self.assertEquals(result,b'Hello World')
def testRecursiveImportErrors(self):
"check we get useful error messages"
try:
| m1 = recursiveImport('reportlab.pdfgen.brush')
self.fail("Imported a nonexistent module")
except ImportError as e:
self.assertIn('reportlab.pdfgen.brush',str(e))
try:
m1 = recursiveImport('totally.non.existent')
self.fail("Imported a nonexi... |
uclouvain/OSIS-Louvain | features/steps/utils/pages.py | Python | agpl-3.0 | 3,065 | 0.000326 | # ############################################################################
# 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 business i... | RRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# 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/lice... | ###################################################################
import pypom
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from features.pages.common import CommonPageMixin
from features.fields.fields import InputField, SelectField, ButtonField
class S... |
micolous/tm1640-rpi | doc/source/conf.py | Python | gpl-3.0 | 8,144 | 0.007859 | # -*- coding: utf-8 -*-
#
# tm1640-rpi documentation build configuration file, created by
# sphinx-quickstart on Fri Apr 12 19:52:17 2013.
#
# 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
# autogenerated file.
#
# ... | to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual... | external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'tm1640... |
snipsco/teleport | src/kubeconfig/kubectl_actions.py | Python | mit | 2,287 | 0.020988 | # encoding: utf-8
import json
import time
from kubectl_data import *
from kubectl_ports import *
from kubectl_wrapper import *
TMP_FILEPATH = '/tmp/'
def create_tmp_json(data, service_path):
with open(service_path, 'w') as out:
json.dump(data, out, indent=2)
def sub_start(service_name, data, kube_type):
fil... | bectl_register(filepath):
data = get_data_yaml(filepath)
register_data(data)
def kubectl_start(se | rvice_name):
data = get_data(service_name)
sub_start(service_name, data, 'service')
time.sleep(1)
sub_start(service_name, data, 'replicationcontroller')
def kubectl_stop(service_name):
data = get_data(service_name)
sub_stop(service_name, data, 'replicationcontroller')
sub_stop(service_name, data, 'servic... |
eduNEXT/edunext-platform | openedx/core/djangoapps/bookmarks/apps.py | Python | agpl-3.0 | 1,146 | 0.001745 | """
Configuration for bookmarks Django app
"""
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from edx_django_utils.plugins import PluginSettings, PluginURLs
from openedx.core.djangoapps.plugins.constants import ProjectType, SettingsType
class BookmarksConfig(AppConfig):
... | ,
SettingsType.COMMON: {PluginSettings.RELATIVE_PATH: 'settings.common'},
}
}
| }
def ready(self):
# Register the signals handled by bookmarks.
from . import signals # lint-amnesty, pylint: disable=unused-import
|
wiredfool/fmod | fmod/controllers/ping.py | Python | gpl-2.0 | 5,311 | 0.046131 | import logging
from pylons import config, request, response, session, tmpl_context as c
from pylons.controllers.util import abort
from fmod.lib.base import BaseController, render
from fmod import model
from sqlalchemy import desc
log = logging.getLogger(__name__)
from hashlib import md5
import time, datetime
#usef... | der_by(Ping.id):
if not ping.image in filter_ | images:
img = ping.Image_fromPing()
if img.in_pool():
c.ping=ping
c.image=ping.image
c.atts = img.all_atts()
return render('one_ping.mako')
else:
ping.fl_decided=True
ping.commit()
def _fmtTime(self, t=None):
if t!= None and hasattr(t, 'timetuple'):
t = time.mktime(t.tim... |
SimpleTax/python-simpletax | simpletax/__init__.py | Python | bsd-3-clause | 52 | 0.038462 | from api import ServerE | rror,NoAccessError,S | impleTax
|
IdeaSolutionsOnline/ERP4R | core/objs/sr_crianca.py | Python | mit | 3,036 | 0.044069 | # !/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
ERP+
"""
__author__ = 'CVt | ek dev'
__credits__ = []
__version__ = "1.0"
__maintainer__ = "CVTek dev"
__status__ = "Development"
__model_name__ = 'sr_crianca.SRCrianca'
import auth, base_models
from orm import *
from form import *
class SRCrianca(Model, View):
def __init__(self, **kargs):
Model.__init__(self, **kargs)
self.__n... | e__ = 'edit'
self.__get_options__ = ['nome'] # define tambem o campo a ser mostrado no m2m, independentemente da descricao no field do m2m
self.__order_by__ = 'sr_crianca.nome'
self.__tabs__ = [
('Pré-Natal', ['sr_pre_natal']),
('Neo-Natal', ['sr_neo_natal']),
... |
arokem/PyEMMA | pyemma/coordinates/tests/test_numpyfilereader.py | Python | bsd-2-clause | 5,975 | 0.002343 | # Copyright (c) 2015, 2014 Computational Molecular Biology Group, Free University
# Berlin, 14195 Berlin, Germany.
# 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 ... | er.get_output()
fh = np.load(self.npz)
data = [x[1] for x in fh.items()]
fh.close()
self.assertEqual(reader.number_of_trajectories(), len(data))
for outp, inp in zip(all_data, data):
np.testing.assert_equal(outp, inp)
def test_stridden_access(self):
re... | reader.get_output(stride=stride)[0]
np.testing.assert_equal(first_traj, wanted[::stride],
"did not match for stride %i" % stride)
def test_lagged_stridden_access(self):
reader = NumPyFileReader(self.f1)
strides = [2, 3, 5, 7, 15]
lags = [1, 3,... |
DomDomPow/snapventure | snapventure-backend/snapventure/migrations/0005_auto_20161103_0856.py | Python | gpl-3.0 | 1,892 | 0.003171 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-03 08:56
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... | ('name', models.CharField(max_length=255)),
('created', models.DateTimeField(auto_now_add=True)),
('last_updated', models.DateTimeField(auto_now=True)),
('journey', models.ForeignKey(on | _delete=django.db.models.deletion.CASCADE, to='snapventure.Journey')),
],
),
migrations.CreateModel(
name='Profile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('bio', mod... |
stonekyx/binary | vendor/scons-local-2.3.4/SCons/Scanner/Dir.py | Python | gpl-3.0 | 3,751 | 0.002399 | #
# Copyright (c) 2001 - 2014 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge... |
return scan_in_memory(node, env, path)
def scan_in_memory(node, env, path=()):
"""
"Scans" a Node.FS.Dir for its in-me | mory entries.
"""
try:
entries = node.entries
except AttributeError:
# It's not a Node.FS.Dir (or doesn't look enough like one for
# our purposes), which can happen if a target list containing
# mixed Node types (Dirs and Files, for example) has a Dir as
# the first e... |
MSEMJEJME/ReAlistair | renpy/lint.py | Python | gpl-2.0 | 13,359 | 0.007411 | # Copyright 2004-2010 PyTom <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, mer... | aluate '%s', in %s.", expr, where)
if additional:
add(additional)
# Returns True of the expression can be compiled as python, False
# otherwise.
def try_compile(where, expr):
try:
renpy.python. | py_compile_eval_bytecode(expr)
except:
report("'%s' could not be compiled as a python expression, %s.", expr, where)
# This reports an error if we're sure that the image with the given name
# does not exist.
def image_exists(name, expression, tag):
# Add the tag to the set of known t... |
tseaver/google-cloud-python | datastore/google/cloud/datastore/batch.py | Python | apache-2.0 | 12,054 | 0.000166 | # Copyright 2014 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, s... | ommit.
"""
new_mutation = _datastore_pb2.Mutation()
self._mutations.append(new_mutation)
return new_mutation.insert
def _add_complete_key_entity_pb(self):
"""Adds a new mutation for an entity with a completed key.
:rtype: :class:`.entity_pb2.Entity`
:returns... | tity protobuf that will be
updated and sent with a commit.
"""
# We use ``upsert`` for entities with completed keys, rather than
# ``insert`` or ``update``, in order not to create race conditions
# based on prior existence / removal of the entity.
new_mutation =... |
Zephyrrus/ubb | YEAR 1/SEM1/FP/LAB/l6-l9/Repository/SQLLoader.py | Python | mit | 2,336 | 0.003853 | # NEVER DO THIS IN SQL!
from Repository.Loader import Loader, LoaderException
from Domain import Grade, Student, Discipline
import sqlite3
class SQLLoader(Loader):
def __init__(self, repo):
self.repo = repo
self.conn = sqlite3.connect(self.repo.getStoragePath() + ".sqlite")
self.curso | r = self.conn.cursor()
def save(self):
# serializable = {'students': [], 'disciplines': [], 'grades': []}
self.cursor.execute('''DROP TABLE IF EXISTS student | s;''')
self.cursor.execute('''DROP TABLE IF EXISTS disciplines;''')
self.cursor.execute('''DROP TABLE IF EXISTS grades;''')
# eww
self.cursor.execute('''CREATE TABLE students (id int, name text)''')
self.cursor.execute('''CREATE TABLE disciplines (id int, name text)''')
... |
gramps-project/gramps | gramps/gen/utils/symbols.py | Python | gpl-2.0 | 7,831 | 0.001022 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2015- Serge Noiraud
#
# 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 opti... | config.get('utf8.dead-symbol')),
(_("Star and crescent"), "\u262a",
config.get('utf8.dead-symbol')),
(_("West Syriac cross"), "\u2670",
config.get('utf8.dead-symbol')) | ,
(_("East Syriac cross"), "\u2671",
config.get('utf8.dead-symbol')),
(_("Heavy Greek cross"), "\u271a",
config.get('utf8.dead-symbol')),
(_("Latin cross"), "\u271d",
... |
juddc/Dipper | dip/tests/test_interpreter.py | Python | mit | 5,801 | 0.001896 | import sys
sys.path.insert(0, "../")
import unittest
from dip.typesystem import DNull, DBool, DInteger, DString, DList
from dip.compiler import BytecodeCompiler
from dip.interpreter import VirtualMachine
from dip.namespace import Namespace
class TestInterpreter(unittest.TestCase):
def _execute_simple(... | result[0] = val
vm = VirtualMachine([], getresult)
globalns = Namespace("globals" | )
ctx = BytecodeCompiler("main", code, data, namespace=globalns)
globalns.set_func("main", ctx.mkfunc())
vm.setglobals(globalns)
vm.run(pass_argv=False)
return result[0]
def test_add(self):
result = self._execute_simple("""
ADD 0 1 ... |
jean/sentry | src/sentry/web/frontend/project_settings.py | Python | bsd-3-clause | 12,517 | 0.001997 | from __future__ import absolute_import
import re
from django import forms
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from uuid import... | tomatically resolve an issue if it hasn\'t been seen for this amount of time.'
)
)
scrub_dat | a = forms.BooleanField(
label=_('Data Scrubber'), help_text=_('Enable server-side data scrubbing.'), required=False
)
scrub_defaults = forms.BooleanField(
label=_('Use Default Scrubbers'),
help_text=_(
'Apply default scrubbers to prevent things like passwords and credit cards... |
googleapis/python-aiplatform | samples/generated_samples/aiplatform_v1_generated_tensorboard_service_read_tensorboard_blob_data_sync.py | Python | apache-2.0 | 1,581 | 0.001265 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | :
# Create a client
client = aiplatform_v1.TensorboardServiceClient()
# Init | ialize request argument(s)
request = aiplatform_v1.ReadTensorboardBlobDataRequest(
time_series="time_series_value",
)
# Make the request
stream = client.read_tensorboard_blob_data(request=request)
# Handle the response
for response in stream:
print(response)
# [END aiplatform_... |
jachris/cook | cook/cpp.py | Python | mit | 18,097 | 0 | import os
import re
from . import core
@core.rule
def executable(
name, sources=None, include=None, define=None, flags=None, links=None,
compiler=None, warnings_are_errors=False, scan=True, debug=True,
objects=None, linkflags=None
):
if compiler is None:
compiler, toolchain = _get_default_com... | ommand = [archiver, '/OUT:' + name]
command.extend(objects)
command.extend(linkflags)
core.call(command, env=_msvc_get_cl_env(compiler))
@core.rule
def shared_li | brary(
name, sources, include=None, define=None, flags=None, headers=None,
compiler=None, warnings_are_errors=False, scan=True, msvc_lib=False,
debug=True, linkflags=None
):
if compiler is None:
compiler, toolchain = _get_default_compiler()
else:
toolchain = _get_toolchain(compiler)
... |
lodow/portia-proxy | slybot/slybot/exporter.py | Python | bsd-3-clause | 325 | 0.006154 | from | scrapy.contrib.exporter import CsvItemExporter
from scrapy.conf import settings
class SlybotCSVItemExporter(CsvItemExporter):
def __init__(self, *args, **kwargs):
kwargs['fields_to_export'] = settings.getlist('CSV_EXPORT_FIELDS') or None
super(SlybotC | SVItemExporter, self).__init__(*args, **kwargs)
|
ursky/metaWRAP | bin/metawrap-scripts/sam_to_fastq.py | Python | mit | 173 | 0.052023 | #!/usr/bin/env python2.7
import sys
for line in open(sys.arg | v[1]):
cut=line.split('\t')
if len(cut) | <11: continue
print ">"+cut[0]
print cut[9]
print "+"
print cut[10]
|
ctwiz/stardust | qa/rpc-tests/mempool_spendcoinbase.py | Python | mit | 2,474 | 0.005659 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Stardust Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test spending coinbase transactions.
# The coinbase transaction in block N can appear in block
# N+1... | pool", "-debug=mempool"]
self.nodes = []
self.nodes.append(start_node(0, self.options.tmpdir, args))
self.is_network_split = False
def run_test(self):
chain_height = self.nodes[0].getblockcount()
assert_equal(chain_height, 200)
node0_address = self.nodes[0].getnewadd... | height chain_height-100+1 ok in mempool, should
# get mined. Coinbase at height chain_height-100+2 is
# is too immature to spend.
b = [ self.nodes[0].getblockhash(n) for n in range(101, 103) ]
coinbase_txids = [ self.nodes[0].getblock(h)['tx'][0] for h in b ]
spends_raw = [ creat... |
darylmathison/github-user-queries | tests/main/test_service.py | Python | gpl-3.0 | 7,359 | 0.001495 | import unittest
from unittest.mock import patch
from app.main.service import GitHubUserService
@patch("app.main.service.github")
class TestGitHubUserService(unittest.TestCase):
def setUp(self):
self.test_user = "test"
self.retrieved_repos_return = [
{
"fork": False,
... | l": "http://parent",
"full_n | ame": self.test_user + "1/test_parent",
"pull_url": "https://localhost/parent/pulls",
"html_url": "https://localhost/parent"
}
}
]
def test_search_for_users_error(self, github_client):
message = "too many"
github_client.sea... |
plotly/plotly.py | packages/python/plotly/plotly/validators/histogram/marker/pattern/_bgcolorsrc.py | Python | mit | 433 | 0.002309 | import _plotly_utils.basevalidators
class BgcolorsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name="bgcolorsrc", parent_name="histogram.marker.pattern", **kwargs
):
super(BgcolorsrcValidator, self).__init__(
| plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "none"),
**kwargs
| )
|
unistra/django-sympa | docs/conf.py | Python | gpl-2.0 | 8,528 | 0.00598 | # -*- coding: utf-8 -*-
#
# sympa documentation build configuration file, created by
# sphinx-quickstart on Mon Aug 25 18:11:49 2014.
#
# 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
# autogenerated file.
#
# All configuration values have a default | ; values that are commented out
# serve to show the default.
from datetime import date
import sys
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath t... |
aldialimucaj/Streaker | setup.py | Python | mit | 680 | 0 | from distutils.core import set | up
setup(
# Application name:
name="streaker",
# Version number (initial):
version="0.0.1",
# Application author details:
author="Aldi Alimucaj",
author_email="aldi.alimucaj@gmail.com",
# Packages
packages=["streaker"],
scripts=['bin/streaker'],
# Include additional fil... | ta=True,
# Details
url="http://pypi.python.org/pypi/Streaker_v001/",
#
license="MIT",
description="GitHub streak manipulator",
# long_description=open("README.txt").read(),
# Dependent packages (distributions)
install_requires=[
# "",
],
)
|
syleam/document_csv | wizard/launch.py | Python | gpl-3.0 | 3,320 | 0.002711 | # -*- coding: utf-8 -*-
##############################################################################
#
# document_csv module for OpenERP, Import structure in CSV
# Copyright (C) 2011 SYLEAM (<http://www.syleam.fr/>)
# Christophe CHAUVET <christophe.chauvet@syleam.fr>
# Copyright (C) 2011 Camptoc... | ther version 3 of the License, or
# (at your option) any later version.
#
# document_csv is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even th | e implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#################... |
texta-tk/texta | utils/word_cluster.py | Python | gpl-3.0 | 2,505 | 0.007186 | from sklearn.cluster import MiniBatchKMeans
import numpy as np
import json
import os
from texta.settings import MODELS_DIR
class WordCluster(object):
"""
WordCluster object to cluster Word2Vec vectors using MiniBatchKMeans.
: param embedding : Word2Vec object
: param n_clusters, int, number o | f clusters in output
"""
def __init__(self):
self.word_to_cluster_dict = {}
self.cluster_dict = {}
def cluster(self, embedding, n_clusters=None):
vocab = list(embedding.wv.vocab.keys())
vocab_vectors = np.array([embedding[word] for word in vocab])
if not... | than 1000, limit to 1000
n_clusters = int(len(vocab) * 0.1)
if n_clusters > 1000:
n_clusters = 1000
clustering = MiniBatchKMeans(n_clusters=n_clusters).fit(vocab_vectors)
cluster_labels = clustering.labels_
for i,cluster_label in enumerate(clust... |
ardi69/pyload-0.4.10 | pyload/plugin/extractor/UnZip.py | Python | gpl-3.0 | 1,891 | 0.00899 | # -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import sys
import zipfile
from pyload.plugin.Extractor import Extractor, ArchiveError, CRCError, PasswordError
from pyload.utils import fs_encode
class UnZip(Extractor):
__name = "UnZip"
__type = "extractor"
__version = "1.12... | raise CRCError(badfile)
else:
z.extractall(self.out)
except (zipfile.BadZipfile, zipfile.LargeZipFile), e:
raise ArchiveError(e)
except RuntimeError, | e:
if "encrypted" in e:
raise PasswordError
else:
raise ArchiveError(e)
else:
self.files = z.namelist()
|
menghanY/LeetCode-Python | LinkedList/LinkedListCycleII.py | Python | mit | 474 | 0.018987 | # https://leetcode.com/problems/linked-list-cycle-ii/
fr | om ListNode import ListNode
class Solution(object):
def detectCycle(self, head):
slow,fast = head,head
while True:
if fast == None or fast.next == None : return None
slow = slow.next
fast = fast.next.next
if slow == fast :
break
... | fast = fast.next
return head |
jkitchin/pycse | pycse/tests/test_lisp.py | Python | gpl-2.0 | 720 | 0.013889 | from pycse.lisp import *
def test_symbol():
assert Symbol('setf').lisp == 'setf'
def test_quote():
assert Quote('setf').lisp == "'setf"
def test_sharpquote():
assert SharpQuote('setf').lisp == "#'setf"
def | test_cons():
assert Cons('a', 3).lisp == '("a" . 3)'
def test_Alist():
assert Alist(["a", 1, "b", 2]).lisp == '(("a" . 1) ("b" . 2))'
def test_vector():
assert Vector(["a", 1, 3]).lisp == '["a" 1 3]'
def test_Comma():
assert Comma(Symbol("setf")).lisp == ',setf'
def test_splice():
assert Splice... | ("a"), 1]).lisp == '`(a 1)'
def test_comment():
assert Comment(Symbol("test")).lisp == '; test'
|
hzlf/openbroadcast | website/urls_api.py | Python | gpl-3.0 | 1,715 | 0.002915 | from django.conf.urls.defaults import *
from tastypie.api import Api
#from tastytools.api import Api
from base.api import BaseResource
from bcmon.api import PlayoutResource as BcmonPlayoutResource
from bcmon.api import ChannelResource as BcmonChannelResource
from alibrary.api import MediaResource, ReleaseResource, ... | ce
from istats.api import StatsResource
from fluent_comments.api import CommentResource
api = Api()
# base
api.register(BaseResource())
# bcmon
api.register(BcmonPlayoutResource())
api.register(BcmonChannelResource())
# library
api.register(MediaResource())
api.register(ReleaseResource())
api.register(ArtistResou... | aylistResource())
api.register(PlaylistItemPlaylistResource())
# importer
api.register(ImportResource())
api.register(ImportFileResource())
# exporter
api.register(ExportResource())
api.register(ExportItemResource())
# abcast
api.register(AbcastBaseResource())
api.register(StationResource())
api.register(ChannelReso... |
LukeMurphey/splunk-network-tools | src/bin/network_tools_app/portscan.py | Python | apache-2.0 | 3,454 | 0.003185 | import socket
import sys
import threading
try:
from Queue import Queue, Empty
except:
from queue import Queue, Empty
from collections import OrderedDict
from . import parseintset
DEFAULT_THREAD_LIMIT = 200
CLOSED_STATUS = 'closed'
OPEN_STATUS = 'open'
if sys.version_info.major >= 3:
unicode = str
class... | D_STATUS))
else:
# Note that it is in the open state
self.output_queue.put((host, port, OPEN_STATUS))
sock_instance.close()
self.input_queue.task_done()
self.output_queue.task_done()
def stop_running(self):
self.keep_runni... | LT_THREAD_LIMIT, callback=None, timeout=5):
# Parse the ports if necessary
if isinstance(ports, (str, unicode)):
parsed_ports = parseintset.parseIntSet(ports)
else:
parsed_ports = ports
# Setup the queues
to_scan = Queue()
scanned = Queue()
# Prepare the scanners
# Thes... |
SmartDeveloperHub/agora-fountain | agora/fountain/vocab/onto.py | Python | apache-2.0 | 4,018 | 0.000249 | """
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- | =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
This file is part of the Sma | rt Developer Hub Project:
http://www.smartdeveloperhub.org
Center for Open Middleware
http://www.centeropenmiddleware.com/
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
Copyright (C) 2015 Center for Open Middleware.
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-... |
credativUK/connector-magento | __unported__/magentoerpconnect/magento_model.py | Python | agpl-3.0 | 28,454 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2013 Camptocamp SA
# Copyright 2013 Akretion
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Gene... |
help="A prefix put before the name of imported sales orders.\n"
"For instance, if the prefix is 'mag-', the sales "
"order 100000692 in Magento, will be named 'mag-100000692' "
"in OpenERP."),
'warehouse_id': fields.many2one('stock.warehouse',
... | help='Warehouse used to compute the '
'stock quantities.'),
'website_ids': fields.one2many(
'magento.website', 'backend_id',
string='Website', readonly=True),
'default_lang_id': fields.many2one(
'res.lang',
... |
kyonetca/onionshare | test/onionshare_web_test.py | Python | gpl-3.0 | 1,129 | 0 | """
OnionShare | https://onionshare.org/
Copyright (C) 2014 Micah Lee <micah@micahflee.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any l... | y of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from onionshare import web
from nose import with_setup
def test_generate_slug_length():
"""ge | nerates a 26-character slug"""
assert len(web.slug) == 26
def test_generate_slug_characters():
"""generates a base32-encoded slug"""
def is_b32(string):
b32_alphabet = "01234556789abcdefghijklmnopqrstuvwxyz"
return all(char in b32_alphabet for char in string)
assert is_b32(web.slug)
|
themaxx75/lapare-bijoux | lapare.ca/lapare/settings/base.py | Python | bsd-3-clause | 2,795 | 0.000716 | import sys
from os.path import join, abspath, dirname
# PATH vars
here = lambda *x: join(abspath(dirname(__file__)), *x)
PROJECT_ROOT = here("..")
root = lambda *x: join(abspath(PROJECT_ROOT), *x)
sys.path.insert(0, root('apps'))
ADMINS = (
('Maxime Lapointe', 'maxx@themaxx.ca'),
)
MANAGERS = ADMINS
SHELL_PLUS... | .CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddlewar... | goproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': '../www_lapare_ca.db',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/... |
tlevine/alot | alot/commands/thread.py | Python | gpl-3.0 | 42,235 | 0 | # Copyright (C) 2011-2012 Patrick Totzke <patricktotzke@gmail.com>
# This file is released under the GNU GPL, version 3 or a later revision.
# For further details see the COPYING file
import os
import re
import logging
import tempfile
import argparse
from twisted.internet.defer import inlineCallbacks
import subprocess... | ttings.get_hook('reply_subject')
if reply_subject_hook:
subject = reply_subject_hook(subject)
else:
rsp = settings.get('reply_subject_prefix')
if not subject.lower().startswith(('re:', rsp.lower())):
subject = rsp + subject
envelope.add('Subjec... | bject)
# set From-header and sending account
try:
from_header, account = determine_sender(mail, 'reply')
except AssertionError as e:
ui.notify(e.message, priority='error')
return
envelope.add('From', from_header)
# set To
sender = mai... |
karesansui/karesansui | karesansui/gadget/guesttag.py | Python | mit | 2,641 | 0.004165 | # -*- coding: utf-8 -*-
#
# This file is part of Karesansui.
#
# Copyright (C) 2009-2012 HDE, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without lim... | R
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRI | GHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import web
from karesansui.lib.rest import Rest, auth
from karesansui.lib.checker import C... |
mcr/ietfdb | ietf/wginfo/urls.py | Python | bsd-3-clause | 2,177 | 0.009187 | # Copyright The IETF Trust 2008, All Rights Reserved
from django.conf.urls.defaults import patterns, include
from ietf.wginfo import views, edit, milestones
from django.views.generic.simple import redirect_to
urlpatterns = patterns('',
(r'^$', views.wg_dir),
(r'^summary.txt', redirect_to, { 'url':'/wg/1wg-... | ),
(r'^(?P<acronym>[a-zA-Z0-9-]+)/milestones/charter/$', milestones.edit_milestones, {'milestone_set': "charter"}, "wg_edit_charter_milestones"),
(r'^(?P<acronym>[a-zA-Z0-9-]+)/milestones/charter/reset/$', milestones.reset_charter_milestones, | None, "wg_reset_charter_milestones"),
(r'^(?P<acronym>[a-zA-Z0-9-]+)/ajax/searchdocs/$', milestones.ajax_search_docs, None, "wg_ajax_search_docs"),
(r'^(?P<acronym>[^/]+)/management/', include('ietf.wgchairs.urls')),
)
|
modoboa/modoboa | modoboa/admin/api/v1/urls.py | Python | isc | 548 | 0.001825 | """Admin API urls."""
from rest_framework import routers
from . import viewsets
router = routers.SimpleRouter()
router.register(r"domains", viewsets.DomainViewSet, basename="domain")
router.register(
r"domainaliases", v | iewsets.DomainAliasViewSet, basename="domain_alias")
router.register(r"accounts", viewsets.AccountViewSet, basename="account")
router.register(r"aliases", viewsets.AliasViewSet, basename="alias")
router.register(
r"senderaddresses", view | sets.SenderAddressViewSet, basename="sender_address")
urlpatterns = router.urls
|
quarkslab/qb-sync | ext_ida/dispatcher.py | Python | gpl-3.0 | 14,364 | 0.00181 | #
# Copyright (C) 2012-2014, Quarkslab.
#
# This file is part of qb-sync.
#
# qb-sync 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 Lice | nse, or
# (at your option) any later version.
#
# This program 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... | rt sys
import socket
import select
import base64
import binascii
import re
import ConfigParser
import traceback
HOST = 'localhost'
PORT = 9100
try:
import json
except:
print "[-] failed to import json\n%s" % repr(sys.exc_info())
sys.exit(0)
class Client():
def __init__(self, s_client, s_srv, name):... |
Turivniy/Python_koans | python2/koans/about_methods.py | Python | mit | 5,806 | 0.001206 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Partially based on AboutMethods in the Ruby Koans
#
from runner.koan import *
def my_global_function(a, b):
return a + b
class AboutMethods(Koan):
def test_calling_a_global_function(self):
self.assertEqual(5, my_global_function(2, 3))
# NOTE: ... | s not a SYNTAX error, but a
# runtime error.
def test_calling_fun | ctions_with_wrong_number_of_arguments(self):
try:
my_global_function()
except Exception as exception:
# NOTE: The .__name__ attribute will convert the class
# into a string value.
self.assertEqual(exception.__class__.__name__,
... |
andreaso/ansible | lib/ansible/modules/cloud/ovirt/ovirt_permissions.py | Python | gpl-3.0 | 10,061 | 0.002286 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Red Hat, Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
#... | system':
return connection.system_service()
return getattr(
connection.system_service(),
'%ss_service' % object_type,
None,
)()
def _object_service(connection, module):
object_type = module.params['object_type']
objects_service = _objects_service(connection, object_typ... |
if object_type == 'system':
return objects_service
object_id = module.params['object_id']
if object_id is None:
sdk_object = search_by_name(objects_service, module.params['object_name'])
if sdk_object is None:
raise Exception(
"'%s' object '%s' was not f... |
kbdancer/TPLINKKEY | scan.py | Python | mit | 5,658 | 0.002301 | #!/usr/bin/env python
# coding=utf-8
# code by kbdancer@92ez.com
from threading import Thread
from telnetlib import Telnet
import requests
import sqlite3
import queue
import time
import sys
import os
def ip2num(ip):
ip = [int(x) for x in ip.split('.')]
return ip[0] << 24 | ip[1] << 16 | ip[2] << 8 | ip[3]
... | ad(ip_address_list):
thread_list = []
queue_list = queue.Queue()
hosts = ip_address_list
for host in hosts:
queue_list.put(host)
for x in range(0, int(sys.argv[1])):
thread_list.append(tThread(queue_list))
for | t in thread_list:
try:
t.daemon = True
t.start()
except Exception as e:
print(e)
for t in thread_list:
t.join()
class tThread(Thread):
def __init__(self, queue_obj):
Thread.__init__(self)
self.queue = queue_obj
def run(self):
... |
hos7ein/firewalld | src/firewall/functions.py | Python | gpl-2.0 | 17,408 | 0.004193 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007,2008,2011,2012 Red Hat, Inc.
#
# Authors:
# Thomas Woerner <twoerner@redhat.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2... | urn False
return True
def checkIP6nMask(ip):
if "/" in ip:
addr = ip[:ip.index("/")]
mask = ip[ip.index("/")+1:]
if len(addr) < 1 or len(mask) < 1:
return False
else:
addr = ip
mask = None
if not checkIP6(addr):
return False
if mask:
... | return False
return True
def checkProtocol(protocol):
try:
i = int(protocol)
except ValueError:
# string
try:
socket.getprotobyname(protocol)
except socket.error:
return False
else:
if i < 0 or i > 255:
return False
r... |
pyfa-org/Pyfa | gui/utils/anim_effects.py | Python | gpl-3.0 | 1,706 | 0 | import math
def OUT_CIRC(t, b, c, d):
t = float(t)
b = float(b)
c = float(c)
d = float(d)
t = t / d - 1
return c * math.sqrt(1 - t * t) + b
def OUT_QUART(t, b, c, d):
t = float(t)
b = float(b)
c = float(c)
d = float(d)
t = t / d - 1
return -c * (t * t * t * t - 1)... | c * t * t * t + b
def OUT_QUAD(t, b, c, d):
t = float(t)
b = float(b)
c = float(c)
d = float(d)
t /= d
return -c * t * (t - 2) + b
def OUT_BOUNCE(t, b, c, d):
t = float(t)
b = float(b)
c = float(c)
d = float( | d)
t /= d
if t < (1 / 2.75):
return c * (7.5625 * t * t) + b
elif t < (2 / 2.75):
t -= (1.5 / 2.75)
return c * (7.5625 * t * t + .75) + b
elif t < (2.5 / 2.75):
t -= (2.25 / 2.75)
return c * (7.5625 * t * t + .9375) + b
else:
t -= (2.625 / 2.75)
... |
kiddinn/plaso | tests/parsers/esedb_plugins/msie_webcache.py | Python | apache-2.0 | 3,923 | 0.001784 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Microsoft Internet Explorer WebCache database."""
import unittest
from plaso.lib import definitions
from plaso.parsers.esedb_plugins import msie_webcache
from tests.parsers.esedb_plugins import test_lib
class MsieWebCacheESEDBPluginTest(test_lib.ESEDB... | s\\test\\AppData\\Local\\Microsoft\\Windows\\'
'INetCache\\IE\\'),
'name': 'Content',
'set_identifier': 0,
'timestamp_desc': definitions.TIME_DESCRIPTION_LAST_ACCESS}
self.CheckEventValues(storage_writer, events[567], expected_event_values)
def testProcessOnDatabaseWithPartit... | ithPlugin(
['PartitionsEx-WebCacheV01.dat'], plugin)
self.assertEqual(storage_writer.number_of_events, 4014)
self.assertEqual(storage_writer.number_of_extraction_warnings, 3)
self.assertEqual(storage_writer.number_of_recovery_warnings, 0)
# The order in which ESEDBPlugin._GetRecordValues() gen... |
jbedorf/tensorflow | tensorflow/python/data/experimental/kernel_tests/serialization/dataset_serialization_test_base.py | Python | apache-2.0 | 26,060 | 0.004298 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ts: See `run_core_tests`.
sparse_tensors: See `run_core_tests`.
Raises:
AssertionError if test fails.
"""
self.verify_run_with_breaks(
ds_fn, [num_outputs], num_outputs, sparse_tensors=sparse_tensors)
| def verify_exhausted_iterator(self, ds_fn, num_outputs, sparse_tensors=False):
"""Verifies that saving and restoring an exhausted iterator works.
An exhausted iterator is one which has returned an OutOfRange error.
Args:
ds_fn: See `run_core_tests`.
num_outputs: See `run_core_tests`.
s... |
wannaphongcom/flappy | flappy/display3d/__init__.py | Python | mit | 279 | 0.003584 |
from flappy.display3d.v | ertexbuffer3d import VertexBuffer3D, VertexBuffer3DFormat
from flappy.display3d.indexbuffer3d import IndexBuffer3D
from flappy. | display3d.program3d import Program3D
from flappy.display3d.texture import Texture
from flappy.display3d.scene3d import Scene3D
|
kaefik/zadanie-python | echoserver.py | Python | mit | 1,395 | 0.002867 | import asyncio
import logging
import concurrent.futures
class EchoServer(object):
"""Echo server class"""
def __init__(self, host, port, loop=None):
self._loop = loop or asyncio.get_event_loop()
self._server = asyncio.start_server(self.handle_connection, host=host, port=port)
def start(s... | run_forever()
def stop(self, and_loop=True):
self._server.close()
if and_loop:
self._loop.close()
@asyncio.coroutine
def handle_connection(self, reader, writer):
peername = writer.get_extra_info('peername')
logging.info('Accepted connection from {}'.format(peern... | a = yield from asyncio.wait_for(reader.readline(), timeout=10.0)
writer.write(data)
except concurrent.futures.TimeoutError:
break
writer.close()
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
server = EchoServer('127.0.0.1', 8899)
tr... |
arokem/pyAFQ | AFQ/utils/tests/test_parallel.py | Python | bsd-2-clause | 1,135 | 0 | import numpy as np
import numpy.testing as npt
import AFQ.utils.parallel as para
def power_it(num, n=2):
# We define a function of the right form for parallelization
return num ** n
def test_parfor():
my_array = np.arange(100).reshape(10, 10)
i, j = np.random.randint(0, 9, 2)
my_list = list(my_... | avel())
for engine in ["joblib", "dask", "serial"]:
for backend in ["threading", "multiprocessing"]:
npt.assert_equal | (para.parfor(power_it,
my_list,
engine=engine,
backend=backend,
out_shape=my_array.shape)[i, j],
power_it(my_array[i, j]))
... |
aerobit/sparky | sparky.py | Python | unlicense | 5,633 | 0.00213 | #!/usr/bin/env python3.4
# dotslash for local
from flask import Flask, render_template, request, redirect
from werkzeug.contrib.fixers import ProxyFix
from urllib.request import urlopen, Request
from urllib.parse import urlparse
from omxplayer import OMXPlayer
from youtube_dl import YoutubeDL
from youtube_dl.utils imp... | =True)
def log(text):
print("[sparky] %s" % text)
global last_logged_message
last_logged_message = text
def get_last_logged_message():
global last_logged_m | essage
return last_logged_message
def get_player():
global player
if player is not None and player.has_finished():
player = None
title = None
return player
if __name__ == '__main__':
app.run("0.0.0.0", debug=True)
|
twisted/quotient | xquotient/test/historic/test_mta2to3.py | Python | mit | 512 | 0.001953 | from axiom.test.historic.stubloader import StubbedTest
from xquotient.mail import MailTransfer | Agent
from axiom.userbase import LoginSystem
class MTAUpgraderTest(StubbedTest):
def testMTA2to3(self):
"""
Make sure MailTransferAgent upgraded OK and that its
"userbase" attribute refers to the store's userbase.
"""
mta = self.store.fin | dUnique(MailTransferAgent)
self.assertIdentical(mta.userbase,
self.store.findUnique(LoginSystem))
|
matrixise/gateway | docs/conf.py | Python | bsd-3-clause | 8,914 | 0.00718 | # -*- coding: utf-8 -*-
#
# Gateway documentation build configuration file, created by
# sphinx-quickstart on Tue Sep 25 06:46:30 2012.
#
# 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
# autogenerated file.
#
# All... | (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' w | ill be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ign... |
prheenan/BioModel | BellZhurkov/Python/TestExamples/Examples/Bell_Examples.py | Python | gpl-2.0 | 3,266 | 0.013778 | # force floating point division. Can still use integer with //
from __future__ import division
# This file is used for importing the common utilities classes.
import numpy as np
import matplotlib.pyplot as plt
import sys
sys.path.append("../../../../")
import BellZhurkov.Python.TestExamples.TestUtil.Bell_Test_Data as ... | plt.title("Woodside and Block, Figure 6a (2016)")
plt.legend(loc='lower center')
fig.savefig("./Woodside2016_Figure6.png")
def RunSchlierf2006Figure1a():
DataToTest = Data.Schlierf2006Figure1a()
Forces,Folding = (DataToTest.Forces,DataToTest.RatesFold)
# everything in SI initially
vary = dict... | k0=True,
DeltaG=False,
DeltaX=True)
GuessDict = dict(beta=1/(4.1e-21),
k0=0.35,
DeltaX=5e-10,
DeltaG=0)
opt = dict(Values=GuessDict,
Vary=vary)
infFold = BellModel.BellZurkovFit(Forces... |
ahmadiga/min_edx | lms/djangoapps/survey/models.py | Python | agpl-3.0 | 8,631 | 0.001738 | """
Models to support Course Surveys feature
"""
import logging
from lxml import etree
from collections import OrderedDict
from django.db import models
from student.models import User
from django.core.exceptions import ValidationError
from model_utils.models import TimeStampedModel
from survey.exceptions import Surv... | ser_id not in results and num_users < limit_num_users:
results[user_id] = | OrderedDict()
num_users = num_users + 1
if user_id in results:
results[user_id][answer.field_name] = answer.field_value
return results
@classmethod
def save_answers(cls, form, user, answers, course_key):
"""
Store answers to the form for a ... |
bdarnell/tornado_http2 | setup.py | Python | apache-2.0 | 702 | 0 | import sys
try:
import setuptools
from setuptools import setup
except ImportError:
setuptools = None
from dist | utils.core import setup
version = '0.0.1'
kwargs = {}
if setuptools is not None:
kwargs['install_requires'] = ['tornado>=4.3']
if sys.version_info < (3, 4):
kwargs['install_requires'].append('enum34')
setup(
name='tornado_http2',
version=version,
packages=['tornado_http2', 'tornado_http... | 'test.crt',
'test.key',
],
},
**kwargs)
|
akheron/stango | tests/test_generate.py | Python | mit | 6,958 | 0.000862 | import io
import os
import unittest
from stango import Stango
from stango.files import Files
from . import StangoTestCase, make_suite, view_value, view_template
dummy_view = view_value('')
class GenerateTestCase(StangoTestCase):
def setup(self):
self.tmp = self.tempdir()
self.manager = Stango()
... | le.txt')) as fobj:
self.eq(fobj.read(), 'barfoo')
def test_view_returns_a_bytes_object(self):
self.manager.files = Files(
('', view_value(b'\xde\xad\xbe\xef')),
)
self.manager.generate(self.tmp)
self.eq(os.listdir(self.tmp), ['index.html'])
with open... | view_returns_a_bytearray_object(self):
self.manager.files = Files(
('', view_value(bytearray(b'\xba\xdc\x0f\xfe'))),
)
self.manager.generate(self.tmp)
self.eq(os.listdir(self.tmp), ['index.html'])
with open(os.path.join(self.tmp, 'index.html'), 'rb') as fobj:
... |
kerimlcr/ab2017-dpyo | ornek/moviepy/moviepy-0.2.2.12/moviepy/video/fx/__init__.py | Python | gpl-3.0 | 121 | 0 | """
T | his module contains transformation functions (clip->clip)
One file for one fx. The file's name is the fx's name
"" | "
|
steeve/libtorrent | set_version.py | Python | bsd-3-clause | 1,975 | 0.021772 | #! /usr/bin/env python
import os
import sys
import glob
version = (int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))
def substitute_file(name):
subst = ''
f = open(name)
for l in f:
if '#define LIBTORRENT_VERSION_MAJOR' in l and name.endswith('.hpp'):
l = '#define LIBTORRENT_VERSION_MAJO... | d.%d',\n" % (version[0], version[1], version[2])
subst += l
f.close()
open(name, 'w+').write(subst)
substitute_file('include/libtorrent/version.hpp')
substitute_file('CMakeLists.txt')
substitute_file('configure.ac')
subst | itute_file('bindings/python/setup.py')
substitute_file('docs/gen_reference_doc.py')
for i in glob.glob('docs/*.rst'):
substitute_file(i)
substitute_file('Jamfile')
|
ctag/cpe453 | JMRI/jython/Jynstruments/ThrottleWindowToolBar/USBThrottle.jyn/LogitechCordlessRumblePad2.py | Python | gpl-2.0 | 5,884 | 0.013936 | print "Loading USBDriver : Logitech Cordless RumblePad 2"
class USBDriver :
def __init__(self):
self.componentNextThrottleFrame = "Hat Switch" # Component for throttle frames browsing
self.valueNextThrottleFrame = 0.5
self.componentPreviousThrottleFrame = "Hat Switch"
| self.valuePreviousThrottleFrame = 1
self.componentNextRunningThrottleFrame = "" # Component for running throttle frames browsing
self.valueNextRunningThrottleFrame = 0.75
self.componentPreviousRunningThrottleFrame = ""
self.valuePreviousRunningThrottleFrame = 0.25
... | current window
self.componentNextRosterBrowse = "Hat Switch" # Component for roster browsing
self.valueNextRoster = 0.75
self.componentPreviousRosterBrowse = "Hat Switch"
self.valuePreviousRoster = 0.25
self.componentRosterSelect = "Button 4" # Component to sel... |
paulsmith/geodjango | django/contrib/gis/db/backend/postgis/creation.py | Python | bsd-3-clause | 9,184 | 0.005989 | from django.conf import settings
from django.core.management import call_command
from django.db import connection
from django.test.utils import _set_autocommit, TEST_DATABASE_PREFIX
import os, re, sys
def getstatusoutput(cmd):
"A simpler version of getstatusoutput that works on win32 platforms."
stdin, stdout,... | _db_name = settings.TEST_DATABASE_NAME
else:
test_db_name = TEST_DATABASE_PREFIX + settings.DATABASE_NAME
return test_db_name
else:
if not settings.DATABASE_NAME:
raise Exception('must configure DATABASE_NAME in settings.py')
return settings.DATABASE_NAME
def... | name, verbosity=1):
"""
This routine loads up the PostGIS SQL files lwpostgis.sql and
spatial_ref_sys.sql.
"""
# Getting the path to the PostGIS SQL
try:
# POSTGIS_SQL_PATH may be placed in settings to tell GeoDjango where the
# PostGIS SQL files are located. This is especi... |
tp7/assfc | tests/font_parsing_tests.py | Python | mit | 5,846 | 0.004961 | import logging
import unittest
from functools import reduce
from ass_parser import StyleInfo, UsageData
from font_loader import TTFFont, FontInfo, FontLoader, TTCFont, FontWeight
from tests.common import get_file_in_test_directory
class FontLoaderTests(unittest.TestCase):
def test_returns_all_not_found_fonts(self)... | '))
self.assertIn('Vanta Thin', font.get_info().names)
def test_parses_fonts_with_utf8_platform_id_0_strings(self):
font = TTFFont(get_file_in_test_directory('SUSANNA_.otf'))
self.assertIn('Susanna', font.get_info().names)
def test_detects_bold_weight(self):
| font = TTFFont(get_file_in_test_directory('Caviar Dreams Bold.ttf'))
self.assertEqual(font.get_info().weight, FontWeight.FW_BOLD)
def test_detects_regular_weight(self):
font = TTFFont(get_file_in_test_directory('Jorvik.ttf'))
self.assertEqual(font.get_info().weight, FontWeight.FW_NORM... |
jhutar/spacewalk | backend/cdn_tools/manifest.py | Python | gpl-2.0 | 8,783 | 0.001139 | # Copyright (c) 2016 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of G... | ry:
for content in product_data['productContent']:
content = content['con | tent']
product.add_repository(content['label'], content['contentUrl'])
except KeyError:
print("ERROR: Cannot access required field in product '%s'" % product.get_id())
raise
def _load_entitlements(self, zip_file):
files = zip_file.namelist()
entitleme... |
vladimir-v-diaz/securesystemslib | securesystemslib/_vendor/ed25519/ed25519.py | Python | mit | 7,618 | 0.000656 | # ed25519.py - Optimized version of the reference implementation of Ed25519
#
# Written in 2011? by Daniel J. Bernstein <djb@cr.yp.to>
# 2013 by Donald Stufft <donald@stufft.io>
# 2013 by Alex Gaynor <alex.gayn | or@gmail.com>
# 2013 by Greg Price <price@mit.edu>
#
# To the extent possible under law, the author(s) have dedicated all copyright
# and related and neighboring rights to this software to the public domain
# worldwide. This software is distributed without any warranty.
#
# You should have received a copy of... | .
"""
NB: This code is not safe for use with secret keys or secret data.
The only safe use of this code is for verifying signatures on public messages.
Functions for computing the public key of a secret key and for signing
a message are included, namely publickey_unsafe and signature_unsafe,
for testing purposes only... |
ConservationInternational/ldmp-qgis-plugin | LDMP/calculate_numba.py | Python | gpl-2.0 | 4,469 | 0.000671 | import os
import json
import numpy as np
try:
from numba.pycc import CC
cc = CC('calculate_numba')
except ImportError:
# Will use these | as regular Python functions if numba is not present.
class CCSubstitute( | object):
# Make a cc.export that doesn't do anything
def export(*args, **kwargs):
def wrapper(func):
return func
return wrapper
cc = CCSubstitute()
@cc.export('ldn_recode_traj', 'i2[:,:](i2[:,:])')
def ldn_recode_traj(x):
# Recode trajectory into deg, st... |
isrealconsulting/codepy27 | main.py | Python | apache-2.0 | 3,227 | 0.00093 | #!/usr/bin/env python
# Copyright 2015 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | format(MAILGUN_DOMAIN_NAME)
data = {
'from': 'Isreal Consulting Webmaster <webmaster@{}>'.format(MAILGUN_DOMAIN_NAME),
'to': recipient,
'subject': 'This is an example email from ICLLC code site codepy',
'text': 'Test message f | rom codepy-1'
}
resp, content = http.request(url, 'POST', urlencode(data))
if resp.status != 200:
raise RuntimeError(
'Mailgun API error: {} {}'.format(resp.status, content))
# [END simple_message]
# [START complex_message]
def send_complex_message(recipient):
http = httplib2.Htt... |
wtsi-hgi/cookie-monster | cookiemonster/tests/processor/_mocks.py | Python | gpl-3.0 | 2,448 | 0.002451 | """
Legalese
--------
Copyright (c) 2015, 2016 Genome Research Ltd.
Author: Colin Nolan <cn13@sanger.ac.uk>
This file is part of Cookie Monster.
Cookie Monster 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; ei... | ` object.
:param priority: (optional) the priority of the rule
:return: the created rule
"""
return Rule(
lambda file_update, data_environment: True,
lambda file_update, data_environment: True,
"my_rule",
priority=priority
)
def create_magic_mock_cookie_jar() -> Coo... | Jar - has the implementation of a CookieJar all methods are implemented using magic mocks
and therefore their usage is recorded.
:return: the created magic mock
"""
cookie_jar = InMemoryCookieJar()
original_get_next_for_processing = cookie_jar.get_next_for_processing
original_enrich_cookie = coo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.