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
beardypig/streamlink
tests/test_streamlink_api.py
Python
bsd-2-clause
1,749
0
import os.path import unittest from unittest.mock import patch from streamlink import Streamlink from streaml
ink.api import streams PluginPath = os.path.join(os.path.dirname(__file__), "plugins") def get_session(): s = Streamlink() s.l
oad_plugins(PluginPath) return s class TestStreamlinkAPI(unittest.TestCase): @patch('streamlink.api.Streamlink', side_effect=get_session) def test_find_test_plugin(self, session): self.assertTrue( "rtmp" in streams("test.se") ) @patch('streamlink.api.Streamlink', side_effe...
rjpower/fastnet
fastnet/distributed/asgd.py
Python
gpl-3.0
4,309
0.01903
#!/usr/bin/env python '''A relatively simple distributed network implementation, using async SGD.''' from fastnet import net, layer, data, parser, weights from fastnet.util import
EZTimer from mpi4py import MPI import ctypes import cudaconv2 import numpy as np import os WORLD = MPI.COMM_WORLD cudaconv2.init(WORLD.Get_rank()) print 'CUDA', os.environ.get('MV2_USE_CUDA') MASTER = 0 WORKERS = range(1, WORLD.Get_size()) batch_size = 128 data_dir = '/ssd/nn-data/im
agenet/' data_provider = 'imagenet' checkpoint_dir = './checkpoint' param_file = 'config/imagenet.cfg' train_range = range(101, 1301) test_range = range(1, 101) data_provider = 'imagenet' #train_range = range(1, 41) #test_range = range(41, 49) train_dp = data.get_by_name(data_provider)(data_dir,train_range) test_dp ...
fardog/river
working/ntp-sync.py
Python
gpl-2.0
877
0
import math import numpy import pyaudio import time import ntplib def sine(frequency, length, rate): length = int(length * rate) factor = float(frequency) * (math.pi * 2) / rate return numpy.sin(numpy.arange(length) * factor) chunks = [] chunks.append(sine(440, 1, 44100)) chunk = numpy.concatena
te(chunks) * 0.25 p = pyaudio.PyAudio() stream = p.open(format=pyaudio.paFloat32, channels=1, rate=44100, output=1) last = 0 print("[ntp-sync] getting clock") c = ntplib.NTPClient() response = c.request('pool.ntp.org', version=3) print("[ntp-sync] clock offset %s" % response.offset) while True: curtime = int(mat...
stream.write(chunk.astype(numpy.float32).tostring()) stream.close() p.terminate()
mrphlip/lrrbot
alembic/versions/e966a3afd100_separate_patreon_user_table.py
Python
apache-2.0
4,230
0.027187
revision = 'e966a3afd100' down_revision = '954c3c4caf32' branch_labels = None depends_on = None import alembic import sqlalchemy import requests import pytz import dateutil.parser import datetime def upgrade(): patreon_users = alembic.op.create_table("patreon_users", sqlalchemy.Column("id", sqlalchemy.Integer, pri...
ta"]: for ob
j in data["included"]: if obj["id"] == pledge["id"] and obj["type"] == pledge["type"]: user["pledge_start"] = dateutil.parser.parse(obj["attributes"]["created_at"]) all_patreon_users.append(user) all_users.append((user_id, data["data"]["id"])) alembic.op.bulk_insert(patreon_users, all_patreon_users...
mmckerns/tutmom
check_env.py
Python
bsd-3-clause
3,306
0.007864
#!/usr/bin/env python # # Author: Mike McKerns (mmckerns @caltech and @uqfoundation) # Copyright (c) 2015-2016 California Institute of Technology. # Copyright (c) 2016-2019 Mike McKerns. # License: 3-clause BSD. """ check environment scipt """ import sys # requirements has = dict( # optimization scipy='0.6.0',...
#print("%s:: %s" % (prog, exc_info()[1])) return False # check required executables try: from pox import which #from subprocess import Popen, STDOUT, PIPE#, call exc
ept ImportError: sys.exit(returns) for module,executables in run.items(): if isinstance(executables, list): found = False for executable in executables: if executable_exist(module, executable): found = True break if not found: retur...
thegmarlow/TagTrack-
examples/oscilloscope.py
Python
mit
678
0.00885
import beaglebone_pru_adc as adc import time numsamples = 10000 # how many samples to capture capture = adc.Capture() capture.oscilloscope_init(adc.OFF_VALUES, numsamples) # captures AIN0 -
the first elt in AIN array #capture.oscilloscope_init(adc.OFF_VALUES+8, numsamples) # captures AIN2 - the third elt in AIN array capture.start() for _ in range(10): if capture.oscilloscope_is_complet
e(): break print '.' time.sleep(0.1) capture.stop() capture.wait() print 'Saving oscilloscope values to "data.csv"' with open('data.csv', 'w') as f: for x in capture.oscilloscope_data(numsamples): f.write(str(x) + '\n') print 'done' capture.close()
indictranstech/reciphergroup-erpnext
erpnext/setup/page/setup_wizard/setup_wizard.py
Python
agpl-3.0
17,443
0.030098
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe, json, copy from frappe.utils import cstr, flt, getdate from frappe import _ from frappe.utils.file_manager import save_file from frappe....
"Price List", "price_list_name": pl_name, "enabled": 1, "buying": 1 if pl_type == "Buying" else 0, "selling": 1 if pl_type == "Selling" else 0, "currency": args["currency"], "territories": [{ "territory": get_roo
t_of("Territory") }] }).insert() def set_defaults(args): # enable default currency frappe.db.set_value("Currency", args.get("currency"), "enabled", 1) global_defaults = frappe.get_doc("Global Defaults", "Global Defaults") global_defaults.update({ 'current_fiscal_year': args.curr_fiscal_year, 'default_cur...
smartdata-x/robots
api/HttpApi.py
Python
apache-2.0
1,065
0.021719
#!/usr/bin/python # -*- coding: utf-8 -*- #encoding=utf-8 ''' Created on 2015年4月21日 @author: kerry ''
' from base.http import MIGHttpMethodGet,MIGHttpMethodPost from base.miglog import miglog import urlparse import json class HttpApi(object): ''' classdocs ''' def __init__(self): ''' Constructor ''' @classmethod def RequestMethodGet(cls,url,port=None,header=None,...
None): parse =urlparse.urlparse(url) if(len(parse.query)==0): neturl = parse.path else: neturl = parse.path+"?"+parse.query http = MIGHttpMethodGet(neturl,parse.netloc) http.HttpMethodGet(header, cookies, port) return http.HttpGetContent()...
ziima/polint
setup.py
Python
gpl-3.0
269
0.003731
# -*- coding: utf-8 -*- from setuptools import setup # There is a problem wi
th unicode characters in setup.cfg under Python 3.5 and 3.6 # See https://github.com/pypa/
setuptools/issues/1062 # Try$ LC_ALL=C python3 setup.py --description setup(author='Vlastimil Zíma')
landscape-test/all-messages
messages/pep8/E261.py
Python
unlicense
64
0
""" E261 Incl
ude at least two spaces befor
e inline comment """
vinodkc/spark
python/pyspark/sql/tests/test_column.py
Python
apache-2.0
8,775
0.002284
# -*- encoding: utf-8 -*- # # 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 ...
ment, not a string or column", lambda: _to_java_column(1) ) class A: pass self.assertRaises(TypeError, lambda: _to_java_column(A())) self.assertRaises(TypeError, lambda: _to_java_column([])) self.assertRaisesRegex( TypeError, "Inv
alid argument, not a string or column", lambda: udf(lambda x: x)(None) ) self.assertRaises(TypeError, lambda: to_json(1)) def test_column_operators(self): ci = self.df.key cs = self.df.value ci == cs self.assertTrue(isinstance((-ci - 1 - 2) % 3 * 2.5 / 3.5, Column)) ...
shawncaojob/LC
PY/22_generate_parentheses.py
Python
gpl-3.0
3,269
0.007648
# 22. Generate Parentheses My Submissions QuestionEditorial Solution # Total Accepted: 90088 Total Submissions: 240551 Difficulty: Medium # Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. # # For example, given n = 3, a solution set is: # # "((()))", "(()())", "...
:rtype: List[s
tr] """ def dfs(line, n, nl, nr): if nl == nr and nl + nr == n * 2: res.append(line) return if nr < n and nr < nl: dfs(line + ")", n, nl, nr + 1) if nl < n: dfs(line + "(", n, nl + 1, nr) ...
azurestandard/django
django/contrib/sessions/tests.py
Python
bsd-3-clause
16,572
0.001026
from datetime import datetime, timedelta import shutil import string import tempfile import warnings from django.conf import settings from django.contrib.sessions.backends.db import SessionStore as DatabaseSession from django.contrib.sessions.backends.cache import SessionStore as CacheSession from django.contrib.sessi...
ssion['some key'] = 'exists' # Need to reset these to pretend we haven't accessed it: self.accessed = False self.modified = False self.assertEqual(self.session.pop('some key'), 'exists') self.assertTrue(self.session.accessed) self.assertTrue(self.session.modified) ...
'does not exist') self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) def test_setdefault(self): self.assertEqual(self.session.setdefault('foo', 'bar'), 'bar') self.assertEqual(self.session.setdefault('foo', 'baz'), 'bar') self.assertTrue(self...
geary/claslite
web/app/lib/elementtree/HTMLTreeBuilder.py
Python
unlicense
7,826
0.001278
# # ElementTree # $Id: HTMLTreeBuilder.py 3265 2007-09-06 20:42:00Z fredrik $ # # a simple tree builder, for HTML input # # history: # 2002-04-06 fl created # 2002-04-07 fl ignore IMG and HR end tags # 2002-04-07 fl added support for 1.5.2 and later # 2003-04-13 fl added HTMLTreeBuilder alias # 2004-12-02 fl ...
If omitted, # the parser looks for META tags inside the document. If no tags # are found, the parser defaults to ISO-885
9-1. Note that if your # document uses a non-ASCII compatible encoding, you must decode # the document before parsing. # # @see elementtree.ElementTree class HTMLTreeBuilder(HTMLParser): # FIXME: shouldn't this class be named Parser, not Builder? def __init__(self, builder=None, encoding=None): ...
gencer/python-phonenumbers
python/phonenumbers/shortdata/region_IS.py
Python
apache-2.0
1,126
0.007993
"""Auto-generated file, do not edit by hand. IS metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_IS = PhoneMetadata(id='IS', country_code=None, international_prefix=None, general_desc=PhoneNumberDesc(national_number_pattern='1\\d{2,5}', possible_length=(3, 4, 6)),...
ossible_length=(4,)), emergency=PhoneNumberDesc(national_number_pattern='112', example_number='112', possible_length=(3,)), short_code=PhoneNumberDesc(national_number_pattern='1(?:1(?:[28]|6(?:1(?:23|16)))|4(?:00|1[145]|4[0146])|55|7(?:00|17|7[07-9])|8(?:0[08
]|1[016-9]|20|48|8[018])|900)', example_number='112', possible_length=(3, 4, 6)), carrier_specific=PhoneNumberDesc(national_number_pattern='1441', example_number='1441', possible_length=(4,)), sms_services=PhoneNumberDesc(national_number_pattern='1(?:415|848|900)', example_number='1415', possible_length=(4,)), ...
protomouse/Flexget
flexget/validator.py
Python
mit
18,604
0.002634
from __future__ import unicode_literals, division, absolute_import, print_function import re from flexget.config_schema import process_config # TODO: rename all validator.valid -> validator.accepts / accepted / accept ? class Errors(object): """Create and hold validator error messages.""" def __init__(self...
if self.name == 'root': return self root = factory('root') root.accept(self) return root def add_parent(self, parent): self.parent = parent return pa
rent def get_validator(self, value, **kwargs): """Returns a child validator of this one. :param value: Can be a validator type string, an already created Validator instance, or a function that returns a validator instance. :param kwargs: Keyword arguments are ...
0--key/lib
portfolio/Python/scrapy/naturebest/naturesbest.py
Python
apache-2.0
2,587
0.003479
import re import os from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from scrapy.http import Request, HtmlResponse from scrapy.utils.response import get_base_url from scrapy.utils.url import urljoin_rfc from urllib import urlencode import hashlib import csv from product_spiders.item...
v/a/@href').extract() for prod_url in prod_urls: url = urljoin_rfc(get_base_url(response), prod_url) yield Request(url) # products for product in self.parse_product(response): yield product def parse_product(self, response): if not is...
if name: url = response.url url = urljoin_rfc(get_base_url(response), url) skus = hxs.select('//td[@class="skuname"]/text()').extract() prices = hxs.select('//td[@class="price"]/text()').extract() skus_prices = zip(skus, prices) for sku, price i...
ChopChopKodi/pelisalacarta
python/version-plex/core/config.py
Python
gpl-3.0
2,224
0.026529
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Configuracion # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ import os,io from types import * PLATFORM_NAME = "plex" def get_pla...
return "" def get_temp_file(filename): return "" def get_runtime_path(): return os.path.abspath( os.path.join( os.path.dirname(__file__) , ".." ) ) def get_data_path():
return os.getcwd() def get_cookie_data(): import os ficherocookies = os.path.join( get_data_path(), 'cookies.lwp' ) cookiedatafile = open(ficherocookies,'r') cookiedata = cookiedatafile.read() cookiedatafile.close(); return cookiedata def verify_directories_created(): return
seismology/mc_kernel
UTILS/repack_database.py
Python
gpl-3.0
9,908
0.001312
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Repacking Instaseis databases. Requires click, h5py, and numpy. :copyright: Lion Krischer (krischer@geophysik.uni-muenchen.de), 2016 Simon Stähler (staehler@geophysik.uni-muenchen.de), 2016 :license: GNU Lesser General Public License, Version 3 [non-comme...
: f_out.createVariable(name, variable.datatype, variab
le.dimensions) f_out.variables[name][:] = f_in_1['Snapshots'].variables[name][:] # Create a new array but this time in 5D. The first dimension # is the element number, the second and third are the GLL # points in both directions, the fourth is the time axis, and the # la...
PillowLounge/lolibot
hardcoded/statistics.py
Python
gpl-3.0
3,782
0.007147
# log moments (mean, variance, skewness, kurtosis) and quantiles # why am I spending time creating a complex quantile and histogram # estimator when I only need average, so far from math import sqrt from bisect import bisect_left import scipy.stats as st maxlong = 9223372036854775807 class RunningStat(object): '...
) def __iter__(self): return self def __next__(self): r = self.inner.__next__() for a in self.actions: r = a(r) self.count += 1 return r def __len__(self): return self.generator.__len__()
- self.count z_score = st.norm.ppf((1+.95)/2) z_sqr = z_score*z_score def wilson_score(positive, n): '''returns lower bound of Wilson score confidence interval for a Bernoulli parameter resource: http://www.evanmiller.org/how-not-to-sort-by-average-rating.html''' assert positive <= n if n is 0: ...
sebalander/trilateration
trilatera.py
Python
gpl-2.0
11,639
0.007991
''' practicar trilateracion ''' # %% import numpy as np import numpy.linalg as ln import matplotlib.pyplot as plt import numdifftools as ndf from scipy.special import chdtri # %% kml_file = "/home/sebalander/Code/VisionUNQextra/trilateration/trilat.kml" # %% texto = open(kml_file, 'r').read() names = list() data...
, 16.797] Db[6, 7] = [20.794, 20.786, 20.788] Db -= 0.055 # le resto 5.5cm porque medimos desde la bas en lugar de l centro indAux = np.arange(len(Db)) Db[indAux, indAux] = 0.0 dg = np.zeros(Db.shape[:2], dtype=float) dg[0, 1] = 8.27 dg[0, 2] = 6.85 dg[0, 3] = 13.01 dg[0, 4] = 18.5 dg[0, 5] = 24.79 dg[0, 6] = 25....
0.89 dg[2, 4] = 14.53 dg[2, 5] = 22.55 dg[2, 6] = 20.22 dg[2, 7] = 38.43 dg[3, 4] = 6.37 dg[3, 5] = 11.97 dg[3, 6] = 13.30 dg[3, 7] = 28.26 dg[4, 5] = 9.17 dg[4, 6] = 6.93 dg[4, 7] = 24.05 dg[5, 6] = 10.40 dg[5, 7] = 16.41 dg[6, 7] = 20.49 # las hago simetricas para olvidarme el tema de los indices triuInd = np.t...
GHubgenius/PeachOrchard
node/src/core/monitor.py
Python
mit
1,446
0.003458
from src.core.log import * from src.core import node_resource as nr from src.core import config from src.core import utility from time import sleep import os def monitor(fuzzy): """ """ # known crashes; key is idx (top level folder before crash info); value is known_crashes = {} try:
utility.msg("Initializing monitor for node %s..." % config.NODE_ID) # check monitor dir if not os.path.isdir(config.MONITOR_DIR):
utility.msg("Directory %s not found" % config.MONITOR_DIR, ERROR) return # # prior to monitor loop, lets ensure we're synced with upstream by providing # current set of crashes; dupes will be thrown out # # register crashes current_crashes = fu...
musashiXXX/django-clamav-upload
clamav_upload/exceptions.py
Python
gpl-3.0
363
0
from django.contrib import messages from
django.core.exceptions import PermissionDenied class UploadPermissionDenied(PermissionDenied): def __init__(self, request, log_func, error_message, *args, **kwargs): log_func(error_message) messages.error(request, error_message) super(UploadPermissionDenied, self).__init__(*ar
gs, **kwargs)
GreatLakesEnergy/sesh-dash-beta
seshdash/tests/test_import.py
Python
mit
4,199
0.010002
# Testing from django.test import TestCase from django.test.utils import override_settings # APP Models from seshdash.models import Sesh_User, Sesh_Alert, Alert_Rule, Sesh_Site,VRM_Account, BoM_Data_Point as Data_Point, Daily_Data_Point as ddp # django Time related from seshdash.utils import time_utils from django.ut...
comission_date=self.start_date, location_city=u"kigali", location_country=u"rwanda", vrm_account = self.VRM, installed_kw=12...
number_of_panels=12, vrm_site_id=self.vrm_site_id, battery_bank_capacity=12321, has_genset=True, ha...
horizon-institute/chariot
src/app/deployments/migrations/0002_auto_20170419_1040.py
Python
mit
2,022
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-04-19 10:40 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('deployments', '0001_initial'), ] operations = [ migrations.AddField( ...
name='boiler_manufacturer', field=models.CharField(blank=True, max_length=255, null=True), ), migrations.AddField(
model_name='deployment', name='boiler_model', field=models.CharField(blank=True, max_length=255, null=True), ), migrations.AddField( model_name='deployment', name='boiler_output', field=models.FloatField(blank=True, null=True), ...
bgaultier/laboitepro
boites/migrations/0008_auto_20170801_1406.py
Python
agpl-3.0
568
0.001761
# -*- coding:
utf-8 -*- # Generated by Django 1.11.2 on 2017-08-01 12:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('boites', '0007_auto_20170801_0645'), ] operations = [ migrations.AlterField( model_name='tile', name='dura...
d'affichage de la tuile"), ), ]
mkelley/brew
brew/ingredients.py
Python
mit
25,766
0.000388
# Licensed under an MIT style license - see LICENSE """ ingredients --- Beer ingredients ================================ """ from enum import Enum from collections.abc import MutableSequence from . import timing as T __all__ = [ 'PPG', 'CultureBank', 'Culture', 'Ingredient', 'Fermentable',
'Unfermentable', 'Hop', 'Spice', 'Fruit', 'Grain', 'Sugar', 'Wort', 'Other', 'Priming', 'Water', 'WaterTreatment', 'Ingredients', ] # Source: Home Brewer's Companion # Beersmith: http://www.beersmith.com/Grains/Grains/GrainList.htm # name, PPG class PPG(Enum): AcidMal...
erican 6-row", 35 AmericanPaleAle = "American pale ale", 36 BelgianPaleAle = "Belgian pale ale", 37 BelgianPilsener = "Belgian pilsener", 37 DriedMaltExtract = "Dried malt extract", 44 EnglishTwoRow = "English 2-row", 38 EnglishMild = "English mild", 37 MarisOtter = "Maris Otter", 38 Gol...
popazerty/beyonwiz-4.1
lib/python/Plugins/SystemPlugins/IceTV/API.py
Python
gpl-2.0
8,110
0.002219
# kate: replace-tabs on; indent-width 4; remove-trailing-spaces all; show-tabs on; newline-at-eof on; # -*- coding:utf-8 -*- ''' Copyright (C) 2014 Peter Urbanec All Right Reserved License: Proprietary / Commercial - contact enigma.licensing (at) urbanec.net ''' import requests import json from fcntl import ioctl fr...
} if region: self.data["member"]["region_id"] = region def post(self): return self.send("post") def put(self): return self.send("put") def send(self, method): r = super(Login, self).send(method) result = r.json() config.plugins.icetv.member.ema...
s"] config.plugins.icetv.member.token.value = result["member"]["token"] config.plugins.icetv.member.id.value = result["member"]["id"] config.plugins.icetv.member.region_id.value = result["member"]["region_id"] config.plugins.icetv.device.id.value = result["device"]["id"] config.p...
skg-net/ansible
lib/ansible/modules/cloud/azure/azure_rm_autoscale.py
Python
gpl-3.0
26,843
0.003502
#!/usr/bin/python # # Copyright (c) 2017 Yuwei Zhou, <yuwzho@microsoft.com> # # 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', ...
ns: name: required: true description: the name of the profile. count: required: true description: - The number of insta
nces that will be set if metrics are not available for evaluation. - The default is only used if the current instance count is lower than the default. min_count: description: the minimum number of instances for the resource. max_count: description:...
bhatiaharsh/naturalHHD
pynhhd-v1.1/pynhhd/structured.py
Python
bsd-2-clause
6,676
0.007939
''' Copyright (c) 2015, Harsh Bhatia (bhatia4@llnl.gov) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions a...
bug('Computing rotated gradient') mtimer = Timer() ddy, ddx =
np.gradient(sfield, self.dx[0], self.dx[1]) ddy *= -1.0 grad = np.stack((ddy, ddx), axis=-1) mtimer.end() LOGGER.debug('Computing rotated gradient done! took {}'.format(mtimer)) return grad def gradient(self, sfield, verbose=False): if (sfield.shape != self.dims)...
sdispater/orator
tests/integrations/test_mysql.py
Python
mit
764
0
# -*- coding: utf-8 -*- import os from .. import OratorTestCase from . import IntegrationTestCase class MySQLIntegrationTestCase(Integrati
onTestCase, OratorTestCase): @classmethod def get_manager_config(cls): ci = os.environ.get("CI", False) if ci: database = "orator_test" user = "root" password = "" else: database = "orator_test" user = "orator" pass...
"user": user, "password": password, }, } def get_marker(self): return "%s"
christianurich/VIBe2UrbanSim
3rdparty/opus/src/opus_gui/util/editorbase.py
Python
gpl-2.0
3,269
0.008259
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE # PyQt4 includes for python bindings to QT from PyQt4.QtCore import Qt, QString from PyQt4.QtGui import QFont, QFontMetrics, QColor, QIcon, QLabel, QWidget, QVBoxLayout from PyQt4.Qsci import QsciScin...
margin 0 is for line numbers self.setMarginWidth(0, fm.width( "00000" ) + 5) self.setMarginLineNumbers(0, True) ## Edge Mode shows a red vetical bar at 80 chars self.setEdgeMode(QsciScintilla.EdgeLine) self.setEdgeColumn(80) self.setEdgeColor(QColor("#CCCCCC")) ...
elf.setBraceMatching(QsciScintilla.SloppyBraceMatch) ## Editing line color #self.setCaretLineVisible(True) #self.setCaretLineBackgroundColor(QColor("#CDA869")) ## Margins colors # line numbers margin self.setMarginsBackgroundColor(QColor("#333333")) self.setMarg...
simonmonk/electronics_cookbook
pi/ch_13_bi_stepper.py
Python
mit
1,655
0.014502
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) in_1_pin = 18 in_2_pin = 23 in_3_pin = 24 in_4_pin = 25 en_pin = 22 GPIO.setup(in_1_pin, GPIO.OUT) GPIO.setup(in_2_pin, GPIO.OUT) GPIO.setup(in_3_pin, GPIO.OUT) GPIO.setup(in_4_pin, GPIO.OUT) GPIO.setup(en_pin, GPIO.OUT) GPIO.output(en_pin, True) period ...
int('f100 - forward 100 steps'); print('
r100 - reverse 100 steps'); while True: command = input('Enter command: ') parameter_str = command[1:] # from char 1 to end parameter = int(parameter_str) if command[0] == 'p': period = parameter / 1000.0 elif command[0] == 'f': step_fo...
bfvanrooyen/vcontrol
cli_commands/command_base.py
Python
mit
228
0.008772
from a
bc import ABCMeta, abstractmethod class BaseCommand(metaclass=ABCMeta): @abstractmethod def parse_arguments(self, subparsers): return @abstractmethod def handle_command
(self, args): return
galtys/galtys-addons
account_move_line_where_query/__init__.py
Python
agpl-3.0
19
0
imp
ort where_quer
y
lixun910/pysal
pysal/model/mgwr/utils.py
Python
bsd-3-clause
6,190
0.006139
import numpy as np from pysal.lib.common import requires @requires('matplotlib') def shift_colormap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'): ''' Function to offset the "center" of a colormap. Useful for data with a negative min and positive max and you want the middle of the colormap...
MGWR surfaces. Parameters ---------- data : pandas or geopandas Dataframe gwr/mgwr results var1 : string name of gwr parameter estimate column in frame var2 : string name of mgwr parameter estimate column in frame gwr_t : string name of...
: float bandwidth for gwr model for var1 mgwr_t : string name of mgwr t-values column in frame associated with var2 mgwr_bw: float bandwidth for mgwr model for var2 name : string common variable name to use for title kwargs1: additional...
tpow/pytds
tests/sspi_test.py
Python
mit
3,151
0.008569
try: import unittest2 as unittest except: import unittest import ctypes from ctypes import create_string_buffer import settings import socket import sys @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows") class SspiTest(unittest.TestCase): def test_enum_security_packages(self): ...
Type, bufs[0][0]) self.assertEqual(desc.pBuffers[0].pvBuf
fer, ctypes.cast(bufs[0][1], pytds.sspi.PVOID).value) def test_sec_context(self): import pytds.sspi cred = pytds.sspi.SspiCredentials( 'Negotiate', pytds.sspi.SECPKG_CRED_OUTBOUND) token_buf = create_string_buffer(10000) bufs = [(pytds.sspi.SECBUFFER_TOKEN, ...
sthirugn/robottelo
tests/foreman/ui/test_discoveredhost.py
Python
gpl-3.0
51,849
0.000019
# -*- encoding: utf-8 -*- """Test class for Foreman Discovery @Requirement: Discoveredhost @CaseAutomation: Automated @CaseLevel: Acceptance @CaseComponent: UI @TestType: Functional @CaseImportance: High @Upstream: No """ import subprocess import time from fauxfactory import gen_string from nailgun import entit...
tab_locators['settings.tab_discovered'] param_name = 'discovery_fact_column
' edit_param( session=session, tab_locator=tab_locator, param_name=param_name, value_type='input', param_value=param_value, ) saved_element = self.settings.get_saved_value( tab_locator, param_name) self.assertEqual(p...
mrquim/mrquimrepo
repo/plugin.video.salts/scrapers/rlsmovies_scraper.py
Python
gpl-2.0
4,302
0.003952
""" SALTS XBMC Addon Copyright (C) 2014 tknorris 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. T...
0" visible="eq(-4,true)"/>' % (name, i18n('auto_select'))) return settings def search(self, video_type, title, year, season=''): # @UnusedVariable html = self._http_get(self.base_url, params={'s': title}, require_debrid=False, cache_limit=1) post_pattern = 'class="post-box-title">.*?href="...
_results(html, post_pattern, date_format, video_type, title, year)
ingadhoc/website
website_sale_order_type_ux/models/__init__.py
Python
agpl-3.0
303
0
########################################################################
###### # For copyright and license notices, see __manifest__.py file in module root # directory #######################################################
####################### from . import website from . import res_config_settings
LumPenPacK/NetworkExtractionFromImages
win_build/nefi2_win_amd64_msvc_2015/site-packages/networkx/algorithms/tests/test_simple_paths.py
Python
bsd-2-clause
9,703
0.012883
#!/usr/bin/env python import random from nose.tools import * import networkx as nx from networkx import convert_node_labels_to_integers as cnlti from networkx.algorithms.simple_paths import _bidirectional_shortest_path from networkx.algorithms.simple_paths import _bidirectional_dijkstra # Tests for all_simple_paths d...
ected_cycle, 0, 3,
ignore_edges=[(2, 1)]) assert_equal(path, [0, 1, 2, 3]) assert_raises( nx.NetworkXNoPath, _bidirectional_shortest_path, directed_cycle, 0, 3, ignore_edges=[(1, 2)], ) def validate_path(G, s, t, soln_len, path): assert_equal(pa...
drewkett/SU2
SU2_PY/SU2/io/config_options.py
Python
lgpl-2.1
6,581
0.009877
## \file config_options.py # \brief python package for config # \author T. Lukaczyk, F. Palacios # \version 6.1.0 "Falcon" # # The current SU2 release has been coordinated by the # SU2 International Developers Society <www.su2devsociety.org> # with selected contributions from the open-source community. # # The ma...
G']) self.PARAM. append(new_dv['PARAM']) def extend(self,new_dvs): assert isinstance(new_dvs,DEFINITION_DV) , 'input must be of type DEFINITION_DV' self.KIND. extend(new_dvs['KIND'])
self.SCALE. extend(new_dvs['SCALE']) self.MARKER.extend(new_dvs['MARKER']) self.FFDTAG.extend(new_dvs['FFDTAG']) self.PARAM. extend(new_dvs['PARAM']) #: class DEFINITION_DV class DV_KIND(ordered_bunch): """ SU2.io.config.DV_KIND() List of design variables (Design variabl...
opendatadurban/citizen_sensors
Weather_Station/test_wind_dir.py
Python
apache-2.0
2,418
0.031844
# Simple example of reading the MCP3008 analog input channels and printing import time import sys import numpy as np # Import SPI library (for hardware SPI) and MCP3008 library. import Adafruit_GPIO.SPI as SPI import Adafruit_MCP3008 import RPi.GPIO as GPIO import spidev # Software SPI configuration: #CLK = 18 #MIS...
43] sortd = np.sort(d) #print sortd midp = (sortd[1:]+sortd[:-1])/2 midp = np.insert(midp,0,0) midp = np.insert(midp,len(midp),5.0) print midp #for i in range(0,len(sortd)): # print directions.get(sortd[i])
# Main program loop. try: while True: GPIO.output(ledPin,0) time.sleep(samplingTime*10.0**-6) # The read_adc function will get the value of the specified channel voMeasured = mcp.read_adc(an_chan) time.sleep(deltaTime*10.0**-6) GPIO.output(ledPin,1) time.slee...
umars/npyscreen
npyscreen/fmPopup.py
Python
bsd-2-clause
1,031
0.025218
#!/usr/bin/python # encoding: utf-8 from . import fmForm from . import fmActionFormV2 import curses class Popup(fmForm.Form): DEFAULT_LINES = 12 DEFAULT_COLUMNS = 60 SHOW_ATX = 10 SHOW_ATY = 2 class ActionPopup(fmActionFormV2.ActionFormV2): DEFAULT_LINES ...
self.add(multiline.Pager, scroll_exit=True, max_height=self.widget_useable_space()[0]-2) class PopupWide(Popup): DEFAULT_LINES = 14 DEFAULT_COLUMNS = None SHOW_ATX = 0 SHOW_ATY = 0 class ActionPopupWide(fmActionFormV2.ActionFormV2): DEFAULT_LINES = ...
= 0 SHOW_ATY = 0
ecreall/nova-ideo
novaideo/views/novaideo_view_manager/widget.py
Python
agpl-3.0
776
0.002577
# Copyright (c) 2014 by Ecreall under licence
AGPL terms # available on http://www.gnu.org/licenses/agpl.html # licence: AGPL # author: Amen Souissi import deform from deform.widget import default_resource_registry class SearchFormWidget(deform.widget.FormWidget): template = 'novaideo:views/novaideo_view_manager/templates/search_form.pt' class SearchTex...
ch', None),) default_resource_registry.set_js_resources( 'live_search', None, 'novaideo:static/js/live_search.js') default_resource_registry.set_css_resources( 'live_search', None, 'pontus:static/select2/dist/css/select2.min.css')
team-xue/xue
xue/cms/plugins/picture/migrations/0007_publisher2.py
Python
bsd-3-clause
10,053
0.006963
from south.db import db from django.db import models from cms.plugins.picture.models import * class Migration: def forwards(self, orm): # Deleting field 'Picture.public' db.delete_column('cmsplugin_picture', 'public_id') # Deleting model 'picturepublic' db.de...
Field', [], {'db_index': 'True'}), 'lft': ('models.PositiveIntegerField', [], {'db_index': 'True'}), 'login_required': ('models.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'moderator_state': ('models.SmallIntegerField', [], {'default': '1', 'blank': 'True'}), ...
', [], {'related_name': "'children'", 'blank': 'True', 'null': 'True', 'to': "orm['cms.Page']"}), 'publication_date': ('models.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}), 'publication_end_date': ('models.DateTimeField', [], {'db_index': 'True', 'null': 'True', 'bl...
codeforboston/cornerwise
server/cornerwise/__init__.py
Python
mit
65
0
from .celery i
mport app as celery_app __
all__ = ["celery_app"]
CoherentLabs/depot_tools
tests/owners_finder_test.py
Python
bsd-3-clause
9,645
0.004769
#!/usr/bin/env vpython3 # Copyright 2013 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 owners_finder.py.""" import os import sys import unittest if sys.version_info.major == 2: import mock else: f...
{'content/bar/foo.cc'}) def test_skip_files_owned_by_author(self): files = [ 'chrome/browser/defaults.h', # owned by brett 'content/bar/foo.cc', # not owned by brett ]
finder = self.ownersFinder(files, author=brett) self.assertEqual(finder.unreviewed_files, {'content/bar/foo.cc'}) def test_native_path_sep(self): # Create a path with backslashes on Windows to make sure these are handled. # This test is a harmless duplicate on other platforms. native_slashes_pat...
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-3.0/Lib/test/test_subprocess.py
Python
mit
31,033
0.001901
import unittest from test import support import subprocess import sys import signal import os import tempfile import time import re mswindows = (sys.platform == "win32") # # Depends on the following external programs: Python # if mswindows: SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), ' ...
utable, "-c", 'import sys; sys.exit(sys.stdin.read() == "pear")'], stdin=tf) p.wait() self.assertEqual(p.returncode, 1) def test_stdout_pipe(self): # stdout redirection p = subprocess.Popen([sys.executable, "-c", ...
dout_filedes(self): # stdout is set to open file descriptor tf = tempfile.TemporaryFile() d = tf.fileno() p = subprocess.Popen([sys.executable, "-c", 'import sys; sys.stdout.write("orange")'], stdout=d) p.wait() os.lseek(...
bit-trade-one/SoundModuleAP
lib-src/lv2/sratom/waflib/Scripting.py
Python
gpl-2.0
10,970
0.056427
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file import os,shlex,shutil,traceback,errno,sys,stat from waflib import Utils,Configure,Logs,Options,ConfigSet,Context,Errors,Build,Node build_dir_override=None no_climb_com...
try: os.unlink(fname) except OSError: Logs.warn('Could not remove %r'%fname) for x in[Context.DBFILE,'config.log']: try: os.unlink(x) except O
SError: pass try: shutil.rmtree('c4che') except OSError: pass def distclean(ctx): '''removes the build directory''' lst=os.listdir('.') for f in lst: if f==Options.lockfile: try: proj=ConfigSet.ConfigSet(f) except IOError: Logs.warn('Could not read %r'%f) continue if p...
google/grr
grr/server/grr_response_server/databases/mysql_time_test.py
Python
apache-2.0
411
0.004866
#!/usr/bin/env python from absl import app from absl.testing import absltest from grr_response_server.databases import db_time_test from grr_response_server.databases import mysql_test from grr.test_lib import test_lib class MysqlClientsTest(db_time_test.DatabaseTimeTestMixi
n,
mysql_test.MysqlTestBase, absltest.TestCase): pass if __name__ == "__main__": app.run(test_lib.main)
davek44/Basset
src/basset_sample.py
Python
mit
2,818
0.011001
#!/usr/bin/env python from optparse import OptionParser import gzip import random import sys ################################################################################ # basset_sample.py # # Sample sequences from an existing dataset of sequences as BED file and # activity table. #################################...
####################################################### def main(): usage = 'usage: %prog [options] <db_bed> <db_act_file> <sample_seqs> <output_prefix>' parser = OptionParser(usage) parser.add_option('-s', dest='seed', default=1, type='float', help='Random number generator seed [Default: %default]') (o...
abase BED and activity table and output prefix') else: bed_file = args[0] act_file = args[1] sample_seqs = int(args[2]) out_pre = args[3] random.seed(options.seed) ############################################################ # process BED ###########################...
tinutomson/wikicoding
wiki/plugins/macros/wiki_plugin.py
Python
gpl-3.0
905
0.007735
from __future__ import absolute_import from __future__ import unicode_literals # -*- coding: utf-8 -*- from django.utils.translation import ugettext as _ from wiki.core.plugins import registry from wiki.core.plugins.base import BasePlugin from wiki.plugins.macros import settings from wiki.plugins.macros.mdx.macro imp...
dline': _('Macros'),
'icon_class': 'fa-play', 'template': 'wiki/plugins/macros/sidebar.html', 'form_class': None, 'get_form_kwargs': (lambda a: {})} markdown_extensions = [MacroExtension(), WikiTocExtension()] def __init__(self): pass registry.regist...
sortsimilar/Citation-Tree
markstress.py
Python
apache-2.0
1,287
0.020202
### This program intends to combine same GSHF in citation tree, and sort them according to the first letter of title; ### Author: Ye Gao ### Date: 2017-11-7 import csv file = open('NodeCheckList.csv', 'rb') reader = csv.reader(file) NodeCheckList = list(reader) file.close() #print NodeCheckList FirstRow = NodeChec...
ent in NodeCheckList: if element[2] != "": element[2] = int(element[2]) SortYear = sorted(NodeCheckList, key=lambda l:l[3], reverse=True) SortCiteTimes = sorted(NodeCheckList, key=lambda l:l[2], reverse=True) print SortYear NodeStressList = [] for element in NodeCheckList: if (int(element[7]) == 0) or (int(elem...
se=False) SortTitle = [FirstRow] + SortTitle title = "" CombineTitle = [] for element in SortTitle: if element[4] != title: CombineTitle.append(element) else: CombineTitle[-1][1] += '|' + element[1] title = element[4] # save result list to NodeStressList.csv; file = open('NodeStressList.csv','wb') for i in ...
r-o-b-b-i-e/pootle
pootle/apps/pootle_fs/resources.py
Python
gpl-3.0
5,525
0
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from fnmatch import fnmatch from django.db....
@cached_property def found_file_paths(self): return [x[1] for x in self.found_file_matches] @cached_property def resources(self): """Uncached Project resources provided by FSPlugin""" return self.context.resources @cached_property def store_filter(self): """Filter...
ootle_path) @cached_property def storefs_filter(self): """Filter StoreFS querysets using file globs""" return StoreFSPathFilter( pootle_path=self.pootle_path, fs_path=self.fs_path) @cached_property def synced(self): """Returns tracked StoreFSs that have ...
quattor/aquilon
lib/aquilon/worker/commands/add_rack_bunker.py
Python
apache-2.0
1,006
0
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2018 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obt...
ed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either expr
ess or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains the logic for `aq add rack --bunker`.""" from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611 from aquilon.worker.commands.add_rack import CommandAddRack class Comman...
manuelm/pyload
module/ConfigParser.py
Python
gpl-3.0
11,895
0.004456
# -*- coding: utf-8 -*- from __future__ import with_statement from time import sleep from os.path import exists, join from shutil import copy from traceback import print_exc from utils import chmod # ignore these plugin configs, mainly because plugins were wiped out IGNORE = ( "FreakshareNet", "SpeedManager", "A...
ction][option] = {"desc": desc, "type": typ, "value": value} else: content, none, value = line.partition("=") content, none, desc = content.par...
place('"', "").strip() typ, none, option = content.strip().rpartition(" ") value = value.strip() if value.startswith("["): if value.endswith("]"): listmode = False ...
plotly/python-api
packages/python/plotly/plotly/validators/layout/_shapes.py
Python
mit
8,858
0
import _plotly_utils.basevalidators class ShapesValidator(_plotly_utils.basevalidators.CompoundArrayValidator): def __init__(self, plotly_name="shapes", parent_name="layout", **kwargs): super(ShapesValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, ...
,`y1`), (`x0`,`y0`) with respect to the axes' sizing mode. If "path", draw a custom SVG path using `path`. with respect to the axes' sizing mode. visible Determines whether or not this shape is visible. x0 ...
the shape's end x position. See `type` and `xsizemode` for more info. xanchor Only relevant in conjunction with `xsizemode` set to "pixel". Specifies the anchor point on the x axis to which `x0`, `x1` and x coordinates within `p...
intip/da-apps
plugins/da_centrallogin/modules/soappy/tests/speedTest.py
Python
gpl-2.0
2,976
0.005712
#!/usr/bin/env python ident = '$Id: speedTest.
py,v 1.4 2003/05/21 14:52:37 warnes Exp $' import time import sys sys.path.insert(1, "..") x='''<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://sche
mas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:xsd="http://www.w3.org/1999/XMLSchema"> <SOAP-ENV:Body> <ns1:getRate xmlns:ns1="urn:demo1:exchange" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <country1 xsi:type="...
robmadole/briefs-caster
src/briefscaster/__init__.py
Python
bsd-3-clause
1,980
0.001515
import sys import os from os.path import dirname, join from flask import Flask, request, abort app = Flask(__name__) config = { 'working_directory': os.getcwd(), 'always_regenerate': True} @app.route('/') def provide_briefcast(): from briefscaster import briefcast url_root = request.url_root ...
), mimetype='application/brief') def main(): try: config['working_directory'] = sys.argv[1] except IndexError: pass print 'briefs-caster - Serving up some fine briefs for you\n' print 'Open http://<IP_ADDRESS>:5000 from the Briefs app\n' print 'CTRL-C to exit the server' app....
utilities """ local_bs = join(dirname(__file__), 'bin', 'bc-bs') local_compact_briefs = join(dirname(__file__), 'bin', 'bc-compact-briefs') if os.access(local_bs, os.X_OK) and \ os.access(local_compact_briefs, os.X_OK): # The local versions are executable, we will use those retur...
NERC-CEH/jules-jasmin
majic/joj/controllers/loggedin.py
Python
gpl-2.0
304
0.023026
import logging from joj.lib.base import * from pa
ste.request import parse_querystring import urllib2 log = logging.getLogger(__name__) class L
oggedinController(BaseController): def index(self): #self closes window return '<html><head></head><body onload="window.close()"></body></html>'
hiliev/py-zfs-rescue
zfs/lzjb.py
Python
bsd-3-clause
5,428
0.002579
# # An attempt at re-implementing LZJB compression in native Python. # # Created in May 2014 by Emil Brink <emil@obsession.se>. See LICENSE. # # ---------------------------------------------------------
------------ # # Copyright (c) 2014-2016, Emil Brink # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided
# that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and # the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions # and the following disclaimer in the do...
wangjun/pythoner.net
pythoner/books/spider.py
Python
gpl-3.0
6,613
0.012414
#encoding=utf-8 """ pythoner.net Copyright (C) 2013 PYTHONER.ORG This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Th...
. If not, see <http://www.gnu.org/licenses/>. """ import random import time,math,os,re,urllib,urllib2,cookielib from BeautifulSoup import BeautifulSoup import time import socket import os import db from string import join from PIL
import Image import os class BrowserBase(object): ERROR = { '0':'Can not open the url,checck you net', '1':'Creat download dir error', '2':'The image links is empty', '3':'Download faild', '4':'Build soup error,the html is empty', '5':'Can not save the i...
ric2b/Vivaldi-browser
chromium/chrome/common/extensions/api/PRESUBMIT.py
Python
bsd-3-clause
869
0.009206
# Copyright 2016 The Chromium Authors. All rights reserved. # Use o
f this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Chromium presubmit script for src/extensions/common. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details on the presubmit API bui
lt into depot_tools. """ USE_PYTHON3 = True import sys def _CheckExterns(input_api, output_api): original_sys_path = sys.path join = input_api.os_path.join src_root = input_api.change.RepositoryRoot() try: sys.path.append(join(src_root, 'extensions', 'common', 'api')) from externs_checker import Ext...
daniellowtw/MentalMaths
utility.py
Python
mit
472
0.010593
__author__ = 'Daniel' fro
m UserData import config def get_integer_input(query="", default=None): """ Takes a query and gets an input from the user :param query: :param default: :return: """ res = "" while not str.isnumeric(res): res = input(query) if res == "" and default is not None: ...
= "0.0.2"
car3oon/saleor
saleor/search/backends/base.py
Python
bsd-3-clause
8,616
0.001857
from __future__ import absolute_import, unicode_literals from django.db.models.lookups import Lookup from django.db.models.query import QuerySet from django.db.models.sql.where import SubqueryConstraint, WhereNode from django.utils.six import text_type class FilterError(Exception): pass class FieldError(Excep...
= self.start + key + 1 return list(new)[0] def __iter__(self): return iter(self.results()) def __len__(self): return len(self.results()) def __repr__(self): data = list(self[:21]) if len(data) > 20: data[-1] = "...(remaining elements
truncated)..." return '<SearchResults %r>' % data def annotate_score(self, field_name): clone = self._clone() clone._score_field = field_name return clone class BaseSearchBackend(object): query_class = None results_class = None rebuilder_class = None def __init__...
82Flex/DCRM
WEIPDCRM/apis/contenttype.py
Python
agpl-3.0
1,147
0
# coding=utf-8 """ DCRM - Darwin Cydia Repository Manager Copyright (C) 2017 WU Zheng <i.82@me.com> This program is free software: you can redistribute it and/or modify it under the terms o
f the GNU Affero General Public License as published by the Free Software Foundation, ei
ther 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 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You sho...
RedHatQE/cfme_tests
cfme/intelligence/reports/menus.py
Python
gpl-2.0
6,600
0.001212
# -*- coding: utf-8 -*- """Module handling report menus contents""" from contextlib import contextmanager import attr from navmazing import NavigateToAttribute from widgetastic.widget import Text from widgetastic_patternfly import Button from . import CloudIntelReportsView from . import ReportsMultiBoxSelect from cfm...
anager.discard() except Exception: # In case of any exception, nothing will be saved view.manager.discard() raise # And reraise the exception else: # If no exception happens, save! view.manager.commit() view.save_button.click() @...
ortMenu @navigator.register(ReportMenu) class EditReportMenus(CFMENavigateStep): VIEW = EditReportMenusView prerequisite = NavigateToAttribute("appliance.server", "CloudIntelReports") def step(self, *args, **kwargs): self.view.edit_report_menus.tree.click_path( "All EVM Groups", ...
googleapis/python-compute
google/cloud/compute_v1/services/region_instance_group_managers/transports/base.py
Python
apache-2.0
13,869
0.001082
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
o=client_info, ),
self.create_instances: gapic_v1.method.wrap_method( self.create_instances, default_timeout=None, client_info=client_info, ), self.delete: gapic_v1.method.wrap_method( self.delete, default_timeout=None, client_info=client_info, ), self.dele...
hazelcast/hazelcast-python-client
hazelcast/protocol/codec/transactional_set_remove_codec.py
Python
apache-2.0
1,225
0.002449
from hazelcast.serialization.bits import * from hazelcast.protocol.builtin import FixSizedTypesCodec from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer, RESPONSE_HEADER_SIZE from hazelcast.protocol.builtin import StringCodec from hazelcast.protocol.builtin import D...
UID_SIZE_IN_BYTES _REQUEST_INITIAL_FRAME_SIZE = _REQUEST_THREAD_ID_OFFSET + LONG_SIZE_IN_BYTES _RESPONSE_RESPONSE_OFFSET = RESPONSE_HEADER_SIZE def encode_request(name, txn_id, thread_id, item): buf = create_initial_buffer(_REQUEST_INITIAL_FRAME_SIZE, _REQUEST_MESSAG
E_TYPE) FixSizedTypesCodec.encode_uuid(buf, _REQUEST_TXN_ID_OFFSET, txn_id) FixSizedTypesCodec.encode_long(buf, _REQUEST_THREAD_ID_OFFSET, thread_id) StringCodec.encode(buf, name) DataCodec.encode(buf, item, True) return OutboundMessage(buf, False) def decode_response(msg): initial_frame = msg...
glenjarvis/decorator_training
src/answer01.py
Python
bsd-3-clause
668
0.002994
#!/usr/bin/env python # Use the sample code in example_01.py. Create three functions named # func1, func2, and func3. # # Make func1 print: # "Hello World" # # Make func2 print: # "It's nice to meet you" # # Make func3 print: # "Howdeeeee" # Put your co
de here: # Now, make a new function called `using_functions`. # Make it take three arguments (name the arguments as you see fit) # Then, execute each of the arguments that you received. # For example, if I used arguments 'a', 'b', 'c' (do
n't use those in # your answer), my code would look like this: # # def using_functions(a, b, c): # a() # # You are left with the exercise of calling all three functions.
rouault/mapnik
tests/python_tests/layer_test.py
Python
lgpl-2.1
745
0.024161
#!/usr/bin/env python # -*- coding: utf-8 -*- from nose.tools import eq_ from utilities import run_all import mapnik # Map initialization def test_layer_init(): l = mapnik.Layer('test') eq_(l.name,'test') eq_(l.srs,'+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') eq_(
l.envelope(),mapnik.Box2d()) eq_(l.clear_label_cache,False) eq_(l.cache_features,False) eq_(l.visible(1),True) eq_(l.active,True) eq_(l.datasource,None) eq_(l.queryable,False) eq_(l.minzoom,0.0) eq_(l.maxzoom > 1e+6,True) eq_(l.group_by,"") eq_(l.maximum_extent,None) eq_(l.bu...
t_")))
lcpt/xc
verif/tests/loads/test_vector2d_point_load_global.py
Python
gpl-3.0
3,358
0.034277
# -*- coding: utf-8 -*- # Reference: Expresiones de la flecha el el Prontuario de # Estructuras Metálicas del CEDEX. Apartado 3.3 Carga puntual sobre ménsula. # ISBN: 84-7790-336-0 # url={https://books.google.ch/books?id=j88yAAAACAAJ}, '''vector2d_point_load_global verification test. Home made test.''' import xc_bas...
analisis.analyze(1) nod2= nodes.getNode(2) vDisp= nod2.getDisp a= x*L delta0= vDisp.dot(vIElem) delta0Teor= (n*a/E/A) ratio0= ((delta0-delta0Teor)/delta0Teor) delta1= vDisp.dot(vJElem) delta1Teor= (-P*a**2*(3*L-a)/6/E/I) ratio1= ((delta1-delta1Teor)/delta1Teor) # print "delta0= ",delta0 # print "delta0Teor= ",delta...
1= ",ratio1 import os from miscUtils import LogMessages as lmsg fname= os.path.basename(__file__) if (abs(ratio0)<1e-10) & (abs(ratio1)<1e-11): print "test ",fname,": ok." else: lmsg.error(fname+' ERROR.')
RevansChen/online-judge
Codewars/7kyu/disemvowel-trolls/Python/test.py
Python
mit
131
0.007634
# Python -
3.6.0 test.asse
rt_equals( disemvowel('This website is for losers LOL!'), 'Ths wbst s fr lsrs LL!' )
rafasis1986/EngineeringMidLevel
migrations/versions_/c05ed437b768_.py
Python
mit
830
0.010843
"""empty message Revision ID: c05ed437b768 Revises: 006a83e83b1a Create Date: 2016-10-14 09:56:26.984816 """ # revision identifiers, used by Alembic. revision = 'c05ed437b768' down_revision = '006a83e83b1a' from alembic import op import sqlalchemy as sa import sqlalchemy_utils def upgrade(): ### commands auto...
requests', type_='foreignkey') op.create_foreign_key(None, 'requests', 'users', ['client_id'], ['id']) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, '
requests', type_='foreignkey') op.create_foreign_key('requests_client_id_fkey', 'requests', 'clients', ['client_id'], ['id']) ### end Alembic commands ###
mbiokyle29/pipelines
seq/tasks.py
Python
mit
7,972
0.01869
from ruffus import * from seq_pipe import utils @collate(input_files, formatter("([^/]+)_[12].fastq$"), ["{path[0]}/{1[0]}_1.fastq", "{path[0]}/{1[0]}_2.fastq"]) def collate_files(input_files, output_files): log.info("Collating paired fastq files: \n\t{} \n\t{}\n".format(input_files[0], input_files[1])) @transf...
e cares but me! root = "root@alpha-helix.oncology.wisc.edu" subject = "Tophat DE pipeline Success report: {}".format(time.strftime
("%d/%m/%Y")) msg['Subject'] = subject msg['From'] = root msg['To'] = COMMASPACE.join(options.emails) msg.attach( MIMEText("\n".join(email_body)) ) # attatch the files for file in [input_file, log.handlers[0].baseFilename]: part = MIMEBase('application', "octet-stream") part.se...
FeitianSmartcardReader/pssi
pssi/plugins/sim/plugin.py
Python
gpl-3.0
1,017
0.000984
# -*- coding: utf-8 -*- # -- plugin.py # Functions required by every plugin # Copyright © 2010 Eric Bourry & Julien Flaissy # This file is part of PSSI (Python Simple Smartcard Interpreter). # PSSI is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as pub...
License, or # (at your option) any later version. # PSSI is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You
should have received a copy of the GNU General Public License # along with PSSI. If not, see <http://www.gnu.org/licenses/> import interpreters import structures def getClassByte(): return 0xA0 def getRootStructure(): return structures.structSIM def getInterpretersTable(): return interpreters.int...
dariox2/CADL
test/testyida6b.py
Python
apache-2.0
4,901
0.007958
# # test shuffle_batch - 6b # # generates a pair of files (color+bn) # pending: make the tuple match # print("Loading tensorflow...") import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import os from libs import utils import datetime tf.set_random_seed(1) def create_input_pipeline_yida(f...
t randomly # permutes the order. min_after_dequeue = len(files1) // 5 # The capacity should be larger than min_after_dequeue, and determines how # many examples are prefetched. TF docs recommend setting this value to: #
min_after_dequeue + (num_threads + a small safety margin) * batch_size capacity = min_after_dequeue + (n_threads + 1) * batch_size # Randomize the order and output batches of batch_size. batch = tf.train.shuffle_batch([crops1, crops2], enqueue_many=False, ...
pantsbuild/pants
src/python/pants/option/options.py
Python
apache-2.0
18,439
0.002766
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import dataclasses import logging from typing import Iterable, Mapping, Sequence from pants.base.build_environment import get_buildroot from pants.base...
e.
:param known_scope_infos: ScopeInfos for all scopes that may be encountered. :param args: a list of cmd-line args; defaults to `sys.argv` if None is supplied. :param bootstrap_option_values: An optional namespace containing the values of bootstrap options. We can use these values when reg...
delitamakanda/socialite
app/email.py
Python
mit
678
0.007375
from threading import Thread from flask_mail import Message from flask import render_template, current_app from . import mail from .decorators import async @async def send_async_email(app, msg): with app.app_context(): mail.send(msg) def send_email(to, subject, t
emplate, **kwargs): app = current_app._get_current_object() msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + ' ' + subject, sender=app.config['MAIL_SENDER'], recipients=[to]) msg.body = render_template(template + '.txt', **kwargs) msg.html = render_template(t
emplate + '.html', **kwargs) thr = Thread(target=send_async_email, args=[app, msg]) thr.start() return thr
bencord0/cloudmeta
manage.py
Python
agpl-3.0
252
0
#!/usr/bin/env python import os import sys if __name_
_ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cloudmeta.settings") from django.core.management import execute_from_command
_line execute_from_command_line(sys.argv)
feroda/lessons-python4beginners
students/2016-09-04/federicofioriti/Epeople.py
Python
agpl-3.0
987
0.006079
def main(): PEOPLE = insert_people() sum_salary_all(PEOPLE) list_people_by_city(PEOPLE) def insert_people(): PEOPLE = [] while True: NAMES = {} NAMES["name"] = name = raw_input("Inserisci nome ") NAMES["city"] = city = raw_input("Inseriscci citta ") NAMES["salar...
ormat(**NAMES)) while True: a = raw_input("Vuoi continuare [Y/n]? ").upper() if a in ["Y", "N"]: break if a == "N": break return PEOPLE def sum_salary_all(list_people): for p in list_people:
sum_salary_single(p) def sum_salary_single(list_people): list_people['annual'] = list_people['salary'] * 13 def list_people_by_city(list_people): list_city = list_people.sort() if __name__ == '__main__': main()
dhermes/gcloud-python
oslogin/google/cloud/oslogin_v1/proto/oslogin_pb2_grpc.py
Python
apache-2.0
7,621
0.003543
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from google.cloud.oslogin_v1.proto import ( common_pb2 as google_dot_cloud_dot_oslogin_dot_common_dot_common__pb2, ) from google.cloud.oslogin_v1.proto import ( oslogin_pb2 as google_dot_cloud_dot_oslogin__v1_dot_proto_dot_oslogi...
e.UNIMPLEMENTED)
context.set_details("Method not implemented!") raise NotImplementedError("Method not implemented!") def add_OsLoginServiceServicer_to_server(servicer, server): rpc_method_handlers = { "DeletePosixAccount": grpc.unary_unary_rpc_method_handler( servicer.DeletePosixAccount, ...
caihaibin/Blog
externals/pygments/lexers/text.py
Python
mit
54,336
0.001436
# -*- coding: utf-8 -*- """ pygments.lexers.text ~~~~~~~~~~~~~~~~~~~~ Lexers for non-source code file types. :copyright: 2006-2008 by Armin Ronacher, Georg Brandl, Tim Hatch <tim@timhatch.com>, Ronny Pfannschmidt, Dennis Kaarsemaker, Kuma...
bygroups(Keyword, Te
xt), 'distribution') ], 'distribution': [ (r'#.*?$', Comment, '#pop'), (r'\$\(ARCH\)', Name.Variable), (r'[^\s$[]+', String), (r'\[', String.Other, 'escaped-distribution'), (r'\$', String), (r'\s+', Text, 'components') ], ...
HorvathLab/NGS
attic/readCounts/src/optparse_gui/__init__.py
Python
mit
12,249
0.032574
''' A drop-in replacement for optparse ( "import optparse_gui as optparse" ) Provides an identical interface to optparse(.OptionParser), But displays an automatically generated wx dialog in order to enter the options/args, instead of parsing command line arguments ''' import sys, os, os.path, fnmatch, types, time imp...
if not match: raise optparse.OptionValueError( "option %s: File %s does not match required filetypes: %s" % (opt, value, ', '.join([ "%s (%s)"%(nm,ft) for nm,ft in option.filetypes]))) return value def check_savedir(option, opt, value): value = value.strip('"') if not option.not...
turn value if os.path.exists(value) and not os.path.isdir(value): raise optparse.OptionValueError( "option %s: Can't remove path %s" % (opt, value)) return value def check_dir(option, opt, value): value = value.strip('"') if not option.notNone and not value: return value ...
wzyy2/RTTdev
bsp/simulator/rtconfig.py
Python
gpl-2.0
2,797
0.007151
import os # toolchains options ARCH='sim' #CROSS_TOOL='msvc' or 'gcc' or 'mingw' #'msvc' and 'mingw' are both for windows # 'gcc' is for linux CROSS_TOOL='mingw' # cross_tool provides the cross compiler # EXEC_PATH is the compiler execute path if CROSS_TOOL == 'gcc' or CROSS_TOOL == 'clang-analyze': CPU =...
LPATH = '' if BUILD == 'debug': CFLAGS += ' -g -O0 -gdwarf-2' AFLAGS += ' -gdwarf-2' else: CFLAGS += ' -O2' POST_ACTION = '' elif PLATFORM == 'mingw': # toolchains PREFIX = '' CC = PREFIX + 'gcc' AS =
PREFIX + 'gcc' AR = PREFIX + 'ar' LINK = PREFIX + 'gcc' TARGET_EXT = 'exe' SIZE = PREFIX + 'size' OBJDUMP = PREFIX + 'objdump' OBJCPY = PREFIX + 'objcopy' DEVICE = ' -ffunction-sections -fdata-sections' DEVICE = ' ' CFLAGS = DEVICE AFLAGS = ' -c' + DEVICE + ' -x assembler-with-...
tyler274/Recruitment-App
recruit_app/recruit/search.py
Python
bsd-3-clause
196
0.005102
import
flask_whooshalchemy as whooshalchemy from models import HrApplication, HrApplicationComment def register_search_models(app): pass # whooshalchemy.whoosh_index(app, HrApplication)
johnbelamaric/themis
vendor/github.com/apache/thrift/test/py.tornado/test_suite.py
Python
apache-2.0
6,403
0.001718
#!/usr/bin/env python # # 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 # "L...
l(v, 63) @gen_test def test_i32(self): v = yield self.client.testI32(-1) self.assertEqual(v, -1) v = yield self.client.testI32(0) self.assertEqual(v, 0) @gen_test def test_i64(self): v = yield self.client.testI64(-34359738368) self.assertEqual(v, -34359...
@gen_test def test_struct(self): x = Xtruct() x.string_thing = "Zero" x.byte_thing = 1 x.i32_thing = -3 x.i64_thing = -5 y = yield self.client.testStruct(x) self.assertEqual(y.string_thing, "Zero") self.assertEqual(y.byte_thing, 1) self.assert...
baylee-d/cos.io
common/migrations/0047_auto_20161115_1743.py
Python
apache-2.0
1,717
0.00233
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2016-11-15 17:43 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('common', '0046_auto_20161115_1703'), ] operations = [ migrations.AlterField...
more left the page will appear. This is requ
ired for all pages where "Show in menus" is checked.'), ), migrations.AlterField( model_name='pagealias', name='menu_order', field=models.IntegerField(blank=True, default=1, help_text='The order this page should appear in the menu. The lower the number, the more left ...
RIT-CS-Mentoring-Center-Queueing/mmcga_project
server/datagrams/user_stats.py
Python
mit
2,044
0.003914
## ## File: user_stats.py ## ## Author: Schuyler Martin <sam8050@rit.edu> ## ## Description: Python class that defines a datagram for storing statistics ## on users ## from datagrams.datagram import Datagram class UserStats(Datagram): ''' Class for storing statistics on a user ''' de...
!= None): if ("q_count" in init_map): self.q_count = init_map["q_count"] if ("login_count" in init_map): self.login_count = init_map["login_coun
t"] def __str__(self): ''' Converts to a string equivalent ''' title = "User Stats for " + self.uid + "\n" return title + super().__str__() def stat_count(self, var_name): ''' Returns the stats measure of a specific variable :param: var_name Vari...
zemuvier/Python-courses
skype_bot2.py
Python
gpl-3.0
1,129
0.000886
from skypebot import * class Skype_Bot: """ This class handles communication with Skype via SkypeBot """ def __init__(self, plugins): self.skype = Skypebot.Skype(Events=self) self.skype.FriendlyName = "Skype Bot Levitan" self.skype.Attach() self.plugins = plugins de...
e :param topic: topic of the conference (it's name) :par
am message: thing to say :return: """ for chat in self.skype.Chats: if chat.Topic == topic: chat.SendMessage(message)
hammerlab/immuno
immuno/mhc_common.py
Python
apache-2.0
4,443
0.006977
# Copyright (c) 2014. Mount Sinai School of Medicine # # 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...
assert len(gene) > 0, "No HLA gene name given in %s" % original assert len(hla) > 0, "Malformed HLA
type %s" % original gene = gene.upper() # skip initial separator sep, hla = _parse_not_numbers(hla) assert sep in ("", ":", "*"), \ "Malformed separator %s in HLA type %s" % (sep, original) family, hla = _parse_numbers(hla, max_len = 2) sep, hla = _parse_not_numbers(hla) assert ...
stvstnfrd/xblock-sdk
workbench/blocks.py
Python
apache-2.0
867
0.002307
"""An XBlock to use as a child when you don't care what child to show. This code is in the Workbench layer. """ from web_fragments.fragment import Fragment from xblock.core import XBlock from .util import make_safe_for_html class DebuggingChildBlock(XBlock): """A simple gray box, to use as a child placehold...
height: 100px; margin: 10px; padding: 5px 10px; font-si
ze: 75%; } """) return frag
lordzfc/wyborySam2014
stats/migrations/0002_auto_20150919_1109.py
Python
mit
419
0.002387
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('stats
', '0001_initial'), ] operations = [ migrations.AlterField( model_name='vote', name='election', field=models.ForeignKey(blank=True, to='stats.Election', null=True),
), ]
marcardioid/DailyProgrammer
solutions/232_Easy/solution.py
Python
mit
427
0.004684
d
ef is_palindrome(data): if isinstance(data, list): data = ''.join(c.lower() for c in ''.join(data) if c.isalpha()) if isinstance(data, str): return "Palindrome" if data == data[::-1] else "Not a palindrome" else: return "Invalid input" if __name__ == "__main__": with open("input...
(lines))
coberger/DIRAC
FrameworkSystem/Service/PlottingHandler.py
Python
gpl-3.0
2,415
0.038509
""" Plotting Service generates graphs according to the client specifications and data """ __RCSID__ = "$Id$" import os import hashlib from types import DictType, ListType from DIRAC import S_OK, S_ERROR, rootPath, gConfig, gLogger, gMonitor from DIRAC.ConfigurationSystem.Client import PathFinder from DIRAC.Core....
( {'Data':data, 'PlotMetadata':metadata, 'SubplotMetadata':subplotMetadata} ) ) return m.hexdigest() types_generatePlot = [ [DictType, ListType], DictType ] def export_generatePlot( self, data, plotMetadata, subplotMetadata = {} ): """ Create a plot according to the client specification and return its name...
ata, plotMetadata, subplotMetadata ) if not result['OK']: return result return S_OK( result['Value']['plot'] ) def transfer_toClient( self, fileId, token, fileHelper ): """ Get graphs data """ retVal = gPlotCache.getPlotData( fileId ) if not retVal[ 'OK' ]: return retVal r...
cit563emef2dasdme/jklasjdf12nfasfdkl
scrape_google_scholar_from_bing.py
Python
mit
1,084
0.001845
import requests from urllib.parse import parse_qs, urlparse from lxml.html import fromstring _HEADERS = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/41.0.2272.76 Chrome/41.0.2272.76 Safari/537.36', 'accept': 'text/html,application/xhtml+xml,application...
print(len(results)) # grab the first link link = results[0].get('href') print(lin
k) # parse the destination url from the querystring qs = urlparse(link).query parsed_qs = parse_qs(qs) print(parsed_qs) print(parsed_qs.get('user', [])) # as one list links = [] for result in results: link = result.get('href') qs = urlparse(link).query links.extend(parse_qs(qs).get('user', [])) print(lin...
kleientertainment/ds_mod_tools
pkg/win32/mod_tools/exported/validate.py
Python
mit
854
0.0363
import zipfile, sys, os, glob import xml.etree.ElementTree as ET from clint.textui import progress from collections import defaultdict anim_map = defaultdict( list ) for zipfilename in progress.bar( glob.glob( "*.zip" ) ): try: with zipfile.ZipFile( zipfilename, "r" ) as zf: root = ...
omstring( zf.read( "animation.xml" ) ) for anim in root.findall( "anim" ): animname = anim.attrib[ 'name' ] rootname =
anim.attrib[ 'root' ] key = ( animname, rootname ) anim_map[ key ].append( zipfilename ) except: pass invalid = False for key, datalist in anim_map.iteritems(): if len( datalist ) > 1: print key print datalist print invalid =...
texastribune/ox-scale
ox_scale/apps/scale/signals.py
Python
apache-2.0
538
0
from django.contrib.auth.models import Group from django.contrib.auth.signals import user_logged_in def setup_user(sender, request, user, **kwargs): """ Make sure all users are in a common group and can log into the admin. This makes setting up permissions in the crud admin easier. """ if not use...
= True user.save() # TODO l
og user_logged_in.connect(setup_user)
blckshrk/Weboob
modules/caissedepargne/browser.py
Python
agpl-3.0
4,017
0.002738
# -*- coding: utf-8 -*- # Copyright(C) 2012 Romain Bignon # # This file is part of weboob. # # weboob is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your opti...
tp://www.gnu.org/licenses/>. from urlparse import urlsplit from weboob.tools.browse
r import BaseBrowser, BrowserIncorrectPassword from .pages import LoginPage, IndexPage, ErrorPage, UnavailablePage __all__ = ['CaisseEpargne'] class CaisseEpargne(BaseBrowser): DOMAIN = 'www.caisse-epargne.fr' PROTOCOL = 'https' CERTHASH = ['165faeb5bd1bad22bf52029e3c09bf540199402a1fa70aa19e9d5f92d562f...