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
plotly/python-api
packages/python/plotly/plotly/validators/layout/ternary/caxis/_nticks.py
Python
mit
505
0.00198
import _plotly_utils.basevalidators class NticksValidator(_plotly_utils.basevalidators.IntegerValidator): def __init__( self, plotly_name="nticks", parent_name="layout.tern
ary.caxis", **kwargs ): super(NticksVali
dator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), min=kwargs.pop("min", 1), role=kwargs.pop("role", "style"), **kwargs )
VikParuchuri/percept
percept/conf/base.py
Python
apache-2.0
3,688
0.005965
""" Application level configuration and logging """ import os import global_settings import sys from logging.config import dictConfig from importlib import import_module import logging log = logging.getLogger(__name__) class Settings(object): """ Configuration class for percept """ settings_list = No...
.MODULE_VARIABLE) log.exception(error_message) self._initialize(settings_module) self._configure_logging() def __getattr
__(self, name): """ If a class is trying to get settings (attributes on this class) """ #If settings have not been setup, do so if not self.configured: self._setup() #Return setting if it exists as a self attribute, None if it doesn't if name in self....
RedhawkSDR/framework-codegen
redhawk/codegen/jinja/java/ports/mapping.py
Python
lgpl-3.0
1,372
0.000729
# # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is part of REDHAWK core. # # REDHAWK core is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free ...
SE. See the GNU Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see http://www.gnu.org/licenses/. # from redhawk.codegen.lang import java from redhawk.codeg
en.jinja.mapping import PortMapper class JavaPortMapper(PortMapper): def _mapPort(self, port, generator): javaport = {} javaport['javaname'] = java.identifier('port_'+port.name()) javaport['javatype'] = generator.className() javaport['constructor'] = generator.constructor(port.name(...
claesenm/HPOlib
HPOlib/benchmark_util.py
Python
gpl-3.0
3,556
0.001406
## # wrapping: A program making it easy to use hyperparameter # optimization software. # Copyright (C) 2013 Katharina Eggensperger and Matthias Feurer # # 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 Found...
ams: raise ValueError("You either try to use arguments with only one lea" "ding minus or try to specify a hyperparameter bef" "ore the --params argument. %s" % " ".join(cli_args)) elif not found_params: ...
raise ValueError("Illegal command line string, expected a hyperpara" "meter starting with - but found %s" % (arg,)) return args, parameters
justinvanwinkle/wextracto
wex/py2compat.py
Python
bsd-3-clause
817
0.001224
""" Compatability fixes to make Python 2.7 look more like Python 3. The general approach is to code using the common subset offered by 'six'. The HTTPMessage class has a different interface. This work-arounds makes the Python 2.7 look enough like the Python 3 for the Wextracto code to work. """ import six if six.P...
mport HTTPMessage def get_content_subtype(self): return self.getsubtype() HTTPMessage.get_content_subtype = get_content_subtype def get_content_charset(self): return self.getparam('charset') HTTPMessage.get_content_charset = get_content_charset def parse_headers(fp): retu...
assert parse_headers # pragma: no cover
willingc/portal
systers_portal/users/models.py
Python
gpl-2.0
6,677
0
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django_countries.fields import CountryField from community.utils import get_groups from membership.constants imp...
_str @receiver(post_save, sender=User) def create_systers_user(sender, instance, created, **kwargs):
"""Keep User and SystersUser synchronized. Create a SystersUser instance on receiving a signal about new user signup. """ if created: if instance is not None: systers_user = SystersUser(user=instance) systers_user.save()
manojpandey/devsoc-matrix
data_updater.py
Python
mit
556
0
#!/usr/bin/env python # -*- -*- import requests import json members_file = open('members.json', 'r') members_data = json.loads(members_file.read()) graph_url = "http:
//graph.facebook.com/" data = {} for member in members_data: img_url = requests.get( graph_url + str(member['fbid']) + '/picture?type=large&redirect=false' ).json()['data']['url'] # print member['fbid'] # print img_url data[member["fbid"]] = [member["name"], img_url] dat...
ps(data))
blankclemens/tools-iuc
data_managers/data_manager_hisat2_index_builder/data_manager/hisat2_index_builder.py
Python
mit
3,657
0.025978
#!/usr/bin/env python # Based heavily on the Bowtie 2 data manager wrapper script by Dan Blankenberg from __future__ import print_function import argparse import os import shlex import subprocess import sys from json import dumps, loads DEFAULT_DATA_TABLE_NAME = "hisat2_indexes" def get_id_name( params, dbkey, fast...
_argument( '--fasta_dbkey', dest='fasta_dbkey', action='store', type=str, default=None ) parser.add_argument( '--fasta_description', dest='fasta_description', action='store', type=str, default=None ) parser.add_argument( '--data_table_name', dest='d
ata_table_name', action='store', type=str, default='hisat2_indexes' ) parser.add_argument( '--indexer_options', dest='indexer_options', action='store', type=str, default='' ) options = parser.parse_args() filename = options.output params = loads( open( filename ).read() ) data_manager_dict = {} ...
gdsfactory/gdsfactory
gdsfactory/components/coupler_ring.py
Python
mit
2,846
0
from typing impor
t Optional import gdsfactory as gf from gdsfactory.component import Component from gdsfactory.components.bend_euler import bend_euler from gdsfactory.components.coupler90 import coupler90 as coupler90function from gdsfactory.components.coupler_straight import ( coupler_straight as coupler_
straight_function, ) from gdsfactory.cross_section import strip from gdsfactory.snap import assert_on_2nm_grid from gdsfactory.types import ComponentFactory, CrossSectionFactory @gf.cell def coupler_ring( gap: float = 0.2, radius: float = 5.0, length_x: float = 4.0, coupler90: ComponentFactory = coupl...
djkonro/client-python
kubernetes/test/test_v1_event_source.py
Python
apache-2.0
843
0.002372
# coding: utf-8 """ Kubernetes No descripti
on provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.7.4 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernet...
ntSource class TestV1EventSource(unittest.TestCase): """ V1EventSource unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1EventSource(self): """ Test V1EventSource """ model = kubernetes.client.models.v1_event_source.V1EventS...
pando85/cherrymusic
web/cherrymusic/apps/api/v1/tests/views/test_track_view.py
Python
gpl-3.0
1,605
0.003115
from rest_framework import status from rest_framework.test import APITestCase, APIClient from django.core.urlresolvers import reverse from cherrymusic.apps.core.models import User, Track from cherrymusic.apps.api.v1.serializers import TrackSerializer from cherrymusic.apps.api.v1.tests.views import UNAUTHENTICATED_RE...
user=self.user) self.serializer = TrackSerializer() def test_unauthenticated_track_query(self): url = reverse('api:track-list') client = APIClient() response = client.get(url) self.assertEqual(response.data, UNAUTHENTICATED_RESPONSE) def test_track_q
uery(self): url = reverse('api:track-list') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) tracks = Track.objects.all() tracks_json = [self.serializer.to_representation(track) for track in tracks] self.assertEqual(response.da...
snakeleon/YouCompleteMe-x86
third_party/ycmd/ycmd/watchdog_plugin.py
Python
gpl-3.0
3,694
0.019491
# Copyright (C) 2013 Google Inc. # # This file is part of ycmd. # # ycmd 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. # # ycmd is di...
from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from builtins import * # noqa import time import copy import logging from threading import Thread, Lock from ycmd.handlers import ServerShutdown _logger = logging.getLogger( __name__ ) # This class impleme...
ea here is to decorate every route handler automatically so that on # every request, we log when the request was made. Then a watchdog thread checks # every check_interval_seconds whether the server has been idle for a time # greater that the passed-in idle_suicide_seconds. If it has, we kill the # server. # # We want ...
StyleShare/flask-volatile
flask_volatile/transaction.py
Python
mit
5,200
0.000192
""":mod:`flask.ext.volatile.transaction` --- Key-level transactions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2011 by Hong Minhee, StyleShare :license: MIT License, see :file:`LICENSE` for more details. """ import time from werkzeug.contrib.cache import BaseCache __all__ = '...
y made by :class:`Transaction`. You don't have t
o instantiate it directly. """ def __init__(self, transaction, tried_number=0): if not isinstance(transaction, Transaction): raise TypeError('expected a flask.ext.volatile.transaction.' 'Transaction, but %r passed' % transaction) self.transaction = trans...
AnshulYADAV007/Lean
Algorithm.Python/Benchmarks/HistoryRequestBenchmark.py
Python
apache-2.0
1,422
0.009155
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the Lice...
r agr
eed 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. from clr import AddReference AddReference("Sy...
IngmarStein/swift
benchmark/scripts/compare_perf_tests.py
Python
apache-2.0
13,004
0.000308
#!/usr/bin/python # -*- coding: utf-8 -*- # ===--- compare_perf_tests.py -------------------------------------------===// # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library...
""" Create markdown formatted table """ test_name_width = max_width(ratio_list, title='TEST', key_len=True
) new_time_width = max_width(new_results, title=new_branch) old_time_width = max_width(old_results, title=old_branch) delta_width = max_width(delta_list, title='DELTA (%)') markdown_table_header = "\n" + MARKDOWN_ROW.format( "TEST".ljust(test_name_width), old_branch.ljust(old_time_width...
yamahata/tacker
tacker/vm/drivers/nova/nova.py
Python
apache-2.0
9,504
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013, 2014 Intel Corporation. # Copyright 2013, 2014 Isaku Yamahata <isaku.yamahata at intel com> # <isaku.yamahata at gmail com> # All Rights Reserved. # # # Licensed under the Apache License, Version 2.0 (the "License"); ...
port_data['fixed_ips'] = [{'subnet_id': subnet_id}] # See api.v2.base.prepare_request_body() for attr, attr_vals in attributes.RESOURCE_ATTRIBUTE_MAP[ attributes.PORTS].iteritems(): if not attr_vals.get('allow_post', False): continue i...
port_data[attr] = attr_vals['default'] LOG.debug(_('port_data %s'), port_data) port = plugin._core_plugin.create_port(context, {'port': port_data}) LOG.debug(_('port %s'), port) return port['id'] def create(self, plugin, context, device): # typical required arguments are...
gdestuynder/MozDef
cron/rotateIndexes.py
Python
mpl-2.0
8,822
0.003401
#!/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/. # Copyright (c) 2014 Mozilla Corporation # set this to run as a cronjob at 00:00 UTC to create th...
_pruning', '20,0,0', options.configfile).split(',') ) options.weekly_rotation_indices = list(getConfig( 'weekly_rotation_indices', 'events', options.configfile).split(',') ) default_mapping_loca
tion = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'defaultMappingTemplate.json') options.default_mapping_file = getConfig('default_mapping_file', default_mapping_location, options.configfile) options.refresh_interval = getConfig('refresh_interval', '1s', options.configfile) options.number_of_s...
jvantuyl/exim_ses_transport
exim_ses_transport/run.py
Python
lgpl-3.0
880
0.002273
""" Exim SES Transport Entry Points """ # Copyright 2013, Jayson Vantuyl <jvantuyl@gmail.com> # # This file is part of exim_ses_transport. # # exim_ses_transport is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Fou...
n 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 Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License # along
with exim_ses_transport. If not, see <http://www.gnu.org/licenses/>. from transport import SesSender def main(): SesSender().run()
tchellomello/home-assistant
homeassistant/components/velbus/binary_sensor.py
Python
apache-2.0
917
0
"""Support for Velbus Binary Sensors.""" import logging from homeassistant.components.binary_sensor import BinarySensorEntity from . import VelbusEntity from .const import DOMAIN _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, entry, async_add_entities): """Set up Velbus binary sensor b...
a[DOMAIN][entry.entry_id]["cntrl"] modules_data = hass.data[DOMAIN][entry.entry_id]["binary_sensor"] entities = [] for address, channel in modules_data: module = cntrl.get_module(address) entities.append(VelbusBinarySensor(module, channel)) async_add_entities(entities) class VelbusBina...
resentation of a Velbus Binary Sensor.""" @property def is_on(self): """Return true if the sensor is on.""" return self._module.is_closed(self._channel)
kylon/pacman-fakeroot
test/pacman/tests/fileconflict031.py
Python
gpl-2.0
408
0.002451
self.descript
ion = "Dir->file transition filesystem conflict resolved by removal (with subdirectory)" lp1 = pmpkg("foo") lp1.files = ["foo/bar/"] self.addpkg2db("local", lp1) sp1 = pmp
kg("foo", "2-1") sp1.conflicts = ["foo"] sp1.files = ["foo"] self.addpkg2db("sync", sp1) self.args = "-S %s" % sp1.name self.addrule("PACMAN_RETCODE=0") self.addrule("PKG_VERSION=foo|2-1") self.addrule("FILE_EXIST=foo")
alanjw/GreenOpenERP-Win-X86
python/Lib/site-packages/_xmlplus/utils/qp_xml.py
Python
agpl-3.0
6,160
0.014123
# # qp_xml: Quick Parsing for XML # # Written by Greg Stein. Public Domain. # No Copyright, no Rights Reserved, and no Warranties. # # This module is maintained by Greg and is available as part of the XML-SIG # distribution. This module and its changelog can be fetched at: # http://www.lyra.org/cgi-bin/viewcvs.cgi/x...
_dump_recurse(f, child, namespaces, elem.lang) f.write(child.following_cdata) if elem.ns: f.write('</ns%d:%s>' % (namespaces[elem.ns], elem.name)) else: f.write('</%s>' % elem.name)
else: f.write('/>')
twisted/sine
sine/test/historic/test_sipDispatcherService2to3.py
Python
mit
412
0.002427
""
" Tests for the upgrade of L{SIPDispatcherService} from version 2 to version 3. """ from axiom.test.historic import stubloader from axiom.userbase import LoginSystem from sine.sipserver import SIPDispatcherService class SIPServerTest(stubloader.StubbedTest): def test_upgrade(self): ss = self.store.findUn...
chispita/epiwork
apps/pollster/migrations/0011_fix_google_fusion_map.py
Python
agpl-3.0
16,680
0.007914
# encoding: utf-8 import datetime from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): def forwards(self, orm): orm.ChartType.objects.all().filter(shortname='google-fusion-map').delete() t, _ = orm.ChartType.objects.all().get_or_cr...
db.models.fields.related.ForeignKey', [], {'to': "orm['pollster.VirtualOptionType']", 'null': 'True', 'blank': 'True'}) }, 'pollster.question': { 'Meta': {'ordering': "['survey', 'ordinal']", 'object_name': 'Question'}, 'da
ta_name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'data_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['pollster.QuestionDataType']"}), 'description': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}), 'erro...
edx/edx-enterprise
integrated_channels/cornerstone/urls.py
Python
agpl-3.0
483
0.00207
# -*- coding: utf-8 -*- """ URL definitions for Cornerstone API. """ from django.conf.urls import url fr
om integrated_channels.cornerstone.views import CornerstoneCoursesListView, CornerstoneCoursesUpdates urlpatterns = [ url( r'^course-list$', CornerstoneCoursesListView.as_view(), name='cornerstone-course-list' ), url( r'course
-updates', CornerstoneCoursesUpdates.as_view(), name='cornerstone-course-updates' ) ]
prashanthr/wakatime
wakatime/packages/pygments_py3/pygments/lexers/javascript.py
Python
bsd-3-clause
47,525
0.000779
# -*- coding: utf-8 -*- """ pygments.lexers.javascript ~~~~~~~~~~~~~~~~~~~~~~~~~~ Lexers for JavaScript and related languages. :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import RegexLexer, include, ...
include('root'), ], 'waitfor': [ (r'\n', Punctuation, '#pop'), (r'\bfrom\b', Keyword), include('root'), ], 'root': [
include('commentsandwhitespace'), (r'/(?! )(\\.|[^[/\\\n]|\[(\\.|[^\]\\\n])*])+/' r'([gim]+\b|\B)', String.Regex), (r'\?|:|_(?=\n)|==?|!=|-(?!>)|[<>+*/-]=?', Operator), (r'\b(and|or|isnt|is|not|but|bitwise|mod|\^|xor|exists|' r'does...
AnselCmy/ARPS
tmsvm/src/ctmutil.py
Python
mit
3,391
0.026601
#!/usr/bin/python #_*_ coding: utf-8 _*_ #author:张知临 zhzhl202@163.com #Filename: ctmutil.py from random import * import measure import math import os.path c_p = os.path.dirname(os.getcwd())+"/" #tc_splitTag="\t" #str_splitTag = "^" #分词分割的标记 def cons_pro_for_svm(label,text,dic,local_fun=measure.tf,...
x[index]+=1.0 else: x[index]=1.0 # 计算特征向量的特征权重 for key in x.keys(): x[key] = local_fun(x[key])*global_weight.get(key) #计算特征向量的模 vec_sum = 0.0 for key in x.keys(): if x[key]!=0: vec_sum+=x[key]**2.0 #对向量进...
y=lambda dic:dic[0],reverse=False) # sorted_keys = x.keys() # sorted_keys.sort() # for key in sorted_keys: # real_x[key]=x[key] return y,[x] def cons_vec_for_cla(text,dic,glo_aff_list=[],normalization=1): '''给定词典、全局因子,对文本构造特征向量。需要设定是否需要对向量进行归一化 vector 从0开始算起。 ''' vec = [...
realmarcin/data_api
lib/doekbase/data_api/cache.py
Python
mit
847
0.003542
""" Add simple, flexible caching layer. Uses `
dogpile caching http://dogpilecache.readthedocs.org/en/latest/index.html`_. """ __author__ = 'Dan Gunter <dkgunter@lbl.gov>' __date__ = '9/26/15' from dogpile.cache import make_region def my_key_generator(namespace, fn, **kw): fname = fn.__name__ def generate_key(*arg): return namespace + "_" + fname...
e_region( function_key_generator=my_key_generator ).configure( 'dogpile.cache.redis', arguments={ 'host': redis_host, 'port': redis_port, 'db': 0, 'redis_expiration_time': 60 * 60 * 2, # 2 hours 'distributed_lock': True } ...
adieyal/billtracker
code/billtracker/bills/migrations/0005_auto__del_field_billstage_stage.py
Python
bsd-3-clause
3,234
0.006494
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'BillStage.stage' db.delete_column(u'bills_billstage', 'stage') def backwards(self, o...
everse this migration. 'BillStage.stage' and its values cannot be restored.") models = { u'bills.bill': { 'Meta': {'object_name': 'Bill'}, 'code': ('django.db.models.fields.CharField', [], {'max_length': '10'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_...
u'bills.billstage': { 'Meta': {'object_name': 'BillStage'}, 'bill': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'stages'", 'to': u"orm['bills.Bill']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, u'bills...
OCA/purchase-workflow
purchase_request_exception/tests/test_purchase_request_exception.py
Python
agpl-3.0
4,327
0.000693
# Copyright 2021 Ecosoft (http://ecosoft.co.th) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from datetime import datetime from odoo.tests.common import TransactionCase from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT class TestPurchaseRequestException(TransactionCase): def setUp(s...
f( "purchase_request_exception.prl_excep_qty_check" ) self.pr_vals = { "requested_by": self.request_user_id.id, "line_ids": [ ( 0, 0, { "name": "Pen", ...
"product_qty": 5.0, "estimated_cost": 500.0, "date_required": self.date_required, }, ), ( 0, 0, { "name": "Ink", ...
jeremiahyan/odoo
addons/fleet/models/fleet_vehicle_model_category.py
Python
gpl-3.0
477
0
# -*- coding: utf-8 -
*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class FleetVehicleModelCategory(models.Model): _name = 'fleet.vehicle.model.category' _description = 'Category of the model' _order = 'sequence asc, id asc' _sql_constraints = [ ('na...
gory name must be unique') ] name = fields.Char(required=True) sequence = fields.Integer()
jason-weirather/py-seq-tools
seqtools/cli/legacy/background_and_nascent_expression.py
Python
apache-2.0
9,310
0.029753
#!/usr/bin/python import argparse, os, sys, re, subprocess from random import randint from GenePredBasics import line_to_entry as genepred_line_to_entry from SequenceBasics import read_fasta_into_hash from shutil import rmtree import BedToolsBasics def main(): parser = argparse.ArgumentParser(description="Analyze na...
ge(0,100)] def get_rpkm(reads_in_gene,total_rea
ds): return 1000000000*float(reads_in_gene)/(float(total_reads)) def calculate_lambda(bins,args,windows_size): sizes = [] for bin in bins: lval = 0 for fnum in bins[bin]: lval += fnum sizes.append(lval) sizes.sort() valid_sizes = sizes[:-1*int(len(sizes)*args.top_expressing_bin_cutoff)] l...
webu/django-filer
tests/utils/custom_image/migrations/0003_auto_20180414_2059.py
Python
bsd-3-clause
839
0.002384
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('custom_image', '0002_auto_20160621_1510'), ] operations = [ migrations.AlterModelOptions( name='image', options={'verbose_name': 'image', 'verbose_name_plural': 'ima...
field=models.OneToOneField(primary_key=True, serialize=False, related_name='custom_image_image_file', parent_link=True, to='filer.File', on_delete=models.CASCADE), ), ] operations += [ migrations.AlterModelOptions( name='image', op
tions={'default_manager_name': 'objects', 'verbose_name': 'image', 'verbose_name_plural': 'images'}, ), ]
swcarpentry/amy
amy/dashboard/views.py
Python
mit
11,679
0.000257
import re from typing import Optional from django.contrib import messages from django.db.models import ( Case, When, Value, IntegerField, Count, Prefetch, Q, ) from django.shortcuts import render, redirect from django.utils.html import format_html from django.urls import reverse from django...
f trainee_dashboard(request): # Workshops person taught at workshops = request.user.task_set.select_related('role', 'event') context = { 'title': 'Your profile',
'workshops': workshops, } return render(request, 'dashboard/trainee_dashboard.html', context) @login_required def autoupdate_profile(request): person = request.user form = AutoUpdateProfileForm(instance=person) if request.method == 'POST': form = AutoUpdateProfileForm(request.POST,...
bischjer/auxiliary
aux/__init__.py
Python
bsd-3-clause
2,087
0.013896
import sys import os # import device # import plugin import pkg_resources def version(): return pkg_resources.get_distribution(aux.__package__.title()).version def base_dir(): return os.path.abspath(os.path.dirname(aux.__file__)) def working_dir(): return os.getcwd() import aux from aux.logger import Lo...
to default settings.' print e.message ## - initiate logger logcontroller = LogController(config) ## - Setup logcontroller.summary['started'] = datetime.now() logcontroller.summary['systems'] = config.options.systems scripts_as_args =
[script for script in config.args if '.py' in script] if len(scripts_as_args) != 1: logcontroller.runtime.error('Script argument missing') sys.exit(1) logcontroller.summary['test'] = [ sys.argv[x] for x in range(0, len(sys.argv)) if '.py' in sys.argv[x] ][0] ## - initiate backend ...
psss/did
did/plugins/wiki.py
Python
gpl-2.0
2,703
0
# coding: utf-8 """ MoinMoin wiki stats about updated pages Config example:: [wiki] type = wiki wiki test = http://moinmo.in/ The optional key 'api' can be used to change the default xmlrpc api endpoint:: [wiki] type = wiki api = ?action=xmlrpc2 wiki test = http://moinmo.in/ """ import ...
changes += 1 url = self.url + change["name"] if url not in self.stats: self.stats.append(url) self.stats.sort() def header(self): """ Show summary header. """ # Differe
nt header for wiki: Updates on xxx: x changes of y pages item( "{0}: {1} change{2} of {3} page{4}".format( self.name, self.changes, "" if self.changes == 1 else "s", len(self.stats), "" if len(self.stats) == 1 else "s"), level=0, options=self.options) ...
trohrt/python_jisho
jisho.py
Python
gpl-3.0
1,491
0.002012
#!/usr/bin/env python3 import json import requests def lookup(query): data = json.loads(requests.get( "http://jisho.org/api/v1/search/words?keyword=%s"
% query).text) results = {} for result in range(len(data["data"])): results[result] = {"readings": [], "words": [], "senses": {}} for a in range(len(data["data"][result]["japanese"])): if (data["data"][result]["japanese"][a]["reading"] not
in results[result]["readings"]): results[result]["readings"].append( data["data"][result]["japanese"][a]["reading"]) if (data["data"][result]["japanese"][a]["word"] not in results[result]["words"]): results[result]["words"].appe...
cbelth/pyMusic
pydub/exceptions.py
Python
mit
233
0
class TooManyMissingFrames(E
xception): pass class InvalidDuration(Exception): pass class InvalidTag(Exception): pass class InvalidID3TagVersion(Exception): pass class
CouldntDecodeError(Exception): pass
Tinkerforge/brickv
src/brickv/bindings/bricklet_voltage.py
Python
gpl-2.0
12,075
0.00472
# -*- coding: utf-8 -*- ############################################################# # This file was automatically generated on 2022-01-18. # # # # Python Bindings Version 2.1.29 # # ...
lueError, ImportError): from ip_connec
tion import Device, IPConnection, Error, create_char, create_char_list, create_string, create_chunk_data GetVoltageCallbackThreshold = namedtuple('VoltageCallbackThreshold', ['option', 'min', 'max']) GetAnalogValueCallbackThreshold = namedtuple('AnalogValueCallbackThreshold', ['option', 'min', 'max']) GetIdentity = na...
MoritzS/django
tests/messages_tests/base.py
Python
bsd-3-clause
13,842
0.000722
from django import http from django.contrib.messages import constants, get_level, set_level, utils from django.contrib.messages.api import MessageFailure from django.contrib.messages.constants import DEFAULT_LEVELS from django.contrib.messages.storage import base, default_storage from django.contrib.messages.storage.ba...
arning', 'error'): messages.extend(Message(self.levels[level], msg) for msg in data['messages']) add_url = reverse('add_message', args=(level,)) self.client.post(add_url, data) response = self.client.get(show_url) self.a
ssertIn('messages', response.context) self.assertEqual(list(response.context['messages']), messages) for msg in data['messages']: self.assertContains(response, msg) @modify_settings( INSTALLED_APPS={
eomahony/Numberjack
fzn/njportfolio.py
Python
lgpl-2.1
9,815
0.002955
from utils import print_commented_fzn, total_seconds import subprocess as sp import datetime import signal import threading import os import sys result_poll_timeout = 0.5 solver_buffer_time = 1.5 # Tell each solver to finish this many seconds ahead of our actual timeout. SATISFACTION, MINIMIZE, MAXIMIZE = 0, 1, -1 U...
res = True if exitcode == 0 else False try: result_queue.put([res, exitcode, process
_name, starttime, stdout, stderr], True, 1.0) except IOError: # Pass on error as the parent process has probably exited, too late pass except Exception: pass def check_optimization(njfilename): import re import mmap ret = SATISFACTION r = re.compile(r'model...
cloud-engineering/Torpid
main.py
Python
mit
777
0.019305
import re import datetime import time #niru's git commit while True: #open the file for reading file = open("test.txt") content = file.read() #Get timestamp ts = time.time() ist = datetime.datetime.fromtimestamp
(ts).strftime('%Y-%m-%d %H:%M:%S') #open file for read and close it neatly(wrap code in try/except) #with open('test.txt', 'r') as r: #content = r.read() #print content #Search the entire content for '@' and replace it with time stamp. new_content = re.sub(r'@.*', ist, content) pri...
nt "torpid loop complete" time.sleep(5)
google-coral/demo-manufacturing
models/retraining/train_classifier.py
Python
apache-2.0
9,469
0.004858
# Copyright 2021 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, ...
classifier_activation='softmax', weights='imagenet') # Freeze first 100 layers base_model.trainable = True for layer in base_model.layers[:100]: layer.trainable =
False model = tf.keras.Sequential([ base_model, tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.GlobalAveragePooling2D(), tf.keras.layers.Dense(units=2, activation='softmax') ]) model.compile(loss='categorical_crossentropy', ...
mobiuscoin/p2pool-mobi
p2pool/work.py
Python
gpl-3.0
25,925
0.007676
from __future__ import division from collections import deque import base64 import random import re import sys import time from twisted.internet import defer from twisted.python import log import bitcoin.getwork as bitcoin_getwork, bitcoin.data as bitcoin_data from bitcoin import helper, script, worker_interface fro...
unt=lambda share: 1 if share.hash in self.my_share_hashes else 0, my_doa_count=lambda share: 1 if share.hash in self.my_doa_share_hashes else 0, my
_orphan_announce_count=lambda share: 1 if share.hash in self.my_share_hashes and share.share_data['stale_info'] == 'orphan' else 0, my_dead_announce_count=lambda share: 1 if share.hash in self.my_share_hashes and share.share_data['stale_info'] == 'doa' else 0, ))) @self.node.tracker...
niwinz/django-greenqueue
greenqueue/scheduler/gevent_scheduler.py
Python
bsd-3-clause
437
0
# -*- coding: utf-8 -*- from gevent import Greenlet from gevent import sleep from .base import SchedulerMixin
class Scheduler(SchedulerMixin, Greenlet): """ Gevent scheduler. Only replaces the sleep method for cor
rect context switching. """ def sleep(self, seconds): sleep(seconds) def return_callback(self, *args): return self.callback(*args) def _run(self): self.start_loop()
Alberto-Beralix/Beralix
i386-squashfs-root/usr/share/pyshared/ubuntuone-client/ubuntuone/logger.py
Python
gpl-3.0
9,937
0.001006
# ubuntuone.syncdaemon.logger - logging utilities # # Author: Guillermo Gonzalez <guillermo.gonzalez@canonical.com> # # Copyright 2010 Canonical Ltd. # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Soft...
with enable_debug(slave): slave.handle(record) @contextlib.contextmanager def enable_debug(self, obj): """context manager that temporarily changes the level attribute of obj to logging.DEBUG. """ old_level = obj.level obj.level = logging....
BUG yield obj obj.level = old_level def clear(self): """cleanup the captured records""" self.records = [] def install(self): """Install the debug capture in the logger""" self.slaves = self.logger.handlers self.logger.handlers = [self] # set the ...
rsanchezavalos/compranet
compranet/pipelines/models/model_orchestra.py
Python
gpl-3.0
2,147
0.004196
# coding: utf-8 import re import os import ast import luigi import psycopg2 import boto3 import random import sqlalchemy import tempfile import glob import datetime import subprocess import pandas as pn from luigi import six from os.path import join, dirname from luigi import configuration from luigi.s3 import S3Targe...
cmd = ''' python {}/missing-classifier.p
y '''.format(self.script) return subprocess.call(cmd, shell=True)
sander76/home-assistant
homeassistant/components/daikin/config_flow.py
Python
apache-2.0
4,406
0.000681
"""Config flow for the Daikin platform.""" import asyncio import logging from uuid import uuid4 from aiohttp import ClientError, web_exceptions from async_timeout import timeout from pydaikin.daikin_base import Appliance from pydaikin.discovery import Discovery import voluptuo
us as vol from homeassistant import config_entries from homeassistant.const import CONF_API_KEY, CONF_HOST, CONF_PASSWORD from .const import CONF_UUID, DOMAIN, KEY_MAC, TIMEOUT _LOGGER = logging.getLogger(__name__) class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow.""" VE...
in config flow.""" self.host = None @property def schema(self): """Return current schema.""" return vol.Schema( { vol.Required(CONF_HOST, default=self.host): str, vol.Optional(CONF_API_KEY): str, vol.Optional(CONF_PASSWORD): st...
sorja/twatter
twatter/utils/query.py
Python
mit
678
0.001475
# -*- coding: utf-8 -*- class SQLQuery(object): result_action = 'fetchall' res
ult = None auto_commit = True def __init__(self, name, sql, params=()): if self.result_action not in ('fetchall', 'fetchone', 'execute'): raise TypeError('Bad `result_action` value, should be fetchall, fetchone or execute') self.name = name self.sql = sql self.params...
def _fetch_data(self, cursor): cursor.execute(self.sql, self.params) if self.result_action == 'fetchall': self.result = cursor.fetchall() elif self.result_action == 'fetchone': self.resul = cursor.fetchone()
fxdgear/beersocial
socialbeer/core/tasks.py
Python
mit
1,478
0.012179
from django.contrib.auth.models import User from django.contrib.sites.models import Site from celery.decorators import task from socialbeer.posts.models import Post from socialbeer.core.utils import expand_urls from socialbeer.members.models import Profile from socialregistration.models import TwitterProfile ...
etweet = True except: pass obj.save() return True
salilab/saliweb
examples/frontend-results.py
Python
lgpl-2.1
440
0
@app.route('/job/<name>') def results(name): job = saliweb.frontend.get_completed_job(name,
flask.request.args.get('passwd')) # Determine whether the job completed su
ccessfully if os.path.exists(job.get_path('output.pdb')): template = 'results_ok.html' else: template = 'results_failed.html' return saliweb.frontend.render_results_template(template, job=job)
lupyuen/RaspberryPiImage
usr/share/pyshared/ajenti/plugins/samba/status.py
Python
apache-2.0
881
0.003405
import os import subprocess class SambaMonitor (object): def __init__(self): self.refresh() def refresh(self): pids = {} ll = subprocess.check_output(
['smbstatus', '-p']).splitlines() for l in ll[4:]:
s = l.split() if len(s) > 0: pids[s[0]] = (s[1], ' '.join(s[3:])) self.connections = [] ll = subprocess.check_output(['smbstatus', '-S']).splitlines() for l in ll[3:]: s = l.split() if len(s) > 0 and s[1] in pids: ...
guarddogofww/cs108test
src/jarabe/frame/clipboardicon.py
Python
gpl-3.0
8,080
0
# Copyright (C) 2007, Red Hat, Inc. # Copyright (C) 2007, One Laptop Per Child # # 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 ...
cent < 100 and cb_object.get_percent() == 100: self.props.active = True self.show_notification() self._current_percent = cb_object.get_percent() def _object_selected_cb(self, cb_service, object_id): if object_id != self._cb_object.get_id(): return self.p...
ication() logging.debug('ClipboardIcon: %r was selected', object_id) def show_notification(self): self._notif_icon = NotificationIcon() self._notif_icon.props.icon_name = self._icon.props.icon_name self._notif_icon.props.xo_color = \ XoColor('%s,%s' % (self._icon.props.s...
pombredanne/SmartNotes
submodules/django-localeurl-read-only/localeurl/settings.py
Python
gpl-3.0
1,050
0.000952
# Copyright (c) 2008 Joost Cassee # Licensed under the terms of the MIT License (see LICENSE.txt) from django.conf import settings URL_TYPES = ('path_prefix', 'domain_component', 'domain') URL_TYPE = getattr(settings, 'LOCALE_URL_TYPE', 'path_prefix') assert URL_TYPE in URL_TYPES, \ "LOCALE_URL_TYPE must be o...
NDEPENDENT_PATHS only used with URL_TYPE == 'path_prefix'" LOC
ALE_INDEPENDENT_MEDIA_URL = getattr(settings, 'LOCALE_INDEPENDENT_MEDIA_URL', True) PREFIX_DEFAULT_LOCALE = getattr(settings, 'PREFIX_DEFAULT_LOCALE', True) assert not (URL_TYPE != 'path_prefix' and PREFIX_DEFAULT_LOCALE), \ "PREFIX_DEFAULT_LOCALE only used with URL_TYPE == 'path_prefix'" DOMAINS = ge...
mudbungie/tradecraft
tests/db_test.py
Python
gpl-3.0
1,518
0.00527
test_email = 'a@b.c' test_password = '1234' # Creates a database connection. def get_db(): from tradecraft.db import Database, read_engine_string conn_string = read_engine_string() return Database(conn_string) # Not actually a test. Just cleaning up in case tests failed earlier. def test_pre
_cleanup(): db = get_db() db.delete_user_by_email(test_email) assert True # Creates a connection to the psql database. def test_create_connection(): from tradecraft.db import Database, read_engine_string from sqlalchemy.engine.base import Connection conn_string = read_engine_string() db = ...
ection()) == Connection def test_in_memory_connection(): from tradecraft.db import Database from sqlalchemy.engine.base import Connection db = get_db() with db.get_session() as s: assert type(s.connection()) == Connection def test_table_create(): db = get_db() assert 'users' in db.e.ta...
ufal/neuralmonkey
neuralmonkey/attention/scaled_dot_product.py
Python
bsd-3-clause
15,590
0
"""The scaled dot-product attention mechanism defined in Vaswani et al. (2017). The attention energies are computed as dot products between the query vector and the key vector. The query vector is scaled down by the square root of its dimensionality. This attention function has no trainable parameters. See arxiv.org/...
x: input Tensor of shape ``(batch, time, dim)``. n_heads: Number of attention heads. head_dim: Dimension of the attention heads. Returns: A 4D Tensor of shape ``(batch, n_heads, time, head_dim/n_heads)`` """ x_shape = tf.shape(x) x_4d = tf.reshape(tf.expand_dims(x, 2), ...
shape[1], n_heads, head_dim]) return tf.transpose(x_4d, perm=[0, 2, 1, 3]) def mask_energies(energies_4d: tf.Tensor, mask: tf.Tensor, mask_value=-1e9) -> tf.Tensor: """Apply mask to the attention energies before passing to softmax. Arguments: energies_4d: Ener...
karan/warehouse
warehouse/migrations/versions/23a3c4ffe5d_relax_normalization_rules.py
Python
apache-2.0
1,897
0.001054
# 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 Li...
RETURNS NULL ON NULL INPUT; """ ) def downgrade(): op.execute( """ CREATE OR REPLACE FUNCTION normalize_pep426_name(text) RETURNS text AS $$ SELECT lower( regexp_replace( regexp_replace(
regexp_replace($1, '(\.|_)', '-', 'ig'), '(1|l|I)', '1', 'ig' ), '(0|0)', '0', 'ig' ) ) $$ LANGUAGE SQL IMMUTABLE RETURNS NULL ON NULL INPUT;...
teury/django-multimedia
multimedia/south_migrations/0020_auto__del_field_audio_encoding__del_field_audio_encoded__del_field_vid.py
Python
bsd-3-clause
7,755
0.007092
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Audio.encoding' db.delete_column(u'multimedia_audio', '...
.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models...
ToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('na...
YzPaul3/h2o-3
h2o-docs/src/booklets/v2_2015/source/GLM_Vignette_code_examples/glm_poisson_example.py
Python
apache-2.0
514
0.021401
# Used swedish insurance data from smalldata instead of MASS/insurance due to the license of the MASS R package. import h2o from h2o.estimators.glm import H2OGeneralizedL
inearEstimator h2o.init() h2o_df = h2o.import_file("http://h2o-public-test-data.s3.amazonaws.com/smalldata/glm_test/Motor_insurance_sweden.txt", sep = '\t') poisson_fit = H2OGeneralizedLinearEstimator(family = "poisson") poisson_fit.train(y="Claims", x = ["Payment", "Insured", "Kilometres", "Zone", "Bon
us", "Make"], training_frame = h2o_df)
lingxz/todoapp
project/users/user_test.py
Python
mit
6,148
0.000651
from project import app, db from flask_testing import TestCase from flask import url_for from project.config import TestConfig from project.models import User import json class UserTestSetup(TestCase): def create_app(self): app.config.from_object(TestConfig) return app def setUp(self):
self.test_username = 'test' self.test_password = 'test' self.test_ema
il = 'test@test.com' db.create_all() def tearDown(self): db.session.remove() db.drop_all() def create_user(self): user = User( username=self.test_username, password=self.test_password, email=self.test_email ) db.session.add(u...
iemejia/incubator-beam
sdks/python/apache_beam/runners/portability/fn_api_runner/execution.py
Python
apache-2.0
27,238
0.006131
# # 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 us...
beam.transforms import trigger from apache_beam.transforms.window import GlobalWindow from apache_beam.transforms.window import GlobalWindows from apache_beam.utils import proto_utils from apache_beam.utils import windowed_value if TYPE_CHECKING: from apache_beam.coders.coder_impl import CoderImpl from
apache_beam.runners.portability.fn_api_runner import worker_handlers from apache_beam.runners.portability.fn_api_runner.translations import DataSideInput from apache_beam.transforms.window import BoundedWindow ENCODED_IMPULSE_VALUE = WindowedValueCoder( BytesCoder(), GlobalWindowCoder()).get_impl().encode_nest...
lino-framework/xl
lino_xl/lib/notes/roles.py
Python
bsd-2-clause
228
0.004386
# Copyright 201
8 Rumma & Ko Ltd # License: GNU Affero General Public License v3 (see file COPYING for details) from lino.core.roles import UserRole class NotesUser(UserRole): pass class NotesStaff(NotesUs
er): pass
blechta/fenapack
doc/source/pylit/pylit.py
Python
lgpl-3.0
61,091
0.00131
#!/usr/bin/env python # -*- coding: iso-8859-1 -*- # pylit.py # ******** # Literate programming with reStructuredText # ++++++++++++++++++++++++++++++++++++++++++ # # :Date: $Date$ # :Revision: $Revision$ # :URL: $URL$ # :Copyright: © 2005, 2007 Günter Milde. # Released without warranty under t...
*, and # * a compilable (or executable) code source with *documentation* # embedded in comment blocks # # # Requirements # ------------ # # :: import os, sys import re, optparse # DefaultDict # ~~~~~~~~~~~ # As `collections.defaultdict` is only introduced in Python 2.5, we
# define a simplified version of the dictionary with default from # http://code.activestate.com/recipes/389639/ # :: class DefaultDict(dict): """Minimalistic Dictionary with default value.""" def __init__(self, default=None, *args, **kwargs): self.update(dict(*args, **kwargs)) self.default = de...
diogobaeder/giva
base/tests/test_clients.py
Python
bsd-2-clause
1,375
0.000728
from datetime import date from unittest.mock import patch from nose.tools import istest from base.clients import ClientConfigurationError, YouTubeClient from base.tests.utils import YouTubeTestCa
se class YouTubeClientTest(YouTubeTestCase): @istest def raises_exception_if_misconfigured_api_key(self): client = YouTubeClient() client.channel_search_parameters['key'] = ''
with self.assertRaises(ClientConfigurationError): client.list_channel_videos() @istest @patch('requests.get') def lists_available_videos_in_the_channel(self, mock_get): response = mock_get.return_value response.status_code = 200 response.content.decode.return_val...
selfcommit/simian
src/tests/simian/mac/common/util_medium_test.py
Python
apache-2.0
3,396
0.005595
#!/usr/bin/env python # # Copyright 2017 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-2.0 # # Unless require...
ript uses the same notation as python to represent unicode # characters. self.assertEqual(ustr_js, util.Serialize(ustr)) def testDeserializeUnicode(self): """Test Deserialize().""" ustr = u'Hello there\u2014' ustr_js = '"Hello there\\u2014"' self.assertEqual(ustr, util.Deseri
alize(ustr_js)) def _DumpStr(self, s): """Return any binary string entirely as escaped characters.""" o = [] for i in xrange(len(s)): o.append('\\x%02x' % ord(s[i])) return ''.join(o) def testSerializeControlChars(self): """Test Serialize().""" input = [] output = [] for x i...
SensSolutions/sens_platform
psens/discarted/psens2.py
Python
gpl-3.0
3,984
0.005773
#!/usr/bin/python # -*- coding: utf-8 -*- """ created on Tue Jul 29 10:12:58 2014 @author: mcollado """ import random from ConfigParser import SafeConfigParser import sys from m
ultiprocessing import Process import time import os import logging from daemon import runner # import paho.mqtt.publish as publish # import ConfigParser # import Adafruit_DHT # import datetime # Importing my modules import pcontrol #import airsensor # create logger logger = logging.getLogger('PSENSv0.1') logger.setLe...
logging.FileHandler('debug.log') fh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.WARNING) # create formatter formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(funcName)s - %(lineno)d - %(message)s') ch.setFormatter(f...
Ensembles/ert
python/python/ert/ecl/ecl_grid.py
Python
gpl-3.0
48,274
0.022807
# Copyright (C) 2011 Statoil ASA, Norway. # # The file 'ecl_grid.py' is part of ERT - Ensemble based Reservoir Tool. # # ERT is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Licens...
rid , int )") _get_active_fracture_index1 = EclPrototype("int ecl_grid_get_active_fracture_index1( ecl_grid , int )") _get_global_index1A = EclPrototype("int ecl_grid_get_global_index1A( ecl_grid , int )") _get_global_index1F = EclPrototype("int ecl_grid_get_global_index1F( ecl_grid , ...
get_ijk1A( ecl_grid , int , int* , int* , int*)") _get_xyz3 = EclPrototype("void ecl_grid_get_xyz3( ecl_grid , int , int , int , double* , double* , double*)") _get_xyz1 = EclPrototype("void ecl_grid_get_xyz1( ecl_grid , int , double* , double* , double*)") _get_cell_...
bitmazk/cmsplugin-redirect
cmsplugin_redirect/cms_plugins.py
Python
mit
1,251
0
"""CMS Plugins for the ``cmsplugin_redirect`` app.""" from django.utils.translation import ugettext_lazy as _ from django.http import HttpResponseRedirect from cms.plugins.link.forms import LinkForm from cms.plugin_pool import plugin_pool from cms.plugin_base import CMSPluginBase from .models import ForceRedirectPlug...
t action') admin_preview = False def render(
self, context, instance, placeholder): current_page = context['request'].current_page # if the user defined a page and that isn't the current one, redirect # there if instance.page_link and instance.page != instance.page_link: url = instance.page_link.get_absolute_url() ...
pymedia/pymedia
examples/video_bench_ovl.py
Python
lgpl-2.1
2,778
0.078474
#! /bin/env python import sys, time, os import pymedia.muxer as muxer import pymedia.video.vcodec as vcodec import pymedia.audio.acodec as acodec import pymedia.audio.sound as sound if os.environ.has_key( 'PYCAR_DISPLAY' ) and os.environ[ 'PYCAR_DISPLAY' ]== 'directfb': import pydfb as pygame YV12= pygame.PF_Y
V12 else: import pygame YV12= pygame.YV12_OVERLAY def videoDecodeBenchmark( inFile, opt ): pygame.init() pygame.display.set_mode( (800,600), 0 ) ovl= None dm= muxer.Demuxer( inFile.split( '.' )[ -1 ] ) f= open( inFile, 'rb' ) s= f.read( 400000 ) r= dm.parse( s ) v= filter( lambda x: x[ 'type' ]=...
e video stream at %d index: ' % v_id a= filter( lambda x: x[ 'type' ]== muxer.CODEC_TYPE_AUDIO, dm.streams ) if len( a )== 0: print 'There is no audio stream in a file %s. Ignoring audio.' % inFile opt= 'noaudio' else: a_id= a[ 0 ][ 'index' ] t= time.time() vc= vcodec.Decoder( dm.streams[...
shubhdev/openedx
cms/djangoapps/contentstore/tests/test_transcripts_utils.py
Python
agpl-3.0
24,610
0.002075
# -*- coding: utf-8 -*- """ Tests for transcripts_utils. """ import unittest from uuid import uuid4 import copy import textwrap from mock import patch, Mock from django.test.utils import override_settings from django.conf import settings from django.utils import translation from nose.plugins.skip import SkipTest fro...
"2.45">Test text 1.</text>
<text start="2.72">Test text 2.</text> <text start="5.43" dur="1.73">Test text 3.</text> </transcript> """) good_youtube_sub = 'good_id_2' self.clear_sub_content(good_youtube_sub) with patch('xmodule.video_module.transcripts_utils.requests...
CERNDocumentServer/invenio
modules/docextract/lib/refextract_cli.py
Python
gpl-2.0
10,531
0.00038
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 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 # Li...
at it came from. --raw-references Treat the input file as pure references. i.e. skip the stage of trying to locate the reference section within
a document and instead move to the stage of recognition and standardisation of citations within lines. """ USAGE_MESSAGE = """Usage: docextract [options] file1 [file2 ...] Command options: %s%s Examples: docextract -o /home/chayward/refs.xml /home/chayward/thesis.pdf ...
Openeight/enigma2
lib/python/Components/Network.py
Python
gpl-2.0
20,757
0.027846
import os import re import netifaces as ni from socket import * from Components.Console import Console from Components.PluginComponent import plugins from Plugins.Plugin import PluginDescriptor from boxbranding import getBoxType class Network: def __init__(self): self.ifaces = {} self.configuredNetworkAdapters =...
s %d.%d.%d.%
d\n" % tuple(iface['ip'])) fp.write(" netmask %d.%d.%d.%d\n" % tuple(iface['netmask'])) if 'gateway' in iface: fp.write(" gateway %d.%d.%d.%d\n" % tuple(iface['gateway'])) if "configStrings" in iface: fp.write(iface["configStrings"]) if iface["preup"] is not False and "configStrings" not in if...
t1g0r/ramey
src/backend/libs/telepot/delegate.py
Python
gpl-3.0
2,741
0.009486
import traceback import telepot from .exception import BadFlavor, WaitTooLong, StopListening def _wrap_none(fn): def w(*args, **kwargs): try: return fn(*args, **kwargs) except (KeyError, BadFlavor): return None return w def per_chat_id(): return _wrap_none(lambda ms...
handled: j.on_message(msg) while 1: msg = j.listener.wait() j.on_message(msg)
# These exceptions are "normal" exits. except (WaitTooLong, StopListening) as e: j.on_close(e) # Any other exceptions are accidents. **Print it out.** # This is to prevent swallowing exceptions in the case that on_close() # gets overridden b...
tibor95/phatch-python2.7
phatch/lib/pyWx/screenshot.py
Python
gpl-3.0
2,264
0.003092
# Copyright (C) 2007-2008 www.stani.be # # 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...
From where do we copy? rect.x, # What's the X of
fset in the original DC? rect.y # What's the Y offset in the original DC? ) # Select the Bitmap out of the memory DC by selecting a new # uninitialized Bitmap. memDC.SelectObject(wx.NullBitmap) return bmp def get_window(window): return get(window.GetRect()) def save(rect, file...
nkgilley/home-assistant
homeassistant/components/wink/binary_sensor.py
Python
apache-2.0
6,531
0
"""Support for Wink binary sensors.""" import logging import pywink from homeassistant.components.binary_sensor import BinarySensorEntity from . import DOMAIN, WinkDevice _LOGGER = logging.getLogger(__name__) # These are the available sensors mapped to binary_sensor class SENSOR_TYPES = { "brightness": "light"...
entation of a Wink binary sensor.""" def __init__(self, wink, hass): """Initialize the Wink binary s
ensor.""" super().__init__(wink, hass) if hasattr(self.wink, "unit"): self._unit_of_measurement = self.wink.unit() else: self._unit_of_measurement = None if hasattr(self.wink, "capability"): self.capability = self.wink.capability() else: ...
davinwang/caffe2
caffe2/python/rnn/lstm_comparison.py
Python
apache-2.0
2,920
0.000685
# Copyright (c) 2016-present, Facebook, 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...
_cudnn)))
print(args) print("t_cudnn / t_own: {}".format(t_cudnn / t_own)) for args, t_own, t_cudnn in results: print("{}: cudnn time: {}, own time: {}, ratio: {}".format( str(args), t_cudnn, t_own, t_cudnn / t_own)) ratio_sum = 0 for args, t_own, t_cudnn i...
benfinkelcbt/OAuthLibrary
2016-04-01/oauth.py
Python
gpl-3.0
1,891
0.037017
import logging import googleOAuth #Map the specific provider functions to provider choices # Additional providers must be added in here ProviderAuthMap = { "google": googleOAuth.SignIn } ProviderAccessMap = { "google": googleOAuth.GetAccessToken } #------------------------------------------------------------------...
on the chosen provider #-------------------------------------------------------------------------- def SignIn(provider, redirect_uri, state): #Lookup the correct function in the tuple signInFunc = ProviderAuthMap.get(provider) #Call the function, getting the full URL + querystring in return authUrl = signInFunc(r...
------------------------------------------------------------------------ def OAuthCallback(request, state, provider, redirect_uri): #First, check for a mismatch between the State tokens and return #an error if found if (request.get('state') != state): return {"error" : True, "errorText" : "State Token Mismatch! P...
caioariede/pyq
testfiles/imports.py
Python
mit
177
0
from foo import bar # noqa from foo import bar as bar2, xyz # noqa from foo.baz impo
rt bang # noqa from . import x import example as example2 # n
oqa import foo.baz # noqa
yephper/django
tests/file_uploads/tests.py
Python
bsd-3-clause
25,386
0.001221
#! -*- coding: utf-8 -*- from __future__ import unicode_literals import base64 import errno import hashlib import json import os import shutil import tempfile as sys_tempfile import unittest from io import BytesIO from django.core.files import temp as tempfile from django.core.files.uploadedfile import ...
RT_CONTENT, 'PATH_INFO': "/unicode_name/", 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) def test_blank_filenames(self): """ Receiving file uplo...
ame is blank (before and after sanitization) should be okay. """ # The second value is normalized to an empty name by # MultiPartParser.IE_sanitize() filenames = ['', 'C:\\Windows\\'] payload = client.FakePayload() for i, name in enumerate(filenames): ...
mfinelli/music-rename
tests/test_checksum.py
Python
gpl-3.0
877
0
import pytest import tempfile import shutil import os import music_rename from music_rename import checksum @pytest.fixture() def empty(request): dir = tempfile.mkdtemp() os.mknod(os.path.join(dir, 'empty.txt')) def cleanup(): shutil.rmtree(dir) request.addfinalizer(cleanup) return os.p...
est.addfinalizer(cleanup) return file[1] def test
_emptyfile(empty): assert music_rename.checksum.md5sum_file( empty) == 'd41d8cd98f00b204e9800998ecf8427e' def test_not_empty(not_empty): assert music_rename.checksum.md5sum_file( not_empty) == '4e3e88d75e5dc70c6ebb2712bcf16227'
sgillies/Fiona
src/fiona/crs.py
Python
bsd-3-clause
5,254
0.002665
# Coordinate reference systems and functions. # # PROJ.4 is the law of this land: http://proj.osgeo.org/. But whereas PROJ.4 # coordinate reference systems are described by strings of parameters such as # # +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs # # here we use mappings: # # {'proj': 'longlat', 'ellps': '...
titud
e of true scale +lon_0 Central meridian +lon_1 +lon_2 +lonc ? Longitude used with Oblique Mercator and possibly a few others +lsat +m +M +n +no_cut +no_off +no_rot +ns +o_alpha +o_lat_1 +o_lat_2 +o_lat_c +o_lat_p +o_lon_1 +o_lon_2 +o_lon_c +o_lon_p +o_proj +over +p +path +proj Projection name (see `proj -...
jayhetee/coveragepy
tests/test_filereporter.py
Python
apache-2.0
4,402
0
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt """Tests for FileReporters""" import os import sys from coverage.plugin import FileReporter from coverage.python import PythonFileReporter from tests.coveragetes...
acu2 = FileReporter("aa/afile.py") zcu = FileReporter("aa/zfile.py") bcu = FileReporter("aa/bb/bfile.py") assert acu == acu2 and acu <= acu2 and acu >= acu2 assert acu < zcu and acu <= zcu and acu != zcu assert zcu > acu and zcu >= acu and zcu != acu assert acu < bcu and...
t bcu > acu and bcu >= acu and bcu != acu def test_egg(self): # Test that we can get files out of eggs, and read their source files. # The egg1 module is installed by an action in igor.py. import egg1 import egg1.egg1 # Verify that we really imported from an egg. If we did...
kczapla/pylint
pylint/test/functional/assignment_from_no_return_py3.py
Python
gpl-2.0
495
0
# pylint: disable=missing-docstring import asyncio async def bla1(): await asyncio.sleep(1) async def bla2():
awa
it asyncio.sleep(2) async def combining_coroutine1(): await bla1() await bla2() async def combining_coroutine2(): future1 = bla1() future2 = bla2() await asyncio.gather(future1, future2) def do_stuff(): loop = asyncio.get_event_loop() loop.run_until_complete(combining_coroutine1()) ...
Nico0084/domogik-plugin-daikcode
docs/conf.py
Python
gpl-3.0
430
0.002326
import sys import os extensions
= [ 'sphinx.ext.todo', ] source_suffix = '.txt' master_doc = 'index' ### part to update ################################### project = u'domogik-plugin-daikcode' copyright = u'2014, Nico0084' version = '0.1' release = version ###################################################### pygments_style = 'sphinx' html...
['_static'] htmlhelp_basename = project
broxtronix/distributed
distributed/tests/test_worker.py
Python
bsd-3-clause
16,430
0.001948
from __future__ import print_function, division, absolute_import from numbers import Integral from operator import add import os import shutil import sys import traceback import logging import re import pytest from toolz import pluck from tornado import gen from tornado.ioloop import TimeoutError from distributed.ba...
test_worker_ncores(): from distributed.worker import _ncores w = Worker('127.0.0.1', 8019) try: assert w.executor._max_workers == _ncores finally: shutil.rmtree(w.local_dir) def test_identity(): w = Worker('127.0.0.1', 8019) ident = w.identity(None) assert ident['type'] == ...
Worker('127.0.0.1', 8019) d = w.host_health() assert isinstance(d, dict) d = w.host_health() try: import psutil except ImportError: pass else: assert 'disk-read' in d assert 'disk-write' in d assert 'network-recv' in d assert 'network-send' in d ...
andrewtron3000/hacdc-ros-pkg
face_detection/src/detector.py
Python
bsd-2-clause
5,077
0.005318
#!/usr/bin/env python #********************************************************************* # Software License Agreement (BSD License) # # Copyright (c) 2011 andrewtron3000 # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the ...
amped(point = pt) coord_publisher.publish(pt_stamped) # # Convert the opencv image back to a ROS image using the # cv_bridge. # newmsg = cv_bridge.cv_to_imgmsg(image, 'mono8') # # Republish the image. Note this image has boxes around # faces if faces were found. # ...
ef listener(publisher, coord_publisher): rospy.init_node('face_detector', anonymous=True) # # Load the haar cascade. Note we get the # filename from the "classifier" parameter # that is configured in the launch script. # cascadeFileName = rospy.get_param("~classifier") cascade = cv....
obi-two/Rebelion
data/scripts/templates/object/draft_schematic/clothing/shared_clothing_armor_bone_leggings.py
Python
mit
466
0.04721
##
## NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Intangible() result.template = "object/draft_schematic/clothing/shared_clothing_armor_bone_leggings.iff" result.att...
mscuthbert/abjad
abjad/tools/documentationtools/GraphvizTableRow.py
Python
gpl-3.0
1,133
0.005296
# -*- encoding: utf-8 -*- from abjad.tools.datastructuretools import TreeContainer class GraphvizTableRow(TreeContainer): r'''A Graphviz table row. ''' ### CLASS VARIABLES ### __documentation_section__ = 'Graphviz' __slots__ = () ### INITIALIZER ### def __init__( self, ...
children=children, name=name, ) ### SPECIAL METHODS ### def __str__(self): r'''Gets string representation of Graphviz table row. Returns string. ''' result = [] result.append('<TR>') for x in self: result.append('
' + str(x)) result.append('</TR>') result = '\n'.join(result) return result ### PRIVATE PROPERTIES ### @property def _node_class(self): from abjad.tools import documentationtools prototype = ( documentationtools.GraphvizTableCell, documentat...
tik0/inkscapeGrid
share/extensions/render_alphabetsoup.py
Python
gpl-2.0
16,568
0.041767
#!/usr/bin/env python ''' Copyright (C) 2001-2002 Matt Chisholm matt@theory.org Copyright (C) 2008 Joel Holdsworth joel@airwebreathe.org.uk for AP 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;...
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ''' # standard library import copy import math import cmath import string import random import os import sys import re # local library import inkex import simplestyle import render_alphabetsoup_config import bezmisc import simplepath i...
er_alphabetsoup_config.alphabet units = render_alphabetsoup_config.units font = render_alphabetsoup_config.font # Loads a super-path from a given SVG file def loadPath( svgPath ): extensionDir = os.path.normpath( os.path.join( os.getcwd(), os.path.dirname(__file__) ) ) # __fi...
sonali0901/zulip
zerver/webhooks/codeship/view.py
Python
apache-2.0
2,072
0.002896
# Webhooks for external integrations. from __future__ import absolute_import from django.utils.translation import ugettext as _ from django.http import HttpRequest, HttpResponse from typing import Any from zerver.lib.actions import check_send_message from zerver.lib.response import json_success, json_error from zerve...
def get_subject_for_http_request(payload): # type: (Dict[str, Any]) -> str return CODESHIP_SUBJECT_TEMPLATE.format(project_name=payload['project_name']) def get_body_for_http_request(payload): # type: (Dict[str, Any]) -> str return CODESHIP_MESSAGE_TEMPLATE.format( build_url=payload['build_ur...
get_status_message(payload): # type: (Dict[str, Any]) -> str build_status = payload['status'] return CODESHIP_STATUS_MAPPER.get(build_status, CODESHIP_DEFAULT_STATUS.format(status=build_status))
SciTools/iris-grib
setup.py
Python
lgpl-3.0
3,340
0.011377
#!/usr/bin/env python import os import os.path from setuptools import setup NAME = 'iris_grib' PYPI_NAME = 'iris-grib' PACKAGE_DIR = os.path.abspath(os.path.dirname(__file__)) PACKAGE_ROOT = os.path.join(PACKAGE_DIR, NAME) packages = [] for d, _, _ in os.walk(os.path.join(PACKAGE_DIR, NAME)): if os.path.exists(o...
, "rb") as fi: result = fi.read().decode("utf-8") return result def file_walk_relative(top, remove=''): """ Returns a generator of files from the top of the tree, removing the given prefix from the root/file result. """ top = top.replace('/', os.path.sep) remove = remove.replace('...
p): for file in files: yield os.path.join(root, file).replace(remove, '') setup_args = dict( name = PYPI_NAME, version = extract_version(), packages = packages, package_data = {'iris_grib': list(file_walk_relative('iris_grib/tests/results', ...
KPRSN/Pulse
Pulse/FileManager.py
Python
mit
7,618
0.006826
""" Karl Persson, Mac OSX 10.8.4/Windows 8, Python 2.7.5, Pygame 1.9.2pre Class taking care of all file actions ingame - Levels - Textures - Sounds """ import pygame from pygame.locals import * import sys, Level, os, random # Class taking care of all file actions class FileManager: # Constructor...
s) elif ballType == 'Mu
ltiBall': if len(self.multiBallSounds) > 0: sound = self.multiBallSounds[random.randint(0, len(self.multiBallSounds)-1)] channel = self.getFreeChannel(self.multiBallChannels) # Only playing if there are any specified sound if sound and channel: ...
elbeardmorez/quodlibet
quodlibet/quodlibet/qltk/prefs.py
Python
gpl-2.0
31,084
0.000097
# -*- coding: utf-8 -*- # Copyright 2004-2009 Joe Wreschnig, Michael Urman, Iñigo Serna, # Steven Robertson # 2011-2017 Nick Boultbee # 2013 Christoph Reiter # 2014 Jan Path # # This program is free software; you can redistribute it and/or modify # it under th...
use_underline=True) fip = Gtk.CheckButton(label=_("Filename includes _folder"), use_underline=True) self._toggle_data = [ (tiv, "title", "~title~version"), (aip, "album", "~albu
m~discsubtitle"), (fip, "~basename", "~filename"), (aio, "artist", "~people") ] t = Gtk.Table.new(2, 2, True) t.attach(tiv, 0, 1, 0, 1) t.attach(aip, 0, 1, 1, 2) t.attach(aio, 1, 2, 0, 1) ...
brianinnes/vPiP
python/test2.py
Python
apache-2.0
1,586
0.001892
# Copyright 2016 Brian Innes # # Licensed under the Apache License, Version
2.0 (th
e "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, # WITH...
Squishymedia/feedingdb
django-faceted-search/faceted_search/utils.py
Python
gpl-3.0
2,983
0.012404
import logging import re from datetime import datetime, timedelta from django.conf import settings import calendar logger = logging.getLogger(__name__) DATETIME_REGEX = re.compile('^(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})(T|\s+)(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2}).*?$') YEAR_MONTH_REGEX = re.co...
if m and m.groups(): return "%s and up" % m.gro
ups() return query def check_parse_date(value): ''' Dates in the url will not be passed in the solr range format, so this helper checks values for a date match and returns a correctly formatted date range for solr. [2010-12-01T00:00:00Z TO 2010-12-31T00:00:00Z] ''' # Months ar...
pichuang/OpenNet
mininet-patch/examples/cluster/nctu_ec_wired_and_wireless_topo.py
Python
gpl-2.0
4,474
0.008046
#!/usr/bin/python ''' nctu_cs_wired_and_wireless_topo.gy ''' from mininet.cluster.net import MininetCluster from mininet.cluster.placer import DFSPlacer from mininet.log import setLogLevel from mininet.cluster.cli import ClusterCLI as CLI from mininet.node import Controller, RemoteController from mininet.topo import T...
, sw_list): for i in xrange(1, sw_num+1): sw_list.append(self.addSwitch("{0}
{1}".format(prefix_name, i), dpid='{0:x}'.format(self.sw_id))) self.sw_id += 1 def handle_top_down( self, prefix_name, num, top_list, down_list): temp = 0 for i in xrange(0, len(top_list)): for j in xrange(1, num+1): switch = self.addSwitch("{0}{1}".format(pr...
IntelBUAP/Python3
Evaluaciones/tuxes/eva2/validapass.py
Python
gpl-2.0
1,660
0.002415
#! /usr/bin/python3 import re err = "La contraseña no es segura" msg = "Escriba una contraseña al menos 8 caracteres alfanumericos" def ismayor8(a): """ Compara si es mayor a 8 caracteres """ if (len(a) < 8): return False return True def minus(a): """ compara si existe alguna le...
ag = False for letra in a: if (re.match(patron, letra)): flag = True return flag def alfanumeric(a): """ Compara si la cadena es alfanumerica """ if (a.isalnum()): return True else: return False def vpass(): """ Validamos contraseña """ ...
ida = False while salida is False: try: print (msg, end='\n') paswd = str(input('passwd: ')) if (ismayor8(paswd)): if (alfanumeric(paswd)): if (minus(paswd) and mayus(paswd) and unnum(paswd)): salida = True ...
iaddict/mercurial.rb
vendor/mercurial/mercurial/encoding.py
Python
mit
9,581
0.002714
# encoding.py - character transcoding support for Mercurial # # Copyright 2005-2009 Matt Mackall <mpm@selenic.com> and others # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. import error import unicodedata, locale, os def _getpr...
nts in arbitrary other encodings can have be round-tripped or recovered by clueful clients - local strings that have a cached known UTF-8 encoding (aka localstr) get sent as UTF-8 so Unicode-oriented clients get the Unicode data they want - because we must preserve UTF-8 bytestring in places s...
tadata can't be roundtripped without help (Note: "UTF-8b" often refers to decoding a
sciunto-org/scifig
libscifig/__init__.py
Python
gpl-3.0
69
0
#!/usr/bin/env python # -
*- coding: utf-8 -*- __version_
_ = '0.1.3'
aruneli/validation-tests
tests/validation_v2/cattlevalidationtest/core/test_services_lb_host_routing.py
Python
apache-2.0
76,409
0.000013
from common_fixtures import * # NOQA @pytest.mark.P0 @pytest.mark.LBHostRouting @pytest.mark.incremental class TestLbserviceHostRouting1: testname = "TestLbserviceHostRouting1" port = "900" service_scale = 2 lb_scale = 1 service_count = 4 @pytest.mark.create def test_lbservice_host_rout...
ronment(uuid=data[0])[0] logger.info("env is: %s", format(env))
services = \ [client.list_service(uuid=i)[0] for i in data[1]] logger.info("services: %s", services) lb_service = client.list_service(uuid=data[2])[0] assert len(lb_service) > 0 logger.info("lb service is: %s", format(lb_service)) validate_add_service_link...
zentralopensource/zentral
server/accounts/views/auth.py
Python
apache-2.0
6,664
0.001351
import logging import uuid from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME, login as auth_login from django.core import signing from django.core.exceptions import PermissionDenied from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import resolve_url fro...
on_device.get_verification_url()) else: # Okay, security check complete. Log the user in. auth_login(request, form.get_user()) return HttpResponseRedirect(redirect_to) else: try: realm_pk = uuid.UUID(request.GET.get("realm")) ...
(Realm.DoesNotExist, TypeError, ValueError): form = ZentralAuthenticationForm(request) context = { "redirect_to": redirect_to, "redirect_field_name": REDIRECT_FIELD_NAME, } if form: context["form"] = form if realm: login_realms = [realm] else: log...