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
vrutkovs/gnome-music
gnomemusic/widgets.py
Python
gpl-2.0
34,519
0.000985
# Copyright (c) 2013 Vadim Rutkovsky <vrutkovs@redhat.com> # Copyright (c) 2013 Shivani Poddar <shivani.poddar92@gmail.com> # Copyright (c) 2013 Arnel A. Borja <kyoushuu@yahoo.com> # Copyright (c) 2013 Seif Lotfy <seif@lotfy.com> # Copyright (c) 2013 Sai Suman Prayaga <suman.sai14@gmail.com> # Copyright (c) 2013 Jackso...
nderer = Gd.StyledTextRenderer( xpad=16, ellipsize=Pango.EllipsizeMode.END, xalign=0.0 ) list_widget.add_renderer(type_renderer, lambda *args: None, None) cols[0].clear_attributes(type_renderer) cols[0].add_attribute(type_renderer, 'markup', 0) ...
.StyledTextRenderer( xpad=16, ellipsize=Pango.EllipsizeMode.END, xalign=1.0 ) durationRenderer.add_class('dim-label') list_widget.add_renderer(durationRenderer, lambda *args: None, None) cols[0].clear_attributes(durationRenderer) cols[0].add_at...
DAFRELECTRONICS/IoTprinter
gfx/adalogo.py
Python
cc0-1.0
4,011
0.168786
width = 75 height = 75 data = [ 0x00,0x00,0x00,0x00,0x00,0xe0,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x01,0xf0,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x03,0xf0,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x03,0xf8,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x07,0xf8,0x00,
0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x0f,0xf8,
0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x1f,0xfc,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x1f,0xfc,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x3f,0xfc,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x7f,0xfe,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x7f,0xfe,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0xff,0xfe,0x...
ODM2/ODMToolsPython
odmtools/lib/ObjectListView/CellEditor.py
Python
bsd-3-clause
19,490
0.003797
# -*- coding: utf-8 -*- #---------------------------------------------------------------------------- # Name: CellEditor.py # Author: Phillip Piper # Created: 3 April 2008 # SVN-ID: $Id$ # Copyright: (c) 2008 by Phillip Piper, 2008 # License: wxWindows license #-------------------------...
stView""" d
ef __init__(self, *args, **kwargs): kwargs["choices"] = ["True", "False"] wx.Choice.__init__(self, *args, **kwargs) def GetValue(self): "Get the value from the editor" return self.GetSelection() == 0 def SetValue(self, value): "Put a new value into the editor" i...
hlamer/kate
addons/kate/pate/src/plugins/format.py
Python
lgpl-2.1
19,591
0.007045
# -*- coding: utf-8 -*- # # Kate/Pâté plugins to work with C++ code formatting # Copyright 2010-2013 by Alex Turbov <i.zaufi@gmail.com> # # # This software 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 Foundation...
: lineStr = str(document.line(cl)) i
f not firstIteration: # skip first iteration pos.setColumn(len(lineStr)) # set current column to the end of current line else: firstIteration = False # do nothing on first iteration # Iterate from the curre...
JohanComparat/nbody-npt-functions
bin/bin_MD/DF_read_density_field.py
Python
cc0-1.0
4,660
0.03176
# cd pySU/pyMultidark/trunk/bin/fortranfile-0.2.1/ import numpy as n import os from os.path import join from astropy.io import fits import time import fortranfile import sys DFdir = join("/data2", "users", "gustavo", "BigMD", "1Gpc_3840_Planck1_New", "DENSFIELDS") mockDir = "/data1/DATA/eBOSS/Multidark-box-mocks/v1.0...
format='D', array=vz ) c7 = fits.Column(name="Vmax",format='D', array=Vmax ) c8 = fits.Column(name="Vpeak",format=
'D', array=Vpeak ) c9 = fits.Column(name="Mvir",format='D', array=Mvir ) c10 = fits.Column(name="parent_id",format='D', array=parent_id ) c11 = fits.Column(name="snap_id",format='D', array=snap_id ) c12 = fits.Column(name="kind",format='D', array=kind ) c13 = fits.Column(name="z_dis",format='D', array=z_dis ) # n...
caspartse/python-translate
data/db2list.py
Python
mit
241
0
#!/usr/bin/env python # -*- coding:utf-8 -* import dbm import codecs db = dbm.open('./vocabulary', 'r') vDict = db.keys() vList = sorted(vDict) print len(vList) with codecs.op
en('vocabulary.list', 'w') as f: f.write('\n'.joi
n(vList))
MSusik/invenio
invenio/legacy/bibexport/templates.py
Python
gpl-2.0
29,937
0.008518
# -*- coding: utf-8 -*- ## $Id: webmessage_templates.py,v 1.32 2008/03/26 23:26:23 tibor Exp $ ## ## handles rendering of webmessage module ## ## This file is part of Invenio. ## Copyright (C) 2009, 2010, 2011 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU G...
} table.spacedcells th{ padding-right: 20px; text-align: left; } </style> <script type="text/javascript"> <!-- function SetAllCheckBoxes(FormName, FieldName, CheckValue) { if(!document.forms[FormName]) return; var objCheckBoxes = document.forms[FormName].elements[FieldName]; if(!objCheckB...
eck boxes for(var i = 0; i < countCheckBoxes; i++) objCheckBoxes[i].checked = CheckValue; } // --> </script> """ return styles def tmpl_navigation_menu(self, language = CFG_SITE_LANG): """Returns HTML representing navigation menu for field exporter.""" _ = gette...
computationalmodelling/python-package-template
package_template/arith.py
Python
bsd-2-clause
58
0
def add(x,
y): """Add two numbers""" return
x + y
drkitty/cyder
cyder/core/system/validators.py
Python
bsd-3-clause
173
0
from d
jango.core.exceptions import ValidationError def validate_no_spaces(value): if ' ' in value: raise ValidationError('System name cannot contain spaces.')
claremacrae/raspi_code
hardware/raspio_pro_hat/pulse_rgbled.py
Python
mit
570
0.001754
from gpiozero import RGBLED from time import sleep led = RGBLED(red=17, green=18, blue=19) delay = 0.02 while True: for x in ran
ge(100): led.red = x/100 sleep(delay) for x in range(100, -1, -1): led.red = x/100 sleep(delay) for x in range(100): led.green = x/100 sleep(delay) for x in range(100, -1, -1): led.green = x/100 sleep(delay) for x in range(100): l...
0, -1, -1): led.blue = x/100 sleep(delay)
endlessm/chromium-browser
third_party/llvm/lldb/test/API/issue_verification/disable.py
Python
bsd-3-clause
656
0.001524
#!/usr/bin/env python """Renames *.py files to *.py.park.""" import os import sys def main(): """Drives the main script behavior.""" script_dir = os.path.dirname(os.path.realpath(__file__)) for filename in os.listdir(script_dir): basename, extension = os.path.splitext(filename) if basename...
ce_path + ".park" sys.stdout.write("ren
aming {} to {}\n".format( source_path, dest_path)) os.rename(source_path, dest_path) if __name__ == "__main__": main()
tvgdb/pianissimo
backend/tasks/__init__.py
Python
gpl-3.0
579
0.001727
from celery
import Celery def make_celery(app): celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'], backend=app.config["CELERY_BACKEND_URL"], include=['tasks.library_tasks']) celery.conf.update(app.config) celery.conf['CELERY_ACCEPT_CONTENT'] = ['pickle', 'json'] TaskBase = celery.Task ...
se.__call__(self, *args, **kwargs) celery.Task = ContextTask return celery
FreescaleSemiconductor/quantum
quantum/plugins/metaplugin/run_tests.py
Python
apache-2.0
1,656
0.000604
#!/usr/bin/env python # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 OpenStack, LLC # 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 # # h...
gin This file should be run from the top dir in the quantum directory To run all tests:: PLUGIN_DIR=quantum/plugins/metaplugin ./run_tests.sh """ import os import sys from nose import config from nose import core sys.path.append(os.getcwd()) sys.path.append(os.path.dirname(__file__)) from quantum.common.test_...
if __name__ == '__main__': exit_status = False # if a single test case was specified, # we should only invoked the tests once invoke_once = len(sys.argv) > 1 test_config['plugin_name'] = "meta_quantum_plugin.MetaPluginV2" cwd = os.getcwd() working_dir = os.path.abspath("quantum/plugins/m...
aspc/mainsite
aspc/courses/management/commands/solicit_reviews.py
Python
mit
1,761
0.003975
from django.core.management.base import BaseCommand from aspc.courses.models import Schedule from datetime import datetime, timedelta from django.core.mail import EmailMultiAlternatives from django.template.loader import get_template from django.template import Context from aspc.settings import EMAIL_HOST_USER # Assum...
schedules = Schedule.objects.filter(create_ts__lte=datetime.now()-timedelta(days=MIN_DAYS), create_ts__gte=datetime.now()-timedelta(days=MAX_DAYS)) emails_sent = 0 for schedule in schedules: try: context = Context({'user': sc...
ender(context) user_data = schedule.user.user.all() if user_data and user_data[0].subscribed_email: msg = EmailMultiAlternatives(EMAIL_TITLE, text_content, EMAIL_HOST_USER, [schedule.user.email]) msg.attach_alternative(html_content, "text/html") ...
allenlavoie/tensorflow
tensorflow/python/layers/convolutional_test.py
Python
apache-2.0
50,372
0.003871
# Copyright 2015 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...
images = random_ops.random_uniform((5, height, width, 4), dtype='float16') output = conv_layers.conv2d(images, 32, [3, 3], activation=nn_ops.relu) self.
assertListEqual(output.get_shape().as_list(), [5, height - 2, width - 2, 32]) def testCreateConv2DIntegerKernelSize(self): height, width = 7, 9 images = random_ops.random_uniform((5, height, width, 4)) layer = conv_layers.Conv2D(32, 3) output = layer.apply(images) self.as...
r26zhao/django_blog
blog/sitemaps.py
Python
mit
697
0.008608
from django.contrib.sitemaps import Sitemap from .models import Post, Category, Tag class PostSitemap(Sitemap): priorit
y = 0.9 changefreq = 'weekly' def items(self): return Post.objects.all() def lastmod(self, obj): return obj.date_modified class CategorySitemap(Sitemap): priority = 0.9 changefreq = 'weekly' def items(self): return Category.objects.all() def lastmod(self, obj): ...
.all()[0].date_created class TagSitemap(Sitemap): priority = 0.9 changefreq = 'weekly' def items(self): return Tag.objects.all() def lastmod(self, obj): return obj.post_set.all()[0].date_created
binsina/python-searchengine
searchengine/scraper.py
Python
bsd-3-clause
3,070
0.004886
#!/usr/bin/env python from HTMLParser import HTMLParser, HTMLParseError import optparse from urllib2 import urlopen, URLError from searchengine.logger import Logging class TagSelector(HTMLParser): """ Strip all HTML tags from a string. """ def __init__(self, *args, **kwargs): self.reset() ...
nt_dict class HTMLScraper(object): """ A simple HTML Scraper class to get visable text from a given URL. """ def __init__(self, url, *args, **kwargs): self.log = kwargs.get('log', Logging(
)) self.url = url def get_url_content(self): """ Open and read the content of a URL. """ try: url_handler = urlopen(self.url) except URLError, e: self.log.warning("HTMLScraper", "get_url_content", e) return "" ...
slinderman/theano_pyglm
pyglm/components/impulse.py
Python
mit
18,930
0.004966
import theano import theano.tensor as T from pyglm.utils.basis import * from pyglm.components.component import Component from pyglm.components.priors import create_prior def create_impulse_component(model, glm, latent): typ = model['impulse']['type'].lower() if typ.lower() == 'basis': return LinearBas...
w_ir3 = T.reshape(self.w_ir, [1,self.N,self.B]) # Make w_ir3 broadcastable in the 1st dim T.addbroadcast(w_ir3,0) # Take the elementwise product of the fi
ltered stimulus and # the repeated weights to get the weighted impulse current along each # impulse basis dimension. Then sum over bases to get the # total coupling current from each presynaptic neurons at # all time points self.I_imp = T.sum(self.ir*w_ir3, axis=2) # self...
tiangolo/fastapi
docs_src/extra_models/tutorial001_py310.py
Python
mit
899
0
from fastapi import FastAPI from pydantic import BaseModel, EmailStr app = FastAPI() class UserIn(BaseModel): username: str password: str email: EmailStr full_name: str | None = None class UserOut(BaseModel): username: str email: EmailStr full_name: str | None = None class UserInDB(Ba...
_password_hasher(user_in.password) user_in_db = UserInDB(**user_in.dict(), hashed_password=hashed_password) print("User saved! ..not really") return user_
in_db @app.post("/user/", response_model=UserOut) async def create_user(user_in: UserIn): user_saved = fake_save_user(user_in) return user_saved
n3wb13/OpenNfrGui-5.0-1
lib/python/Plugins/Extensions/MediaPortal/resources/update.py
Python
gpl-2.0
6,241
0.021798
# -*- coding: utf-8 -*- ############################################################################################### # # MediaPortal for Dreambox OS # # Coded by MediaPortal Team (c) 2013-2015 # # This plugin is open source but it is NOT free software. # # This plugin may only be distributed to and executed...
riginal authors. Also decompiling and modification of the closed source # parts is NOT permitted. # # Advertising with this plugin is NOT allowed. # For other uses, permission from the authors is necessary. # ############################################################################################### from Plugin...
ion): self.session = session def checkforupdate(self): getPage("http://master.dl.sourceforge.net/project/e2-mediaportal/version.txt", timeout=15).addCallback(self.gotUpdateInfo).addErrback(self.gotError) def gotError(self, error=""): pass def gotUpdateInfo(self, html): if re.search(".*?<html", html): r...
Azure/azure-sdk-for-python
sdk/containerregistry/azure-containerregistry/azure/containerregistry/_generated/_container_registry.py
Python
mit
4,280
0.004439
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.7.4, generator: @autorest/python@5.12.4) # Changes may cause incorrect behavior and will be lost if the code is regenerated. # ------------------------------...
er_registry.operations.ContainerRegi
stryBlobOperations :ivar authentication: AuthenticationOperations operations :vartype authentication: container_registry.operations.AuthenticationOperations :param url: Registry login URL. :type url: str :keyword api_version: Api Version. The default value is "2021-07-01". Note that overriding this ...
itielshwartz/BackendApi
lib/oauth2client/devshell.py
Python
apache-2.0
4,410
0.001361
# Copyright 2015 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 required by applicable law or agree...
, 1) to_read = int(len_str) - len(json_str) if to_read > 0: json_str += sock.recv(to_read, socket.MSG_WAITALL).decode() return CredentialInfoResponse(json_str) clas
s DevshellCredentials(client.GoogleCredentials): """Credentials object for Google Developer Shell environment. This object will allow a Google Developer Shell session to identify its user to Google and other OAuth 2.0 servers that can verify assertions. It can be used for the purpose of accessing data ...
smallyear/linuxLearn
salt/salt/modules/nspawn.py
Python
apache-2.0
42,749
0.000468
# -*- coding: utf-8 -*- ''' Manage nspawn containers .. versionadded:: 2015.8.0 `systemd-nspawn(1)`__ is a tool used to manage lightweight namespace containers. This execution module provides several functions to help manage these containers. .. __: http://www.freedesktop.org/software/systemd/man/systemd-nspawn.html...
ctory {0}: {1}' .format(name, exc) ) def _build_failed(dst, name): try: __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL shutil.rmtree(dst) except OSError as exc: if exc.errno != errno.ENOENT: raise CommandExecutionError( ...
oot dir {0}'.format(dst) ) raise CommandExecutionError( 'Container {0} failed to build'.format(name) ) def _bootstrap_arch(name, **kwargs): ''' Bootstrap an Arch Linux container ''' if not salt.utils.which('pacstrap'): raise CommandExecutionError( 'pacst...
larmstrong12/portfolio
backend/apps/requests/urls.py
Python
apache-2.0
247
0.008097
from django.conf.urls import patt
erns, url from views import AddRequest, PricingList urlpatterns = patterns('', url('^request/$', AddRequest.as_view(), name='add-
request'), url('^pricing/$', PricingList.as_view(), name='pricing-list'), )
dedoogong/asrada
utils/labelImg.py
Python
apache-2.0
57,731
0.001975
#!/usr/bin/env python # -*- coding: utf-8 -*- import codecs import distutils.spawn import os.path import platform import re import sys import subprocess from functools import partial from collections import defaultdict import keyboard #Using module keyboard try: from PyQt5.QtGui import * from PyQt5.QtCore im...
ntentsMargins(0, 0, 0, 0) filelistLayout.addWidget(self.fileListWidget) fileListContainer = QWidget() fileListContainer.setLayout(filelistLayout) self.filedock = QDockWidget(u'File List', self) self.filedock.setObjectName(u'Files') self.filedock.setWidget(fileListContaine...
dget = ZoomWidget() self.colorDialog = ColorDialog(parent=self) self.canvas = Canvas(parent=self) self.canvas.zoomRequest.connect(self.zoomRequest) scroll = QScrollArea() scroll.setWidget(self.canvas) scroll.setWidgetResizable(True) self.scrollBars = { ...
awemulya/fieldsight-kobocat
onadata/apps/eventlog/migrations/0003_auto_20170522_1154.py
Python
bsd-2-clause
783
0.002554
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings c
lass Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('eventlog', '0002_auto_20170522_1134'), ] oper
ations = [ migrations.AddField( model_name='fieldsightlog', name='source', field=models.ForeignKey(related_name='log', to=settings.AUTH_USER_MODEL, null=True), ), migrations.AlterField( model_name='fieldsightlog', name='type', ...
j0hn/guicavane
setup.py
Python
gpl-3.0
5,235
0.012999
#!/usr/bin/env python # coding: utf-8 import os import sys from distutils.core import setup from distutils.command.install import install VERSION_NUMBER = "1.6.3" class CustomInstall(install): def run(self): install.run(self) for script in self.distribution.scripts: script_path = os...
translation in os.listdir("guicavane\\Translations\\"): if not os.path.isdir("guicavane\\Translations\\" + translation): continue files.append(("Translations\\" + translation
+ "\\LC_MESSAGES", ["guicavane\\Translations\\" + translation + "\\LC_MESSAGES\\" + \ x for x in os.listdir("guicavane\\Translations\\" + translation + "\\LC_MESSAGES")])) hosts_dir = "guicavane\\Hosts" hosts = os.listdir(hosts_dir) hosts = [os.path.join(hosts_dir, x) for x in hos...
fabiand/igor
igor/reports.py
Python
lgpl-2.1
2,729
0
# # Copyright (C) 2012 Red Hat, Inc. # # This program 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 Foundation; either version 2.1 of the License, or # (at your option) any later version. # # This program is dis...
ut 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 this program. If no
t, see <http://www.gnu.org/licenses/>. # # Author: Fabian Deutsch <fabiand@fedoraproject.org> # # -*- coding: utf-8 -*- import os import simplejson as json from lxml import etree import utils BASE_PATH = os.path.dirname(os.path.abspath(__file__)) REPORT_PATH = os.path.join(BASE_PATH, "data") TRANSFORM_MAP = { "j...
youtube/cobalt
build/android/pylib/instrumentation/instrumentation_parser_test.py
Python
bsd-3-clause
4,062
0.002216
#!/usr/bin/env vpython # Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unit tests for instrumentation.InstrumentationParser.""" import unittest from pylib.instrumentation import instrumentation_parse...
arser.InstrumentationParser(raw_output) statuses = list(parser.IterStatus())
code, bundle = parser.GetResult() self.assertEqual(None, code) self.assertEqual({}, bundle) self.assertEqual([], statuses) def testInstrumentationParser_resultAndCode(self): raw_output = [ 'INSTRUMENTATION_RESULT: shortMsg=foo bar', 'INSTRUMENTATION_RESULT: longMsg=a foo', 'walke...
JulyKikuAkita/PythonPrac
cs15211/LongestMountaininArray.py
Python
apache-2.0
3,561
0.003371
__source__ = 'https://leetcode.com/problems/longest-mountain-in-array/' # Time: O(N) # Space: O(1) # # Description: Leetcode # 845. Longest Mountain in Array # # Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold: # # B.length >= 3 # There exists some 0 < i < B.length - 1 # such ...
0] < B[1] < ... B[i-1]
< B[i] > B[i+1] > ... > B[B.length - 1] # (Note that B could be any subarray of A, including the entire array A.) # # Given an array A of integers, return the length of the longest mountain. # # Return 0 if there is no mountain. # # Example 1: # # Input: [2,1,4,7,3,2,5] # Output: 5 # Explanation: The largest mountain ...
lorganthesorn/CryptoArb
Analysis/calculator.py
Python
mit
603
0.011609
from M
arkets import Poloniex from Markets import YoBit p = Poloniex.Poloniex(None, None) y = YoBit.Yobit(None, None) #pPairs = [i for i in p.getTickers().keys()] #yPairs = [i for i in y.getTickers().keys()] #pPairs.sort() #yPairs.sort() yBook = y.returnOrderBook('dash_btc') pBook = p.returnOr
derBook('BTC_DASH') yBid, yAsk = float(yBook['bids'][0][0]), float(yBook['asks'][0][0]) pBid, pAsk = float(pBook['bids'][0][0]), float(pBook['asks'][0][0]) print('arb: %0.4f, y: %0.4f, p: %0.4f'%((yAsk - pBid)/pBid, yAsk, pBid)) print('arb: %0.4f, y: %0.4f, p: %0.4f'%((pAsk - yBid)/yBid, pAsk, yBid))
hzdg/django-staticbuilder
staticbuilder/management/commands/collectforbuild.py
Python
mit
5,220
0.001149
from blessings import Terminal from django.conf import settings from django.contrib.staticfiles import finders, storage as djstorage from django.core.exceptions import ImproperlyConfigured from django.core.management.base import BaseCommand from django.core.management import call_command from django.utils.encoding impo...
"" build_dirs, built_files = self.find_all(storage) found_files = set() for finder in finders.get_finders(): for path, s in finder.list([]): # Prefix the relative path if the source storage contains it if getattr(s, 'prefix', None): ...
else: prefixed_path = path found_files.add(prefixed_path) stale_files = built_files - found_files for fpath in stale_files: self.log(u"Deleting '%s'" % smart_text(fpath), level=1) storage.delete(fpath) found_dirs = se...
nylas/flanker
tests/addresslib/address_test.py
Python
apache-2.0
32,254
0.001502
# coding:utf-8 from nose.tools import assert_raises, eq_, ok_ from flanker.addresslib.address import (Address, AddressList, EmailAddress, UrlAddress) from flanker.addresslib.address import parse, parse_list def test_addr_properties(): email = parse('name@host.com') url...
tance(result, AddressList)) eq_(len(result), len(lst)+2) ok_("foo@bar.com" in result) def test_addresslist_with_apostrophe(): s = '''"Allan G\'o" <allan@example.com>, "Os Wi" <oswi@example.com>''' lst = parse_list(s) eq_(2, len(lst)) eq_('Allan G\'o <allan@example.com>', lst[0].full_spec()) ...
xample.com>', lst[1].full_spec()) lst = parse_list("Eugueny ώ Kontsevoy <eugueny@gmail.com>") eq_('=?utf-8?q?Eugueny_=CF=8E_Kontsevoy?= <eugueny@gmail.com>', lst.full_spec()) eq_(u'Eugueny ώ Kontsevoy', lst[0].display_name) def test_addresslist_non_ascii_list_input(): al = [u'Aurélien Berger <ab@exam...
talon-one/talon_one.py
talon_one/models/new_attribute.py
Python
mit
13,648
0
# coding: utf-8 """ Talon.One API The Talon.One API is used to manage applications and campaigns, as well as to integrate with your application. The operations in the _Integration API_ section are used to integrate with our platform, while the other operations are used to manage applications and campaigns. #...
t(entity, allowed_values) ) self._entity = entity @property def event_type(self): """Gets the event_type of this NewAttribute. # noqa: E501 :return: The event_type of this NewAttribute. # noqa: E501 :rtype: str """ return self._event_type @e...
e. # noqa: E501 :type: str """ self._event_type = event_type @property def name(self): """Gets the name of this NewAttribute. # noqa: E501 The attribute name that will be used in API requests and Talang. E.g. if `name == \"region\"` then you would set the region attr...
SysTheron/adhocracy
src/adhocracy/lib/cli.py
Python
agpl-3.0
10,730
0.000186
import itertools from logging import getLogger import os import signal import threading import time import paste.script import paste.fixture import paste.registry import paste.deploy.config from paste.deploy import loadapp from paste.script.command import Command import rq from adhocracy import model from adhocracy.l...
periodical['task'].enqueue() next_run = float(now + periodical['delay']) self.redis.hset(hash_name, key_name, next_run) # expire our schedules hash an our after the next sheduled run max_duration = max([p['delay'] for p in self.periodicals.values()]) ...
or can set a lock in redis. The lock will be set or extended for the given *duration* from (from the time it is set or renewed) and is valid for the current process. ''' redis = self.redis key = self.lock_key duration = self.timer_duration + 1 pid = self.p...
coreynicholson/youtube-dl
youtube_dl/extractor/npo.py
Python
unlicense
21,110
0.001895
from __future__ import unicode_literals import re from .common import InfoExtractor from ..compat import ( compat_HTTPError, compat_str, ) from ..utils import ( determine_ext, ExtractorError, fix_xml_ampersands, orderedSet, parse_duration, qualities, strip_jsonp, unified_strdat...
, }, { 'url': 'http://www.npo.nl/de-nieuwe-mens-deel-1/21-07-2010/WO_VPRO_043706', 'info_dict': { 'id': 'WO_VPRO_043706', 'ext': 'm4v', 'title': 'De nieuwe mens - Deel 1', 'description': 'md5:518ae51ba1293ffb80d8d8ce90b74e4b',
'duration': 4680, }, 'params': { 'skip_download': True, } }, { # non asf in streams 'url': 'http://www.npo.nl/hoe-gaat-europa-verder-na-parijs/10-01-2015/WO_NOS_762771', 'info_dict': { 'id': 'WO_NOS_762771', 'ext': 'mp4', ...
neerajvashistha/pa-dude
lib/python2.7/site-packages/sphinx/ext/pngmath.py
Python
mit
9,187
0.000544
# -*- coding: utf-8 -*- """ sphinx.ext.pngmath ~~~~~~~~~~~~~~~~~~ Render math in HTML via dvipng. This extension has been deprecated; please use sphinx.ext.imgmath instead. :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re i...
p.builder, '_mathpng_tempdir'): return try: shutil.rmtree(app.builder._mathpng_tempdir) except Exception: pass def get_tooltip(self, node): if self.builder.config.pngmath_add_tooltips: return ' alt="%s"' % self.encode(node['latex']).strip() return '' def html_visit_ma...
sm = nodes.system_message(msg, type='WARNING', level=2, backrefs=[], source=node['latex']) sm.walkabout(self) self.builder.warn('display latex %r: ' % node['latex'] + msg) raise nodes.SkipNode if fname is None: # something failed -- use text-only a...
SummerLW/Perf-Insight-Report
dependency_manager/dependency_manager/manager.py
Python
bsd-3-clause
7,128
0.003788
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os from dependency_manager import base_config from dependency_manager import exceptions DEFAULT_TYPE = 'default' class DependencyManager(object):...
nfo2} # dependency2: {platform1: dependency_info3, # ...} # ...} # # Where the dependencies and platforms are strings, and the # dependency_info's are DependencyInfo instances. self._lookup_dict = {} s
elf.supported_configs = supported_config_types or [] for config in configs: self._UpdateDependencies(config) def FetchPath(self, dependency, platform): """Get a path to an executable for |dependency|, downloading as needed. A path to a default executable may be returned if a platform specific ...
hujiaweibujidao/XSolutions
python/APythonTest.py
Python
apache-2.0
2,492
0.002097
# # coding=utf-8 # import os # def tree(top): # #path,folder list,file list # for path, names, fnames in os.walk(top): # for fname in fnames: # yield os.path.join(path, fname) # # for name in tree(os.getcwd()): # print name # # import time # from functools import wraps # # def timethis(f...
# Class of obj is <type 'type'> # # print(obj.__metaclass__) # # # def temp(x): # return x+2 # # print(temp.func_code) # # import dis # print([ord(b) for b in temp.func_code.co_code]) # dis.dis(temp.func_code) # # #写一个程序,打印数字1到100,3的倍数打印“Fizz”来替换
这个数,5的倍数打印“Buzz”, # #对于既是3的倍数又是5的倍数的数字打印“FizzBuzz”。 # for x in range(101): # #4 is string length # print "fizz"[x%3*4::]+"buzz"[x%5*4::] or x # # class decorator(object): # # def __init__(self, f): # print("inside decorator.__init__()") # # f() # Prove that function definition has completed ...
mzdaniel/oh-mainline
vendor/packages/mock/tests/testmagicmethods.py
Python
agpl-3.0
10,336
0.003289
# Copyright (C) 2007-2011 Michael Foord & the mock team # E-mail: fuzzyman AT voidspace DOT org DOT uk # http://www.voidspace.org.uk/python/mock/ from tests.support import unittest2, inPy3k try: unicode except NameError: # Python 3 unicode = str long = int import inspect from mock import Mock, MagicM...
assertEqual(mock == object(), False) self.ass
ertEqual(mock != object(), True) def eq(self, other): return other == 3 mock.__eq__ = eq self.assertTrue(mock == 3) self.assertFalse(mock == 4) def ne(self, other): return other == 3 mock.__ne__ = ne se...
haku86/happyowlweb
happyowlweb/happyowlweb/wsgi.py
Python
mit
1,570
0.001274
""" WSGI config for happyowlweb project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATIO...
os.path import abspath, dirname from sys import path SITE_ROOT = dirname(dirname(abspath(__file__))) path.append(SITE_ROOT) # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in...
s" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "happyowlweb.settings.production") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application applicati...
sharph/lifx-python
lights_on.py
Python
agpl-3.0
71
0.014085
#!/usr/bin/env python3 import lifx lifx.set_power(lifx.BCAST, T
rue)
RobertoPrevato/flask-three-template
bll/membership/__init__.py
Python
mit
1,482
0.006073
""" * Copyright 2015, Roberto Prevato roberto.prevato@gmail.com * https://github.com/RobertoPrevato/Flask-three-template * * Licensed under the MIT license: * http://www.opensou
rce.org/licenses/MIT """ from bll.membership.membershipprov
ider import MembershipProvider def register_membership(app): """ Initialize an application global membership provider. NB: an alternative, if needed, is to initialize a membership provider for each logical area (e.g. admin, public, etc.); which allows to use different database structures to sto...
derekmoyes/opsy
opsy/plugins/monitoring/main.py
Python
mit
1,477
0.001354
from flask import Blueprint, render_template, redirect, url_for, current_app monitoring_main = Blueprint('monitoring_main', __name__, # pylint: disable=invalid-name template_folder='templates', static_url_path='/static', static_folde...
ta(): data = { 'dashboards': current_app.config['monitoring']['dashboards'], 'uchiwa_url': current_app.config['monitoring']['uchiwa_url'], } return data @monitoring_main.route('/') def index(): return redirect(url_for('monitoring_main.events')) @monitorin
g_main.route('/events') def events(): return render_template('events.html', title='Events') @monitoring_main.route('/checks') def checks(): return render_template('checks.html', title='Checks') @monitoring_main.route('/clients') def clients(): return render_template('clients.html', title='Clients') @m...
seecr/meresco-distributed
test/failover/matchesversiontest.py
Python
gpl-2.0
7,957
0.003896
## begin license ## # # "Meresco Distributed" has components for group management based on "Meresco Components." # # Copyright (C) 2018, 2021 Seecr (Seek You Too B.V.) https://seecr.nl # Copyright (C) 2021 Data Archiving and Network Services https://dans.knaw.nl # Copyright (C) 2021 SURF https://www.surf.nl # Copyright...
on': '0.1'})) try: _ = self.top.call.somemessage() self.fail() except NoneOfTheObserversRespond: pass self.assertEqual(['updateConfig'], self.observer.calledMethodNames()) def testDoesMatchCall(self): consume(self.matchesVersion.updateConfig(**{'s...
f testDoesNotMatchAny(self): consume(self.matchesVersion.updateConfig(**{'software_version': '0.1'})) try: _ = retval(self.top.any.somemessage()) self.fail() except NoneOfTheObserversRespond: pass self.assertEqual(['updateConfig'], self.observer.called...
comsaint/legco-watch
app/raw/processors/library_member.py
Python
mit
5,346
0.002806
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.timezone import now import json import logging import os import re import shutil import warnings from raw.models import RawCouncilAgenda, LANG_EN, LANG_CN, RawMember, GENDER_M, GENDER_F from raw import utils from ...
English only items keys_to_copy = [u'year_of_birth', u'place_of_birth', u'homepage'] for k in keys_to_copy: val = item.get(k,
None) if val is not None: setattr(obj, k, val.strip()) if item[u'gender'] == u'M': obj.gender = GENDER_M else: obj.gender = GENDER_F # Copy and rename the photo to the app # Unless it is the generic photo...
mkaiserpm/emonpython
emontranslator.py
Python
mit
2,232
0.010305
#!/usr/bin/python ''' Created on 01.05.2017 @author: mario Emontranslator Receive messages from serial/uart Generate JSON Emon Input Messages Insert via EMON API / APIKEY to emoncms on locahost (running on pi) ''' import serial import httplib import time domain = "localhost" emoncmspath = "emoncms" apikey = "2eba9...
rd emontx baud rate ser = serial.Serial('/dev/ttyS0', 9600) def parseLine(linestr): nodeid = None temp = 0 humid = 0 voltage = 0 if "BAD-CRC" n
ot in linestr: if len(linestr) > 2: data = linestr.split(" ") print linestr print data nodeid = int(data[0]) temp = float(data[1]) temp = temp/ 100. humid = float(data[2]) humid = humi...
sfam/netdisco
netdisco/tellstick.py
Python
mit
1,815
0.000551
"""Tellstick device discovery.""" import socket import threading from datetime import timedelta DISCOVERY_PORT = 30303 DISCOVERY_ADDRESS = '<broadcast>' DISCOVERY_PAYLOAD = b"D" DISCOVERY_TIMEOUT = timedelta(seconds=5) class Tellstick(object): """Base class to discover Tellstick devices.""" def __init__(se...
self.scan() return self.entries def update(self): """Scan network for Tellstick devices.""" entri
es = [] sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(DISCOVERY_TIMEOUT.seconds) sock.sendto(DISCOVERY_PAYLOAD, (DISCOVERY_ADDRESS, DIS...
leafnode/npp_markdown_script
lib/markdown/__main__.py
Python
bsd-3-clause
3,376
0.004443
""" COMMAND-LINE SPECIFIC STUFF ============================================================================= """ import markdown import sys import optparse import logging from logging import DEBUG, INFO, CRITICAL logger = logging.getLogger('MARKDOWN') def parse_options(): """ Define and parse `optparse` ...
t_file = sys.stdin else: input_file = args[0]
if not options.extensions: options.extensions = [] return {'input': input_file, 'output': options.filename, 'safe_mode': options.safe, 'extensions': options.extensions, 'encoding': options.encoding, 'output_format': options.output_format, ...
NinjaMSP/crossbar
crossbar/adapter/mqtt/test/interop.py
Python
agpl-3.0
6,672
0.002398
##################################################################################### # # Copyright (c) Crossbar.io Technologies GmbH # # Unless a separate license agreement exists between you and Crossbar.io GmbH (e.g. # you have purchased a commercial license), the license terms below apply. # # Should you enter ...
ecord.popleft() if x == reading.data: pass elif isinstance(reading.data, list) and x in reading.data: reading.data.remove(x)
else: self.factory.success = False self.factory.reason = (x, reading.data) self.factory.reactor.stop() return if len(self._record) > 0: while len(self._record) > 0 and self._record[0].send: ...
badloop/SickRage
sickrage/show/Show.py
Python
gpl-3.0
5,537
0.002167
# This file is part of SickRage. # # URL: https://www.sickrage.tv # Git: https://github.com/SickRage/SickRage.git # # SickRage 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, o...
therwise - the show object that was deleted, if it exists, ``None`` otherwise """ error, show = Show._validate_indexer_id(indexer_id) if error is not None: return error, show try: sickbeard.showQueueScheduler.action.removeShow(show, bool(remove_files))...
return ex(exception), show return None, show @staticmethod def overall_stats(): db = DBConnection() shows = sickbeard.showList today = str(date.today().toordinal()) downloaded_status = Quality.DOWNLOADED + Quality.ARCHIVED snatched_status = Quality.SNATCH...
edoburu/django-parler-rest
testproj/migrations/0001_initial.py
Python
apache-2.0
1,819
0.003299
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Country', fields=[ ('id', models.AutoField(verb...
('country_code', models.CharField(unique=True, max_length=2, verbose_name='country code', db_index=True)),
], options={ 'verbose_name': 'country', 'verbose_name_plural': 'countries', }, bases=(models.Model,), ), migrations.CreateModel( name='CountryTranslation', fields=[ ('id', models.AutoField(ver...
google-research/tensor2robot
utils/train_eval_test_utils.py
Python
apache-2.0
5,835
0.005656
# coding=utf-8 # Copyright 2022 The Tensor2Robot Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
filename patterns are used. """ if expected_output_filename_patterns is None: expected_output_filename_patterns = ( DEFAULT_TRAIN_FILENAME_PATTERNS + DEFAULT_EVAL_FILENAME_PATTERNS) # Check that expected files have been written. for pattern in expected_output_filename_patterns: filename_patter...
, filenames) filenames_dir = tf.io.gfile.listdir(model_dir) tf.logging.info('filenames_dir: %s', filenames_dir) test_case.assertNotEmpty( filenames, msg='No files found with pattern "%s"' % filename_pattern) for filename in filenames: with tf.io.gfile.GFile(filename) as f: test_cas...
fayf/pyload
module/plugins/hoster/SpeedyshareCom.py
Python
gpl-3.0
1,259
0.009531
# -*- coding: utf-8 -*- # # Test links: # http://speedy.sh/ep2qY/Zapp-Brannigan.jpg import re import urlparse from module.plugins.internal.SimpleHoster import SimpleHoster, create_getInfo class SpeedyshareCom(SimpleHoster): __name__ = "SpeedyshareCom" __type__ = "hoster" __version__ = "0.06" _...
e(self, pyfile): m = re.search(self.LINK_FREE_PATTERN, se
lf.html) if m is None: self.link = m.group(1) getInfo = create_getInfo(SpeedyshareCom)
brave/muon
script/bump-version.py
Python
mit
1,507
0.013271
#!/usr/bin/env python import os import re import sys from lib.config import SOURCE_ROOT, get_electron_version, get_chrome_version from lib.util import execute, parse_version, scoped_cwd def main(): if len(sys.argv) != 2 or sys.argv[1] == '-h': print 'Usage: bump-version.py [<version> | major | minor | patch]'...
ion + '+' + chrome with scoped_cwd(SOURCE_ROOT): update_package_json(version) tag_version(version) def increase_version(versions, index): for i in range(index + 1, 3): versions[i] = '0' versions[index] = str(int(versions[index]) + 1) return versions def update_package_json(version): package_j...
, 'r') as f: lines = f.readlines() for i in range(0, len(lines)): line = lines[i]; if 'version' in line: lines[i] = ' "version": "{0}",\n'.format(version) break with open(package_json, 'w') as f: f.write(''.join(lines)) def tag_version(version): execute(['git', 'commit', '-a', '-m...
ttindell2/openshift-ansible
roles/openshift_health_checker/openshift_checks/logging/logging_index_time.py
Python
apache-2.0
4,995
0.003003
""" Check for ensuring logs from pods can be queried in a reasonable amount of time. """ import json import time from uuid import uuid4 from openshift_checks import OpenShiftCheckException from openshift_checks.logging.logging import LoggingCheck ES_CMD_TIMEOUT_SECONDS = 30 class LoggingIndexTime(LoggingCheck): ...
ame in (['kibana', 'Kibana'], ['es', 'Elasticsearch']): pods = self.get_pods_for_component(component) running_pods = self.running_pods(pods) if not running_pods: raise OpenShiftCheckException(
component + 'NoRunningPods', 'No {} pods in the "Running" state were found.' 'At least one pod is required in order to perform this check.'.format(name) ) running_component_pods[component] = running_pods uuid = self.curl_kibana_wi...
roofit-dev/parallel-roofit-scripts
profiling/vincemark/analyze_g.py
Python
apache-2.0
13,421
0.005663
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Author: Patrick Bos # @Date: 2016-11-16 16:23:55 # @Last Modified by: E. G. Patrick Bos # @Last Modified time: 2017-09-05 17:27:17 import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from pathlib import Path import itertool...
.factorplot(x='num_cpu', y='walltime_s', col='N_bins', hue='timing_type', row='segment', estimator=np.min, data=df_totals, legend_out
=False, sharey='row') # plt.subplots_adjust(top=0.93) # g.fig.suptitle(f'total wallclock timing of migrad, hesse and minos') # savefig(g, savefig_dn / f'total_timing.png') plot_stuff = input("press ENTER to plot stuff, type n and press ENTER to not plot stuff. ") if plot_stuff != "n": g = sns.factorplot(x='N_bins...
python27/NetworkControllability
NetworkControllability/strutral_controllability.py
Python
bsd-2-clause
6,085
0.009696
""" structral controllability measure, driver nodes """ # Copyright (C) 2014 by # Xin-Feng Li <silfer.lee@gmail.com> # All rights reserved # BSD license import networkx as nx import matplotlib.pyplot as plt __author__ = """Xin-Feng Li (silfer.lee@gmail.com)""" def get_driver_nodes(DG): '''Return the dri...
h, node number start from 0 Returns ------- driver node num: the number of
driver nodes driver nodes: the driver nodes we are looking for Notes: ------- The index of nodes in DG must start from 0, 1, 2, 3... References: ----------- [1] Yang-Yu Liu, Jean-Jacques Slotine, Albert L. Barabasi. Controllability of complex networks. Nature, 2011. ''' ...
CMPUT404W17/FoundBook
fb/tests.py
Python
mit
12,320
0.008929
from django.test import TestCase from fb.models import Author, Post, Comment, Config from django.contrib.auth.models import User from fb.services.post_service import PostService from django.test.utils import setup_test_environment import json from BeautifulSoup import BeautifulSoup class ClientTest(TestCase): def...
, "contentType": "text/plain", "description": "", "content": "dont care", "visibility": "r", "unlisted": False, "author_id": self.users[1].author.id}, {"title": "friend only 10", "source": "http://", "origin": "http://", "contentType": "text/plain", "descr...
author_id": self.users[2].author.id}, {"title": "friend private 11", "source": "http://", "origin": "http://", "contentType": "text/plain", "description": "", "content": "dont care", "visibility": "r", "unlisted": False, "author_id": self.users[2].author.id}, ...
Shaps/ansible
test/support/network-integration/collections/ansible_collections/ansible/netcommon/plugins/modules/net_logging.py
Python
gpl-3.0
2,503
0.001199
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Ansible by Red Hat, inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type
ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["deprecated"], "supported_by": "network", } DOCUMENTATION = """module: net_logging author: Ganesh Nalawade (@ganeshrn) short_description: Manage logging on network devices description: - This module provides declarative management of logging on n...
alternative: Use platform-specific "[netos]_logging" module why: Updated modules released with more functionality extends_documentation_fragment: - ansible.netcommon.network_agnostic options: dest: description: - Destination of the logs. choices: - console - host name: description: ...
pepitogithub/PythonScripts
Letras.py
Python
gpl-2.0
550
0.049091
class Letras: """ - Contenedor de letras (no incluye la enie). - Tiene tres set(): - vocales. - consonantes. - letras. - Tener en cuenta que al ser Set(), no tienen orden, por lo
que de ser necesario, se deben castear a list() y ordenar el nuevo objeto con el metodo conveniente. """ vocales = set(["a","e","i","o","u"])
consonantes = set(["b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z"]) letras = vocales.union(consonantes)
PyQwt/PyQwt4
qt3examples/MultiDemo.py
Python
gpl-2.0
4,825
0.001865
#!/usr/bin/env python # Plot of Numeric & numarray arrays and lists & tuples of Python floats. import sys from qt import * from Qwt4.Qwt import * def drange(start, stop, step): start, stop, step = float(start), float(stop), float(step) size = int(round((stop-start)/step)) result = [start]*size for i ...
stall NumPy to plot NumPy arrays" except TypeError, message: print "%s: %s" % (TypeError, message) print "Rebuild PyQwt to plot NumPy arrays" self.removeChild(numpy_plot) # try to create a plot widget for Numeric arrays try: # i
mport does_not_exist import Numeric numeric_plot = QwtPlot('Plot -- Numeric arrays', self) numeric_plot.plotLayout().setCanvasMargin(0) numeric_plot.plotLayout().setAlignCanvasToScales(1) numeric_x = Numeric.arange(0.0, 10.0, 0.01) numeric_y = lore...
adaptive-learning/proso-apps
proso_concepts/models.py
Python
mit
14,974
0.002872
from collections import defaultdict from datetime import datetime, timedelta from django.contrib.auth.models import User from django.db import models from django.db.models import Q, Count, Sum, Max, Min from django.db.models.signals import pre_save from django.dispatch import receiver from hashlib import sha1 from pros...
is should by corner case, so it is efficient to not filter Answers continue # item is not in concept time_expiration_lower_bound = get_config('proso_models', 'knowledge_overview.time_shift_hours', default=4) time_expiration_factor = get_config('proso_models', 'knowledge_overvi...
t=2) for concept in mapping[item]: if user in current_user_stats and concept in current_user_stats[user] \ and current_user_stats[user][concept].time > time: if not self.has_time_expired(current_user_stats[user][concept].time, time, time_expiration...
OpenMined/PySyft
packages/syft/src/syft/lib/misc/__init__.py
Python
apache-2.0
6,217
0.002091
# stdlib from collections import defaultdict import sys from typing import Any as TypeAny from typing import Callable from typing import Dict from typing import KeysView from typing import List as TypeList from typing import Set # third party from cachetools import cached from cachetools.keys import hashkey # relativ...
for tar
get_method, allowed in allowed_functions.items(): if not allowed: continue def generate_func(target_method: str) -> Callable: def func(self: TypeAny, *args: TypeAny, **kwargs: TypeAny) -> TypeAny: func = getattr(self, target_method, None) ...
Lekensteyn/Solaar
lib/logitech_receiver/settings.py
Python
gpl-2.0
12,856
0.025124
# -*- python-mode -*- # -*- coding: UTF-8 -*- ## Copyright (C) 2012-2013 Daniel Pavel ## ## 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...
d=None, label=None, description=None, device_kind=None): assert name self.name = name self.label = label or name self.description = description self.device_kind = device_kind self._rw = rw self._validator = validator ass
ert kind is None or kind & validator.kind != 0 self.kind = kind or validator.kind self.persister = None def __call__(self, device): assert not hasattr(self, '_value') assert self.device_kind is None or device.kind in self.device_kind p = device.protocol if p == 1.0: # HID++ 1.0 devices do not support f...
FrodeSolheim/fs-uae-launcher
launcher/settings/audio_settings_page.py
Python
gpl-2.0
1,061
0
import fsui from fswidgets.widget import Widget from launcher.i18n import gettext from launcher.option import Option from launcher.settings.settings_page import SettingsPage from system.prefs.components.notworking import PrefsNotWorkingWarningPanel class AudioSettingsPage(SettingsPage): def __init__(self, parent:...
itle = gettext("Audio") subtitle = "" self.add_header(icon, title, subtitle) self.add_option("volume") self.add_option("stereo_separation") self.add_section(gettext("Floppy Drive Sound Emulation")) self.add_option("floppy_drive_volume") self.add_option(Option.FL...
cy") self.add_option("audio_buffer_target_size")
SuperDARNCanada/borealis
experiments/testing_archive/test_rxfreq_not_num.py
Python
gpl-3.0
1,611
0.005587
#!/usr/bin/python # write an experiment that raises an exception import sys import os BOREALISPATH = os.environ['BOREALISPATH'] sys.path.append(BOREALISPATH) import experiments.superdarn_common_fields as scf from experiment_prototype.experiment_prototype import ExperimentPrototype from utils.experiment_options.expe...
"beam_angle": scf.STD_16
_BEAM_ANGLE, "beam_order": beams_to_use, "scanbound": [i * 3.5 for i in range(len(beams_to_use))], #1 min scan "rxfreq" : '12005', # not an int or float "acf": True, "xcf": True, # cross-correlation processing "acfint": True, # interferometer acf...
wisechengyi/pants
src/python/pants/option/enclosing_scopes_test.py
Python
apache-2.0
3,058
0.003924
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import unittest from pants.option.parser_hierarchy import InvalidScopeError, all_enclosing_scopes, enclosing_scope from pants.option.scope import GLOBAL_SCOPE class TestEnclosingScopeTr...
nent, and scopes with empty components raise an InvalidSc
opeError.""" base_dashed_scope = "base-scope" self.assertEqual(enclosing_scope(base_dashed_scope), GLOBAL_SCOPE) subscope_underscore = "sub_scope" self.assertEqual(enclosing_scope(subscope_underscore), GLOBAL_SCOPE) compound_scope = f"{base_dashed_scope}.{subscope_underscore}" ...
sharadagarwal/autorest
AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/operations/http_server_failure.py
Python
mit
7,501
0.000533
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
request = self._client.head(url, query_parameters) response = self._cli
ent.send(request, header_parameters, **operation_config) if response.status_code < 200 or response.status_code >= 300: raise models.ErrorException(self._deserialize, response) if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response...
whypro/IBATI
ibati/models/backup.py
Python
mpl-2.0
350
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime from ..extensions import db cl
ass Backup(db.Model): __tablename__ = 'ibati_backup' id = db.Column(db.Integer, primary_key=True) date_str = db.Column(db.String(14), nullable=False) zip_file = db.Column(db.String(255)) size
= db.Column(db.Integer)
zhangnian/fastapi
fastapi/utils/error_handlers.py
Python
mit
404
0.002475
from flask import jsonify def error_404_handler(error): resp = jsonify({
'code': -1, 'msg': 'not found', '
data': None}) resp.status_code = 404 return resp def error_429_handler(error): resp = jsonify({'code': -1, 'msg': 'to many requests', 'data': None}) resp.status_code = 429 return resp def error_handler(error): response = jsonify(error.to_dict()) return response
ShyamSS-95/Bolt
bolt/lib/nonlinear/nonlinear_solver.py
Python
gpl-3.0
29,921
0.010227
#!/usr/bin/env python3 # -*- coding:
utf-8 -*- """ This is the module where the main solver object for the nonlinear solver of bolt is defined. This solver object stores the details of the system defined under physical_system, and is evolved using the methods of this module. The solver has the opt
ion of using 2 different methods: - A semi-lagrangian scheme based on Cheng-Knorr(1978) which uses advective interpolation.(non-conservative) - The interpolation schemes available are linear and cubic spline. - Finite volume scheme(conservative): - Riemann solvers available are the local Lax-F...
Nettacker/Nettacker
lib/payload/scanner/ics_honeypot/changes_percentage.py
Python
gpl-3.0
1,608
0.004975
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function import sys import json HONEYPOT_CHANGES_PERCENTAGE = 11 def files_check(): try: file1 = open(sys.argv[1], "rb").read() except Exception as _: sys.exit(print("cannot open the file, {0}".format(sys.argv[1]))) t...
main__": if len(sys.argv) != 3: sys.exit(print("usage: python {0} file1.json file2.json".format(sys.argv[0]))) file1, file2 = files_check() for target_selected in file1: NOT_FIND_FLAG = True for target_find in file2: if target_selected["host"] == target_find["host"]: ...
PERCENTAGE = percentage(target_selected["I20100_RESPONSE"], target_find["I20100_RESPONSE"]) print("HOST:{0}\tCHANGE PERCENTAGE:{1}%\tDEFAULT CONFIG:{2}\tI30100 TRAP:{3}".format( target_selected["host"], PERCENTAGE, target_selected["DEFAULT_SIGNATURES"] or ...
KevinSeghetti/survey
survey/checklist/migrations/0012_auto_20150928_1443.py
Python
gpl-3.0
503
0.001988
# -*- coding: utf-8 -*- fro
m __future__ import unicode_literals from django.db import models, migrations def fix_notes_field (apps, schema_editor): Question = apps.get_model("checklist", "Question") for question in Question.objects.all(): question.notes = "" question.save() class Migration(migrations.Migration): ...
eld), ]
meego-tablet-ux/meego-app-browser
tools/site_compare/scrapers/ie/__init__.py
Python
bsd-3-clause
735
0.012245
#!/usr/bin/python2.4 # # Copyright 2007 Google Inc. All Rights Reserved. """Selects the appropriate scraper for Internet Explorer.""" __author__ = 'jhaas@google.com (Jonathan Haas)' def GetScraper(version): """Returns the scraper mo
dule for the given version. Args: version: version string of IE, or None for most recent Returns: scrape module for given version """ # Pychecker will warn that the parameter is unused; we only # support one version of IE at this time # We only have one version of the IE scraper for now return...
e__ == "__main__": version = "7.0.5370.1" print GetScraper(version).version
editeodoro/Bbarolo
pyBBarolo/_version.py
Python
gpl-2.0
32
0
__version__ =
version = '1
.2.3'
huzq/scikit-learn
sklearn/feature_extraction/tests/test_dict_vectorizer.py
Python
bsd-3-clause
7,189
0.000835
# Authors: Lars Buitinck # Dan Blanchard <dblanchard@ets.org> # License: BSD 3 clause from random import Random import numpy as np import scipy.sparse as sp from numpy.testing import assert_array_equal from numpy.testing import assert_allclose import pytest from sklearn.feature_extraction import DictVectori...
[0.0, 0.3, 0.0, 1.0, 0.0], [0.0, -1.0, 0.0, 0.0, 1.0], ] D_in = [ {"version": ["1", "2", "1"], "ham": 2}, {"version": "2", "spam": 0.3}, {"version=3": True, "spam": -1}, ] v = DictVectorizer() X = v.fit_transform(D_in) X = X.toarray() assert_array_equal(X, X_...
D_out = v.inverse_transform(X) assert D_out[0] == {"version=1": 2, "version=2": 1, "ham": 2} names = v.get_feature_names() assert names == D_names def test_iterable_not_string_error(): error_value = ( "Unsupported type <class 'int'> in iterable value. " "Only iterables of string ...
lizardsystem/lizard-wbconfiguration
lizard_wbconfiguration/migrations/0033_auto__chg_field_areaconfiguration_nutc_inc_2__chg_field_areaconfigurat.py
Python
gpl-3.0
75,395
0.005756
# encoding: 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): # Changing field 'AreaConfiguration.nutc_inc_2' db.alter_column('lizard_wbconfiguration_areaconfiguration'...
db.alter_column('lizard_wbconfiguration_areaconfiguration', 'min_concentr_nitrogyn_precipitation', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=20, decimal_places=5)) # Changing field 'AreaConfiguration.nutc_min_2' db.alter_column('lizard_wbconfiguration_areaconfigurat...
ax_digits=20, decimal_places=5)) # Changing field 'AreaConfiguration.ini_con_cl' db.alter_column('lizard_wbconfiguration_areaconfiguration', 'ini_con_cl', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=20, decimal_places=5)) # Changing field 'AreaConfiguration.wegz' ...
KWierso/treeherder
treeherder/etl/jobs.py
Python
mpl-2.0
18,563
0.000593
import copy import logging import os import time from datetime import datetime from hashlib import sha1 import newrelic.agent from django.core.exceptions import ObjectDoesNotExist from django.db.utils import IntegrityError from past.builtins import long from treeherder.etl.artifact import (serialize_artifact_json_blo...
atum.get('start_timestamp'))) end_time = datetime.fromtimestamp( _get_number(job_datum.get('end_timestamp'))) # first, try to create the job with the given guid (if it doesn't # exist yet) job_guid_root = get_guid_root(job_guid) if not Job.objects.filter(guid__in=[job_guid, job_guid_root])....
ultaneously. So just attempt to create # it, but allow it to skip if it's the same guid. The odds are # extremely high that this is a pending and running job that came in # quick succession and are being processed by two different workers.
tridge/MAVProxy
MAVProxy/modules/mavproxy_rally.py
Python
gpl-3.0
13,720
0.0043
""" MAVProxy rally module """ from pymavlink import mavwp from pymavlink import mavutil import time, os, platform from MAVProxy.modules.lib import mp_module from MAVProxy.modules.lib import mp_util if mp_util.has_wxpython: from MAVProxy.modules.lib.mp_menu import * class RallyModule(mp_module.MPModule): ...
if len(args) < 3: flag = self.settings.rally_flags else: flag = int(args[2]) #currently only supporting autoland values: #True (nonzero) and False (zero)
if (flag != 0): flag = 2 if not self.have_list: print("Please list rally points first") return if (self.rallyloader.rally_count() > 4): print("Only 5 rally points possible per flight plan.") return latlon = self.mpstate.c...
lileeyao/acm
dp/hard/longest_substring_without_repeating_characters.py
Python
gpl-2.0
520
0.001923
class Solution: # @return an integer def lengthOfLon
gestSubstring(self, s): lookup = {} maxlen = 0 start = 0 for i in xrange(len(s)): if s[i] not in lookup: lookup[s[i]] = i else: maxlen = max(maxlen, i - start) start = max(start, lookup[s[i]] + 1) ...
ution() print s.lengthOfLongestSubstring("wlrbbmbmasdas")
sumeet/stopwatch
tests.py
Python
mit
2,021
0
import time import unittest import stopwatch class MockSystemClock(object): """Represents a system clock with time starting at `0` and incremented whenever `sleep()` is called. Meant to replace the `time()` and `sleep()` functions in the `time` module. >>> clock = MockSystemClock() >>> clock.ti...
ef sleep(self, seconds): """Increment the system time by `seconds`.""" self._system_time += seconds class StopwatchTestCase(unittest.TestCase): def setUp(self): """Monkey patch `time.time()` and `time.sleep()` to point to the corresponding methods on a new `MockSystemClock` instan...
self._time_time = time.time self._time_sleep = time.sleep mock_system_clock = MockSystemClock() time.time = mock_system_clock.time time.sleep = mock_system_clock.sleep def tearDown(self): """Restore the `time` module.""" time.time = self._time_time ti...
Damgaard/account-deleter
deleter/tests.py
Python
gpl-3.0
1,050
0
# Copyright (C) 2013 Andreas Damgaard Pedersen # # This program is free software: you
can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even...
NU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from django.test import TestCase ...
AlpineNow/python-alpine-api
alpine/workspace.py
Python
mit
18,353
0.003106
from __future__ import absolute_import from .exception import * from .alpineobject import AlpineObject from .user import User import json class Workspace(AlpineObject): """ A class for interacting with workspaces. The top-level methods deal with workspace properties. The subclass `Member` can be used to...
s
tage
tdruez/django-registration
registration/tests/test_views.py
Python
bsd-3-clause
1,271
0.000787
""" Tests for django-registration's built-in views. """ from django.core.urlresolvers import reverse from django.test import override_settings, TestCase from ..models import RegistrationProfile @override_settings(ROOT_URLCONF='registration.tests.urls') class ActivationViewTests(TestCase): """ Tests for asp...
data = { 'username': 'bob', 'email': 'bob@example.com', 'password1': 'secret', 'password2': 'secret' } resp = self.client.post( reverse('registration_register'), data=data ) profile = Regis
trationProfile.objects.get( user__username=data['username'] ) resp = self.client.get( reverse( 'registration_activate', args=(), kwargs={'activation_key': profile.activation_key} ) ) self.assertRedirects...
jupiny/EnglishDiary
english_diary/users/mixins/tasks.py
Python
mit
1,168
0
from django.conf import settin
gs from django.contrib.auth import get_user_model from django.template.loader import render_to_string from core.utils.email import send_email class SendVerificationEmailTaskMixin(object): @property def email_sender(self): return NotImplemented @property def email_subject(self): retu...
otImplemented @property def email_template(self): return NotImplemented def run(self, user_id): user = get_user_model().objects.get(pk=user_id) # Send email to only user who has email except for TEST_EMAIL if user.email and user.email != settings.TEST_EMAIL: se...
Velkata/IntorductionToLogicApps_AzureBootcampBulgaria2016
src/daTkzsGame/Tkzs/Tkzs/app.py
Python
apache-2.0
876
0.004566
""" This script runs the application using a development server. It contains the definition of routes and views for the application. """ from flask import Flask, render_template, request import requests app = Flask(__name__) app.config.from_pyfile('app.cfg') # Make the WSGI interface available at the top level so wf...
s.post(app.config['TRIGGER_URL'], data=request.data, headers={'Con
tent-type': 'application/json'}, timeout=200) return r.text, r.status_code if __name__ == '__main__': import os HOST = os.environ.get('SERVER_HOST', 'localhost') try: PORT = int(os.environ.get('SERVER_PORT', '5555')) except ValueError: PORT = 5555 app.run(HOST, PORT)
opencivicdata/scrapers-ca
disabled/ca_sk_municipalities/people.py
Python
mit
3,626
0.003309
from utils import CanadianScraper, CanadianPerson as Person from pupa.scrape import Organization import os import re import subprocess from urllib.request import urlopen COUNCIL_PAGE = 'http://www.municipal.gov.sk.ca/Programs-Services/Municipal-Directory-pdf' # See also HTML format http://www.mds.gov.sk.ca/apps/Pub/M...
pdf.close() data = subprocess.check_output(['pdftotext', '-layout', '/tmp/sk.pdf', '-']) data = data.splitlines(True) pages = [] page = [] for line in data: if line.strip() and 'Page' not in line and 'CITIES' not in line and 'NORTHERN TOWNS, VILLAGES' not in li...
elif page: pages.append(page) page = [] districts = [] for page in pages: index = re.search(r'(\s{6,})', page[0]) if index: index = index.end() - 1 else: index = -1 dist1 = [] d...
LaurentClaessens/mazhe
src_yanntricks/yanntricksKScolorD.py
Python
gpl-3.0
526
0.045627
from yanntricks import * def KScolo
rD(): pspict,fig = SinglePicture("KScolorD") pspict.dilatation(1) x=var('x') C=Circle(Point(0,0),1) N1=C.graph(90,180) N2=C.graph(270,360) C.parameters.color="blue" N1.parameters.color="black" N2.parameters.color=N1.parameters.color N1.wave(0.1,0.2) #N2.wave(0.1,0.2) N=...
pspict.DrawGraphs(C,N1,N2,N,S) pspict.DrawDefaultAxes() fig.conclude() fig.write_the_file()
odoousers2014/LibrERP
l10n_it_sale/wizard/confirmation.py
Python
agpl-3.0
3,636
0.002475
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (c) 2013-2014 Didotech SRL (info at didotech.com) # All Rights Reserved. # # WARNING: This program as such is intended to be used by professional # programmers who take the who...
############################################################################ from openerp.osv import orm, fields import decimal_precision as dp import netsvc from tools import ustr class sale_order_confirm(orm.TransientModel): _inherit = "sale.order.confirm" _columns = { 'cig': fields.char('C
IG', size=64, help="Codice identificativo di gara"), 'cup': fields.char('CUP', size=64, help="Codice unico di Progetto") } # def default_get(self, cr, uid, fields, context=None): # sale_order_obj = self.pool['sale.order'] # if context is None: # context = {} # # ...
calebjordan/klayout-macros
pymacros/Make Layer Cells.py
Python
mit
2,057
0.017501
# $description: Split into layer cells # $autorun # $show-in-menu import pya import sys sys.stderr = sys.s
tdout class MenuAction(pya.Action): def __init__(self, title, shortcut, action): self.title = title self.shortcut = shortcut self.action = action def triggered(self): self.action() def make_layer_cells(): #Load Vie
w app = pya.Application.instance() mw = app.main_window() lv = mw.current_view() ly = lv.active_cellview().layout() dbu = ly.dbu if lv==None: raise Exception("No view selected") cv = lv.cellview(lv.active_cellview_index()) #Loop through layers for laye...
nucular/AutobahnPython
examples/twisted/websocket/echo_variants/client.py
Python
mit
2,386
0
############################################################################### # # The MIT License (MIT) # # Copyright (c) Tavendo GmbH # # 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 with...
.decode('utf8'))) reactor.callLater(1, self.sendHello) if __name__ == '__main__': if len(sys.argv) < 2: print("Need the WebSocket server address, i.e. ws://127.0.0.1:9000") sys.exit(1) if len(sys.argv) > 2 and sys.argv[2] == 'debug': log.startLogging(sys.stdout)
debug = True else: debug = False factory = WebSocketClientFactory(sys.argv[1], debug=debug, debugCodePaths=debug) factory.protocol = EchoClientProtocol connectWS(factory) reactor.run()
xapi-project/sm
tests/test_lvmlib.py
Python
lgpl-2.1
6,561
0
import unittest import mock import lvmlib class ExecResultMixIn(object): def assertExecutionSucceeded(self, exec_result): returncode, stdout, stderr = exec_result self.assertEquals(0, returncode) def assertExecutionFailed(self, exec_result): returncode, stdout, stderr = exec_result ...
lvsubsystem.add_volume_group('vg')
exec_result = lvsubsystem.fake_lvcreate( "someprog --something-stupid -n name n -L 100 vg".split(), '') self.assertExecutionFailed(exec_result) def test_fake_lvcreate_fails_if_no_volume_group_found(self): lvsubsystem = lvmlib.LVSubsystem(mock.Mock(), mock.Mock()) exec...
motasay/twitter-sentiment
src/evaluation.py
Python
gpl-3.0
1,524
0.003937
import logging from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import explained_variance_score from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_error from sklearn.metrics import r2_score import matplotlib.pyplo...
' % str(report)) cm = confusion_matrix(Y_true, Y_pred) logging.info('Confusion Matrix:\n%s' % str(cm)) # fig = plt.figure() # ax = fig.add_subplot(111) # cax = ax.matshow(cm) # fig.colorbar(cax) #
# ax.set_xticklabels(['']+['-1', '0', '1']) # ax.set_yticklabels(['']+['-1', '0', '1']) # # plt.title('Confusion Matrix') # plt.ylabel('True label') # plt.xlabel('Predicted label') # plt.show(block=False) else: var = explained_variance_score(Y_true, Y_pred) ...
Quantify-world/apification
src/apification/renderers.py
Python
mit
101
0.009901
import j
son class JSONRenderer(object): def render(self, data): return json.
dumps(data)
aawc/ProjectEuler
05/evenlyDivisible.py
Python
mit
1,404
0.026353
#!/bin/python import math def SumOfFactors(f_1, f_2): for key in f_2.keys(): if (key in f_1): f_1[key] += f_2[key] else: f_1[key] = f_2[key] return f_1; def PrimeFactorsOfNumber(n): sqrt_n = int(math.sqrt(n)) if (n == sqrt_n * sqrt_n): # Perfect square return SumOfFactors( P...
factors[n] = 1 return factors def EvenlyDivisible(largest): prime_factors = {}; for i in range (largest, 2, -1): prime_factors_i = PrimeFactorsOfNumber(i) print i, prime_factors_i for prime_factor in prime_factors_i.keys(): value = prime_factors_i[prime_factor] if prime_factor in prime_fa...
prime_factor] = value print prime_factor, value, prime_factors else: prime_factors[prime_factor] = value print prime_factor, value, prime_factors product = 1 for prime_factor in prime_factors: value = prime_factors[prime_factor] product *= math.pow(prime_factor, value) re...
youtube/cobalt
third_party/libvpx/tools/3D-Reconstruction/MotionEST/Exhaust.py
Python
bsd-3-clause
8,571
0.007584
## Copyright (c) 2020 The WebM project authors. All Rights Reserved. ## ## Use of this source code is governed by a BSD-style license ## that can be found in the LICENSE file in the root of the source ## tree. An additional intellectual property rights grant can be found ## in the file PATENTS. All contributing p...
stNeighborFeatureScore(MotionEST): """ Constructor: cur_f: current frame ref_f: reference frame blk_sz: block size wnd_size: search window size
beta: neigbor loss weight max_iter: maximum number of iterations metric: metric to compare the blocks distrotion """ def __init__(self, cur_f, ref_f, blk_size, wnd_size, beta=1, max_iter=100, ...
hanw/p4-hlir
p4_hlir/hlir/exclusive_conditions.py
Python
apache-2.0
8,296
0.006027
# Copyright 2013-present Barefoot Networks, 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 ...
pass if violated: cont
inue unknown_value = self._check_condition(unknown_cond, used_hdrs_valid) if unknown_value == Solver.DONT_KNOW: return None if result is None: result = unknown_value elif result != unknown_value: return None if result ...
restran/api-gateway-dashboard
dashboard/forms.py
Python
mit
3,021
0.002025
# !/usr/bin/env python # -*- coding: utf-8 -*- # created by restran on 2016/1/2 from __future__ import unicode_literals, absolute_import from django import forms from django.utils.translation import ugettext_lazy as _ from .models import * from common.forms import BaseModelForm logger = logging.getLogger(__name__) ...
en_ex >= refresh_token_ex: raise forms.ValidationError(_('refresh_token 的过期时间不能小于
access_token')) return refresh_token_ex ClientForm.base_fields.keyOrder = [ 'name', 'memo', 'url', 'enable', 'app_id', 'secret_key', 'login_auth_url', 'access_token_ex', 'refresh_token_ex', 'sms_login_auth_url', 'sms_change_password_url', 'change_password_url' ] # # class ClientEndpointFor...
tta/gnuradio-tta
gr-qtgui/python/__init__.py
Python
gpl-3.0
944
0.006356
# # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. #...
. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # The presence of this file turns th
is directory into a Python package from qtgui_swig import * import qtgui_swig as qtgui # to preserve the old interface