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 |
|---|---|---|---|---|---|---|---|---|
boberfly/gaffer | config/azure/publishBuild.py | Python | bsd-3-clause | 5,308 | 0.030332 | #!/usr/bin/env python
##########################################################################
#
# Copyright (c) 2019, Cinesite VFX Ltd. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# ... | his software may be used t | o endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND... |
kylef/django-request | request/utils.py | Python | bsd-2-clause | 5,183 | 0.001929 | # -*- coding: utf-8 -*-
import re
from django.utils.translation import ugettext_lazy as _
from .router import Patterns
HTTP_STATUS_CODES = (
# Infomational
(100, _('Continue')),
(101, _('Switching Protocols')),
(102, _('Processing | (WebDAV)')),
# Success
(200, _('OK')),
(201, _('Created')),
(202, _('Accepted')),
(203, _('Non-Authoritative Information')),
(204, _('No Content')),
(205, _('Reset Content')),
(206, _('Partial Content')),
(207, _('Multi-St | atus (WebDAV)')),
# Redirection
(300, _('Multiple Choices')),
(301, _('Moved Permanently')),
(302, _('Found')),
(303, _('See Other')),
(304, _('Not Modified')),
(305, _('Use Proxy')),
(306, _('Switch Proxy')), # No longer used
(307, _('Temporary Redirect')),
# Client Error
... |
jcoady9/beets | test/test_autotag.py | Python | mit | 34,286 | 0.000029 | # -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation t... | st_add_string_both_none(self):
dist = Distance()
dist.add_string('string', None, None)
self.assertEqual(dist._penalties['string'], [0])
def test_distance(self):
config['match']['distance_weights']['album'] = 2.0
config['match']['distance_weights']['medium'] = 1.0
_cl... |
dist.add('album', 0.5)
dist.add('media', 0.25)
dist.add('media', 0.75)
self.assertEqual( |
peterstace/project-euler | OLD_PY_CODE/project_euler_old_old/187/187.py | Python | unlicense | 813 | 0.00615 | from math import log
def num_prime_factors(upper_limit):
"""
Create an array whose entries are the number of not necessarily distinct
prime factors of the index. The upper bound is the first number not
included.
"""
factor_count = [0] * upper_limit
prime = 2 #start with the first prime, whic... | += 1
| if prime >= upper_limit:
return factor_count
if factor_count[prime] == 0: break
print(sum(1 if n == 2 else 0 for n in num_prime_factors(100000000)))
|
cngo-github/nupic | examples/opf/experiments/missing_record/make_datasets.py | Python | agpl-3.0 | 4,661 | 0.01888 | #! /usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# | with Numenta, Inc., for a separate license for this software code, the
# following | terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without ev... |
naummo/swarm_maze_opencl_solver | renderer.py | Python | mit | 11,317 | 0.002828 | """
renderer.py renders the simulation animation using the data produced by simulator.py.
"""
import numpy as np
import pygame as pg
import configs as cfg
import maze
x_var = cfg.X
y_var = cfg.Y
pos_var = cfg.BOID_POS_VAR * cfg.Dimensions
pheromone_lvl_var = cfg.BOID_PHEROMONE_VAR * cfg.Dimensions
class Point:
... | ions
# initialize font; must be called after 'pygame.init()' to avoid 'Font not Initialized' error
print("Rendering the animation.")
label_font = pg.font.SysFont(cfg.label_face, cfg.label_size)
pheromone_level_font = pg.font.SysFont(cfg.pheromone_level_face, cfg.pheromone_level_size)
frames | = []
# TODO: use pygame.OPENGL
screen = pg.display.set_mode(cfg.window_size)
maze_surf = pg.Surface(cfg.window_size)
maze_surf.fill(color=cfg.maze_bg_color)
# Render static background -------------------------------------
for x in range(cfg.maze_width):
for y in range(cfg.maze_height):
... |
postla/OpenNFR-E2 | lib/python/Screens/Setup.py | Python | gpl-2.0 | 9,464 | 0.028423 | from Screens.Screen import Screen
from Components.ActionMap import NumberActionMap, ActionMap
from Components.config import config, ConfigNothing, ConfigYesNo, ConfigSelection, ConfigText, ConfigPassword
from Tools.Directories import resolveFilename, SCOPE_CURRENT_PLUGIN
from Components.SystemInfo import SystemInfo
fro... | randing import getMachineBrand, getMachineName
impo | rt xml.etree.cElementTree
def setupdom(plugin=None):
# read the setupmenu
try:
# first we search in the current path
setupfile = file(resolveFilename(SCOPE_CURRENT_PLUGIN, plugin + '/setup.xml'), 'r')
except:
# if not found in the current path, we use the global datadir-path
setupfile = file(eEnv.resolve('$... |
cliqz/socorro | webapp-django/crashstats/base/views.py | Python | mpl-2.0 | 335 | 0 | from django.conf import settings
from django.shortcuts import render
def handler500(request):
data = {'product': settings.DEFAULT_PRODUCT}
return render(request, '500.html' | , data, status=500)
def handler404(request):
data = {'product': | settings.DEFAULT_PRODUCT}
return render(request, '404.html', data, status=404)
|
jmaas/cobbler | cobbler/modules/managers/genders.py | Python | gpl-2.0 | 3,539 | 0.001695 | import distutils.sysconfig
import sys
import os
import time
import cobbler.templar
from cobbler.utils import _
from cobbler.cexceptions import CX
plib = distutils.sysconfig.get_python_lib()
mod_path = "%s/cobbler" % plib
sys.path.insert(0, mod_path)
template_file = "/etc/cobbler/genders.template"
settings_file = "/etc... | turn_list=True):
distros_genders[dist.name] += system.name + ","
# remove a trailing comma
distros_genders[dist.name] = distros_genders[dist.name][:-1]
if(distros_genders[dist.name] == ""):
distros | _genders.pop(dist.name, None)
# mgmtclasses
for mgmtcls in api.mgmtclasses():
# create the key
mgmtcls_genders[mgmtcls.name] = ""
for system in api.find_system(mgmt_classes=mgmtcls.name, return_list=True):
mgmtcls_genders[mgmtcls.name] += system.name + ","
# remove a... |
Hexadorsimal/pynes | nes/processors/cpu/instructions/flags/cld.py | Python | mit | 87 | 0 | from . | clear import ClearInstruction
class Cld(ClearInstruction):
flag_name | = 'd'
|
anhstudios/swganh | data/scripts/templates/object/tangible/ship/crafted/capacitor/shared_basic_capacitor.py | Python | mit | 472 | 0.04661 | #### NOTICE: THIS FILE IS AUTOGENERAT | ED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/ship/crafted/capacitor/shared_basic_capacitor.iff"
result.attribute_template_id = 8
result.stfName("spa... | result |
whav/hav | tests/media/test_media.py | Python | gpl-3.0 | 1,120 | 0 | from django.test import SimpleTestCase
from datetime import da | te, time, datetime
from hav.apps.media.utils.dtrange import range_from_partial_date
class DateTimeRangeTest(SimpleTestCase):
def testYearOnly(self):
self.assertEqual(
range_from_partial_date(2017),
(
datetime.combine(date(2017, 1, 1), time.min),
dat... | range_from_partial_date(2017, 2),
(
datetime.combine(date(2017, 2, 1), time.min),
datetime.combine(date(2017, 2, 28), time.max),
),
)
def testYearMonthAndDay(self):
self.assertEqual(
range_from_partial_date(2017, 2, 15),
... |
modelblocks/modelblocks-release | resource-naturalstoriesfmri/scripts/get_sound_power.py | Python | gpl-3.0 | 4,677 | 0.004062 | import sys
import re
import numpy as np
import pandas as pd
import librosa
import argparse
argparser = argparse.ArgumentParser('''
Utility for computing sound power metrics from the Natural Stories audio stimuli
''')
argparser.add_argument('files', nargs='+', help='Paths to audio files for processing')
argpars... | ix = (np.arange(len(power[doc | id])) / (441. * args.interval)).astype(int)
splits = np.where(ix[1:] != ix[:-1])[0] + 1
time = splits.astype(float) / 441.
chunks = np.array([x.mean() for x in np.split(power[docid], splits)][1:])
intervals_cur = pd.DataFrame({'time': time, 'soundPower%sms' % int(args.interval * 1000): c... |
stephane-martin/salt-debian-packaging | salt-2016.3.3/salt/states/boto_cloudwatch_alarm.py | Python | apache-2.0 | 6,749 | 0.000148 | # -*- coding: utf-8 -*-
'''
Manage Cloudwatch alarms
.. versionadded:: 2014.7.0
Create and destroy cloudwatch alarms. Be aware that this interacts with
Amazon's services, and so may incur charges.
This module uses boto, which can be installed via package, or pip.
This module accepts explicit credentials but can als... | ntinue
if isinstance(v, int) and v == int(v2):
conti | nue
if isinstance(v, list) and sorted(v) == sorted(v2):
continue
difference.append("{0}='{1}' was: '{2}'".format(k, v, v2))
else:
difference.append("new alarm")
create_or_update_alarm_args = {
"name": name,
"region": region,
"key": key,
... |
MozillaSecurity/peach | Peach/analyzer.py | Python | mpl-2.0 | 1,607 | 0.004356 | # This Source Code Form is subjec | t to the terms of the Mozilla Public
# License, v. 2.0. If a copy of | the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
class Analyzer(object):
"""
Analyzers produce data and state models. Examples of analyzers would be the parsing of Peach Pit XML files,
tokenizing a string, building a data model based on XML file, etc.
""... |
kunalarya/simple-sat-solver | satsolver/parser.py | Python | apache-2.0 | 2,344 | 0 | from __future__ import print_function, absolute_import
import re
class CNFParser(object):
"""Stream parser for DIMACS format"""
def __init__(self, file_object):
self.file_object = file_object
self.var_count = 0
self.clauses = []
self.remove_doubles = re.compile(r'\s\s+')
... | line = line.strip()
if len(line) == 0:
return
# Be flexible with comments (since some benchmarks use either)
if line[0] in '#c':
return
line = | self.remove_doubles.sub(r' ', line)
elms = line.split()
clause = []
for clause_str in elms:
clause_str = clause_str.strip()
try:
literal = int(clause_str)
except ValueError:
self._warn('Error in line #{} -- could not parse "{}... |
consbio/ncdjango | ncdjango/geoprocessing/utils.py | Python | bsd-3-clause | 6,036 | 0.002982 | import os
from importlib import import_module
import numpy
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db import transaction
from netCDF4 import Dataset
from rasterio.dtypes import is_ndarray
from shapely.geometry import shape
from trefoil.netcdf.crs import set_... | 'This service has been automatically generated from the result of a geoprocessing job.'
),
data_path=rel_path,
projection=v.extent.projection.srs,
full_extent=v.extent,
initial_extent=v.extent,
... | variable='data',
projection=v.extent.projection.srs,
x_dimension=x_var,
y_dimension=y_var,
name='data',
renderer=renderer,
full_extent=v.extent
)
ProcessingResultSe... |
Aditya8795/Python-Scripts | peturb.py | Python | mit | 1,147 | 0.00959 | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
# returns a random d dimensional vector, a direction to peturb in
def direction(d,t):
# if type == uniform
if(t == 'u'):
return np.random.uniform(-1/np.sqrt(2), 1/np.sqrt(2), d)
elif(t == 'n'):
return np.ra... | .cos(angles[0])
for i in range(1,d-1):
temp = 1
for j in range(i):
temp = temp * np.sin(angles[j])
x[i] = temp*np.cos(angles[i])
x[d-1] = x[d-2]*np.tan(angles[d-2])
return x
fig = plt.figure()
ax = plt.axes(projection='3d')
for i in range(100... | np.random.uniform(0,1,1)[0]
xs = np.sin(np.arccos(1-2*R))*np.cos(2*np.pi*R2)
ys = np.sin(np.arccos(1-2*R))*np.sin(2*np.pi*R2)
zs = 1- 2*R
ax.scatter3D(xs, ys, zs, cmap='Greens')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show() |
fogbow/fogbow-dashboard | openstack_dashboard/dashboards/fogbow/members/models.py | Python | apache-2.0 | 1,494 | 0.005355 | """
Stub file to work around django bug: https://code.djangoproject.com/ticket/7198
"""
class APIDictWrapper(object):
""" Simple wrapper for api dictionaries
Some api calls return dictionaries. This class provides identical
behavior as APIResourceWrapper, except that it will also behave as a
... | ferred method of access, to be
consistent with api resource objects from novaclient.
"""
def __init__(self, apidict):
self._apidict = apidict
def __getattr__(self, attr):
try:
return self._apidict[attr]
except | KeyError:
msg = 'Unknown attribute "%(attr)s" on APIResource object ' \
'of type "%(cls)s"' % {'attr': attr, 'cls': self.__class__}
raise AttributeError(msg)
def __getitem__(self, item):
try:
return self.__getattr__(item)
except AttributeError ... |
jorik041/Weevely | testsuite/test_etcpwd.py | Python | gpl-3.0 | 1,005 | 0.01791 | from baseclasses import SimpleTestCase
from unittest import skipIf
from test import conf
class AuditEtcPwd(SimpleTestCase):
def test_etcpwd(self):
self.assertRegexpMatches(self._outp(":audit.etcpasswd"), | 'mail:x:8:8:mail:/var/mail:/bin/sh')
self.assertRegexpMatches(self._outp(":audit.etcpasswd -real"), 'root:x:0:0:root:/root:/bin/bash')
self.assertNotRegexpMatches(self._outp(":audit.etcpasswd -real"), 'mail:x:8:8:mail:/var/mail:/bin/sh')
self.assertRegexpMatches(self._outp(":audit.etcp... | oot:x:0:0:root:/root:/bin/bash')
self.assertRegexpMatches(self._outp(":audit.etcpasswd -real -vector read"), 'root:x:0:0:root:/root:/bin/bash')
@skipIf(not conf['shell_sh'], "Skipping shell.sh dependent tests")
def test_etcpwd_cat(self):
self.assertRegexpMa... |
quodlibet/quodlibet | quodlibet/browsers/iradio.py | Python | gpl-2.0 | 32,430 | 0.000123 | # Copyright 2011 Joe Wreschnig, Christoph Reiter
# 2013-2020 Nick Boultbee
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later... | rolledWindow
from quodlibet.qltk.x import SymbolicIconImage
from quodlibet.qltk.menubutton import MenuButton
STATION_LIST_URL = \
"https://quodlibet.github.io/radio/radiolist.bz2"
STATIONS_FAV = os.path.join(quodlibet.get_user_dir(), "stations")
STATIONS_ALL = os.path.join(quodlibet.get_user_dir(), "stations_all")... | uce duplicate stations (max 3 URLs per station)
# prefer stations that match a genre?
# Migration path for pickle
sys.modules["browsers.iradio"] = sys.modules[__name__]
class IRadioError(Exception):
pass
class IRFile(RemoteFile):
multisong = True
can_add = False
format = "Radio St... |
berinhard/newfies-dialer | newfies/dnc/forms.py | Python | mpl-2.0 | 2,103 | 0.003329 | #
# Newfies-Dialer License
# http://www.newfies-dialer.org
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (C) 2011-2013 Star2Billing S.L.
#
# The Initia... | fields = ['name']
exclude = ('user',)
class DNCContactSearchForm(forms.Form):
"""Search Form on Contact List"""
phone_number = forms.CharField(label=_('phone number'), required=False,
widget=forms.TextInput(attrs={'size': 15}))
# contact_no_type = forms.Cho... | get=forms.RadioSelect)
dnc = forms.ChoiceField(label=_('Do Not Call list').title(), required=False)
def __init__(self, user, *args, **kwargs):
super(DNCContactSearchForm, self).__init__(*args, **kwargs)
# To get user's dnc list
if user:
dnc_list_user = []
dnc_li... |
adsabs/biblib-service | biblib/tests/functional_tests/test_anonymous_epic.py | Python | mit | 3,528 | 0.00085 | """
Functional test
Anonymous Epic
Storyboard is defined within the comments of the program itself
"""
import unittest
from flask import url_for
from biblib.views.http_errors import NO_PERMISSION_ERROR
from biblib.tests.stubdata.stub_data import UserShop, LibraryShop
from biblib.tests.base import TestCaseDatabase, M... | data=library_dave_private.user_view_post_data_json,
headers=user_dave.headers
)
library_id_private = response.json['id']
self.assertEqual(response.status_code, 200, response)
response = self.client.post(
url,
data=library_dave_public.user_view_po... | se)
# Anonymous user tries to access the private library. But cannot.
url = url_for('libraryview', library=library_id_private)
with MockSolrBigqueryService(number_of_bibcodes=0) as BQ, \
MockEndPoint([user_dave, user_anonymous]) as EP:
response = self.client.get(
... |
varunarya10/python-neutronclient | neutronclient/neutron/v2_0/vpn/utils.py | Python | apache-2.0 | 4,400 | 0 | # (c) Copyright 2013 Hewlett-Packard Development Company, L.P.
# 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... | message)
if key == 'action' and value not in dpd_supported_actions:
message = _(
"DPD Dictionary ValueError: "
"Reason-Invalid DPD action : "
"'%(key_value)s' not in %(supported_action)s ") % {
'k | ey_value': value,
'supported_action': dpd_supported_actions}
raise exceptions.CommandError(message)
if key in ('interval', 'timeout'):
try:
if int(value) <= 0:
raise ValueError()
except ValueError:
messag... |
incaser/odoo-templates | sample_addon_oca/models/__init__.py | Python | agpl-3.0 | 114 | 0 | # -*- coding: utf-8 -*-
# See README.rst file on | addon root folder for license detail | s
from . import res_partner
|
barmalei/primus | lib/primus/test/testmysql.py | Python | lgpl-3.0 | 1,858 | 0.014532 | #!/usr/bin/env python
#
#
# Copyright 2009 Andrei <vish@gravitysoft.org>
#
# This program is free software; you can redistribute it and/or modify
# it u | nder the terms of the GNU General Public License as published by
# the Fre | e Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See... |
DataViva/dataviva-scripts | scripts/comtrade/helpers/__init__.py | Python | mit | 5,331 | 0.000188 | country_lookup = {
24: "afago",
108: "afbdi",
204: "afben",
854: "afbfa",
72: "afbwa",
140: "afcaf",
384: "afciv",
120: "afcmr",
180: "afcod",
178: "afcog",
174: "afcom",
132: "afcpv",
262: "afdji",
12: "afdza",
818: "afegy",
232: "aferi",
732: "afesh"... | fro",
826: "eugbr",
292: "eugib",
300: "eugrc",
191: "euhrv",
348: "euhun",
833: "euimn",
372: "euirl",
352: "euis | l",
380: "euita",
381: "euita",
1381: "euita",
412: "euksv",
438: "eulie",
440: "eultu",
442: "eulux",
428: "eulva",
492: "eumco",
498: "eumda",
807: "eumkd",
470: "eumlt",
499: "eumne",
528: "eunld",
578: "eunor",
579: "eunor",
616: "eupol",
620: ... |
alawnchen/django-registration | registration/models.py | Python | bsd-3-clause | 12,135 | 0 | from __future__ import unicode_literals
import datetime
import hashlib
import random
import re
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.db import models
from django.template import RequestContext, TemplateDoesNotExist
from django.template.loader import render_to... | (user.pk)
if | isinstance(user_pk, six.text_type):
user_pk = user_pk.encode('utf-8')
activation_key = hashlib.sha1(salt+user_pk).hexdigest()
return self.create(user=user,
activation_key=activation_key)
def delete_expired_users(self):
"""
Remove expired insta... |
JulyKikuAkita/PythonPrac | cs15211/EqualTreePartition.py | Python | apache-2.0 | 2,676 | 0.001495 | __source__ = 'https://leetcode.com/problems/equal-tree-partition/discuss/'
# Time: O()
# Space: O()
#
# Description: Leetcode # 663. Equal Tree Partition
#
# Given a binary tree with n nodes,
# your task is to check if it's possible to partition the tree to two trees
# which have the equal sum of values after removing... | um%2 == 0 && map.containsKey(sum/2);
}
public int getsum(TreeNode ro | ot, Map<Integer, Integer> map ){
if(root == null)return 0;
int cur = root.val + getsum(root.left, map) + getsum(root.right, map);
map.put(cur, map.getOrDefault(cur,0) + 1);
return cur;
}
}
''' |
kennym/itools | abnf/__init__.py | Python | gpl-3.0 | 923 | 0.001086 | # -*- coding: UTF-8 -*-
# Copyright (C) 2008 Juan David Ibáñez Palomar <jdavid@itaapy.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lice | nse, or
# (at your option) any later version.
#
# This program is distributed in t | he 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 this program. If not, see <h... |
ColdrickSotK/yamlui | yamlui/__init__.py | Python | gpl-2.0 | 2,050 | 0 | # Copyright (c) 2016 Adam Coldrick
#
# This program is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in ... | ntainer': Container,
'label': Label,
'button': Button,
'textbox': TextBox
}
callbacks = {}
trees = {}
def get_callback(key=None, | widget=None):
if key is None:
return None
# First check for methods of objects bound to a direct
# ancestor of the given widget.
current = widget
while current is not None:
if (current.bound_object is not None and
hasattr(current.bound_object, key)):
ret... |
ddebrunner/streamsx.topology | test/python/topology/test2_unicode.py | Python | apache-2.0 | 2,624 | 0.001192 | # coding=utf-8
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2017
import unittest
from streamsx.topology.topology import *
from streamsx.topology.tester import Tester
from streamsx.topology import context
from streamsx.topology.context import ConfigParams
from streamsx import rest
import streamsx.ec as ... | iew names that are unicode.
"""
if self.test_ctxtype == context.ContextTypes.STANDALONE:
return self.skipTest("Skipping unicode view tests for standalone.")
view_names = [u"®®®®", u"™¬⊕⇔"]
topo = Topology()
view0 = topo.source(["hello"]).view(name=view_na | mes[0])
view1 = topo.source(["view!"]).view(name=view_names[1])
self.tester = Tester(topo)
self.tester.local_check = self._check_view_names
self.tester.test(self.test_ctxtype, self.test_config)
def _check_view_names(self):
job = self.tester.submission_result.job
vi... |
bnbowman/HlaTools | src/pbhla/alleles/extract.py | Python | bsd-3-clause | 6,294 | 0.017 | #! /usr/bin/env python
import logging
from operator import itemgetter
from pbcore.io.FastqIO import FastqWriter
from pbhla.fasta.utils import write_fasta, get_num_reads
from pbhla.external.utils import get_alignment_file
from pbhla.filenames import get_file_type
from pbhla.io.BlasrIO import BlasrReader
from pbhla.uti... | te_output( records, output_file, output_type ):
"""Write the records | out to file"""
if output_type == 'fasta':
write_fasta( records, output_file )
else:
with FastqWriter( output_file ) as writer:
for record in records:
writer.writeRecord( record )
check_output_file( output_file )
def _get_output_file( input_file ):
basena... |
WebClub-NITK/Hacktoberfest-2k17 | Python/bharm1.py | Python | mit | 47 | 0.021277 | def main():
| print("Hello, | World!")
main()
|
endlessm/chromium-browser | third_party/skia/infra/bots/recipes/perf_canvaskit.py | Python | bsd-3-clause | 3,320 | 0.004217 | # Copyright 2018 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.
# Recipe which runs the Canvaskit tests using docker
DEPS = [
'checkout',
'docker',
'env',
'infra',
'recipe_engine/file',
'recipe_engine/path',
... | oin('skia')]
args = [
'--builder', api.vars.builder_name,
'--git_hash', | api.properties['revision'],
'--buildbucket_build_id', api.properties.get('buildbucket_build_id', ''),
'--bot_id', api.vars.swarming_bot_id,
'--task_id', api.vars.swarming_task_id,
'--browser', 'Chrome',
'--config', api.vars.configuration,
... |
jkelley05/picture-scavenger-hunt | picture_hunt/forms.py | Python | gpl-2.0 | 1,679 | 0.011316 | from flask.ext.wtf import Form
from wtforms import StringField, BooleanField, TextAreaField, SelectField, FileField, IntegerField
from wtforms.validators import DataRequired, regexp, NumberRange
from wtforms.ext.sqlalchemy. | fields import QuerySelectField
from picture_hunt.models import Team, Task
class TeamForm(Form):
name = StringField('Team Name', validators=[DataRequired()])
note = TextAreaField('Note', validators=[DataRequired()])
class TaskForm(Form):
name = | StringField('Task', validators=[DataRequired()])
points = IntegerField('Points', validators=[DataRequired()])
note = TextAreaField('Note', validators=[DataRequired()])
class UploadForm(Form):
team = SelectField('Team',coerce=int, choices=[(None, 'Make a Team first'),],validators=[NumberRange(min=0, messag... |
fedora-conary/conary | conary/dbstore/sqlerrors.py | Python | apache-2.0 | 1,638 | 0.006105 | #
# Copyright (c) SAS Institute Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | aseError):
pass
class CursorErro | r(DatabaseError):
pass
class UnknownDatabase(DatabaseError):
pass
class ColumnNotUnique(CursorError):
pass
class ConstraintViolation(CursorError):
pass
class DuplicateColumnName(CursorError):
pass
class InvalidTable(CursorError):
pass
|
jbonofre/beam | sdks/python/apache_beam/runners/worker/statesampler_fake.py | Python | apache-2.0 | 1,339 | 0.006721 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional | information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not 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 ap... | er express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This module is experimental. No backwards-compatibility guarantees.
class StateSampler(object):
def __init__(self, *args, **kwargs):
pass
def scoped_state(self, step_name, state... |
renalreg/radar | migrations/versions/c747d6f9d206_add_default_nurture_tubes_values.py | Python | agpl-3.0 | 4,010 | 0.00798 | """add default nurture tubes values
Revision ID: c747d6f9d206
Revises: c9b69c2c665d
Create Date: 2017-05-16 10:21:00.181786
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from radar.models.nurture_tubes import PROTOCOL_OPTION_TYPE, SampleOption
# revision identifiers, ... | = 'c747d6f9d206'
down_revision = 'c9b69c2c665d'
branch_labels = None
depends_on = None
from sqlalchemy.orm import sessionmaker
Session = sessionmaker()
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('nurture_samples_options',
sa.Column('id', sa.Enum('ADULT_NS... | SS_15_2ND', 'CHILDREN_LESS_15_B', 'CHILDREN30_2ND', 'CHILDREN30_B', name='protocol_option_type'), nullable=False),
sa.Column('label', sa.String(), nullable=False),
sa.Column('epa', sa.Integer(), nullable=True),
sa.Column('epb', sa.Integer(), nullable=True),
sa.Column('lpa', sa.Integer(), nullable=True),... |
glon/django_test | article/migrations/0005_auto_20170804_0936.py | Python | apache-2.0 | 1,345 | 0.002974 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-08-04 09:36
from __future__ import unicode_literals
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db. | models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_d | ependency(settings.AUTH_USER_MODEL),
('article', '0004_auto_20170803_0210'),
]
operations = [
migrations.CreateModel(
name='ArticleTag',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_05_01/operations/_available_service_aliases_operations.py | Python | mit | 9,072 | 0.00474 | # 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 may ... | # type: (...) -> Iterable["_models.AvailableServiceAliasesResult"]
"""Gets all available service aliases for this subscription in this region.
:param location: The location.
:type location: str
:keyword callable | cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either AvailableServiceAliasesResult or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.network.v2020_05_01.models.AvailableServiceAliasesResult]
:raises: ~a... |
vup1120/oq-hazardlib | openquake/hazardlib/scalerel/__init__.py | Python | agpl-3.0 | 3,196 | 0.000626 | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2012-2016 GEM Foundation
#
# OpenQuake 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 Licen... | [cls.__name__] = cls
return OrderedDict((k, gsims[k]) for k in sorted(gsims))
def get_available_magnitude_scalerel():
'''
Return an ordered dictionary with the available Magnitude ScaleRel
classes, keyed by class name.
'''
return _get_available_class(BaseMSR)
def get_available_sigma_magnitude... | _available_class(BaseMSRSigma)
def get_available_area_scalerel():
'''
Return an ordered dictionary with the available Area ScaleRel
classes, keyed by class name.
'''
return _get_available_class(BaseASR)
def get_available_sigma_area_scalerel():
'''
Return an ordered dictionary with the av... |
Erotemic/local | windows/init_mitex.py | Python | gpl-3.0 | 697 | 0.007174 | #/usr/bin/env python
import utool as ut
def clean_mitex():
# if mitex does not install correctly
install_dir = 'C:\Program Files (x86)\MiKTeX 2.9'
ut.delete(install_dir)
def install_mathtools():
"""
wget http://mirrors.ctan.org/install/macros/latex/contrib/mathtools.tds.zip
mkdir | tmp2
#7z x -o"tmp2" mathtools.tds.zip
7z x -o"C:/Program Files (x86)/MiKTeX 2.9" mathtools.tds.zip
"""
pass
if __name__ == '__main__':
"""
python %USERPROFILE%/local/windows/init_mitex.py
"""
assert ut.WIN32
url = 'http://mirrors.ctan.org/systems/win32/miktex/setup/basic-miktex-2... | (fpath)
|
EDUlib/notifier | notifier/connection_wrapper.py | Python | agpl-3.0 | 1,867 | 0.002678 | import logging
import time
from django.conf import settings
from django.core.mail import get_connection as dj_get_connection
logger = logging.getLogger(__name__)
class BackendWrapper(object):
"""A wrapper around Django's Email Backend, providing hooks
for instrumentation and testing.
"""
def __ini... | d = backend
logger.info("initialized connection wrapper with email backend: %s", backend)
def send_messages(self, email_messages):
# check settings hook for rewriting email recipient, act accordingly
if settings.EMAIL_REWRITE_RECIPIENT:
for message in email_messages:
... | ()
msg_count = self._backend.send_messages(email_messages)
elapsed = time.time() - t
if msg_count > 0:
logger.info('sent %s messages, elapsed: %.3fs' % (msg_count, elapsed))
for msg in email_messages:
hdrs = dict((k, v) for k, v in dict(msg.message()).iter... |
ucb-sejits/hpgmg | hpgmgconf.py | Python | bsd-2-clause | 5,489 | 0.009838 | import sys,os
try:
import argparse
except ImportError:
print("""ERROR: Could not import argparse
Either use python2.7 or later (perhaps in a strange location such as
/bgsys/tools/python2.7.5-gnu-20130730/bin/hostpython) or install from
PyPI (https://pypi.python.org/pypi/argparse/).""")
sys.exit(1)
def mkd... | false', dest='fv_subcomm', help='Build a subcommunicator for each level in the MG v-cycle to minimize the scope of MPI_AllReduce()')
fv.add_argument('--fv-coarse-solver', help='Use BiCGStab as a bottom (coarse grid) solver', choices=['bicgstab','cabicgstab','cg','cacg'], defa | ult='bicgstab')
fv.add_argument('--fv-smoother', help='Multigrid smoother', choices=['cheby','gsrb','jacobi','l1jacobi'], default='cheby')
args = parser.parse_args()
if args.arch is None:
args.arch = args.petsc_arch
if not args.arch:
args.arch = 'build'
mkdir_p(args.arch)
configu... |
TomAugspurger/pandas | pandas/core/resample.py | Python | bsd-3-clause | 60,682 | 0.000461 | import copy
from datetime import timedelta
from textwrap import dedent
from typing import Dict, Optional, Union, no_type_check
import numpy as np
from pandas._libs import lib
from pandas._libs.tslibs import (
IncompatibleFrequency,
NaT,
Period,
Timedelta,
Timestamp,
to_offset,
)
from pandas._t... | ect.
"""
attrs = (
f"{k}={getattr(self.groupby, k)}"
for k in self._attributes
if getattr(self.groupby, k, None) is not None
)
return f"{type(self).__name__} [{', '.join(attrs)}]"
def __getattr__( | self, attr: str):
if attr in self._internal_names_set:
return object.__getattribute__(self, attr)
if attr in self._attributes:
return getattr(self.groupby, attr)
if attr in self.obj:
return self[attr]
return object.__getattribute__(self, attr)
de... |
oliver-sanders/cylc | cylc/flow/cycling/loader.py | Python | gpl-3.0 | 5,488 | 0 | # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# 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 Licen... | type]()
def get_point_relative(*args, **kwargs):
"""Return a point from an offset expression and a base point."""
cycling_type = kwargs.pop("cycling_type", DefaultCycler.TYPE)
return POINT_RELATIVE_GETTERS[cycling_type](*args, **kwargs)
def get_interval(*args, **kwargs):
"""Return a cylc.flow.cyclin... | pe", DefaultCycler.TYPE)
return get_interval_cls(cycling_type=cycling_type)(*args, **kwargs)
def get_interval_cls(cycling_type=None):
"""Return the cylc.flow.cycling.IntervalBase-derived class we're using."""
if cycling_type is None:
cycling_type = DefaultCycler.TYPE
return INTERVALS[cycling_t... |
tomchadwin/qgis2web | qgis2web/test/test_qgis2web_writers.py | Python | gpl-2.0 | 124,843 | 0.000849 | # coding=utf-8
"""Writers test.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'ri... | : False,
'Template': 'full-screen',
'Widget Background': '#000000',
'Widget Icon': '#ffffff',
'Layer search': 'None',
'Highlight on hover': False,
'Show popups on hover': False
}}
def test01_LeafletWriterResults... | d_layer(layer_path)
QgsProject.instance().addMapLayer(layer)
# Export to web map
writer = LeafletWriter()
writer.params = self.defaultParams()
writer.layers = [layer]
writer.visible = [True]
writer.interactive = [True]
writer.cluster = [False]
wri... |
dhood/launch | launch_testing/setup.py | Python | apache-2.0 | 934 | 0.001071 | from setuptools import find_packages
from setuptools import setup
setup(
name='launch_testing',
version='0.0.0',
packages=find_packages(exclude=['test']),
install_requires=['setuptools'],
author='Esteve Fernandez',
author_email='esteve@osrfoundation.org',
maintainer='Est | eve Fernandez',
maintainer_email='esteve@osrfoundation.org',
url='https://github.com/ros2/launch',
download_url='https://github.com/ros2/launch/releases',
keywords=['ROS'],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
... | cess.',
long_description='''\
This package provides helper scripts for writing tests that use the ROS launch tool.''',
license='Apache License, Version 2.0',
test_suite='test',
)
|
youtube/cobalt | third_party/skia_next/third_party/skia/infra/bots/recipes/upload_dm_results.py | Python | bsd-3-clause | 4,195 | 0.007151 | # Copyright 2016 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.
# Recipe for uploading DM results.
import calendar
PYTHON_VERSION_COMPATIBILITY = "PY3"
DEPS = [
'recipe_engine/file',
'recipe_engine/json',
'reci... | ta('uploa | d .png images (attempt 4)', retcode=1) +
api.step_data('upload .png images (attempt 5)', retcode=1)
)
yield (
api.test('trybot') +
api.properties.tryserver(
gerrit_project='skia',
gerrit_url='https://skia-review.googlesource.com/',
) +
api.properties(
build... |
msegado/edx-platform | openedx/core/process_warnings.py | Python | agpl-3.0 | 9,900 | 0.002323 | """
Script to process pytest warnings output by pytest-json-report plugin and output it as a html
"""
import argparse
import io
import itertools
import json
import os
import re
from collections import Counter
from write_to_html import (
HtmlOutlineWriter,
) # noqa pylint: disable=import-error,useless-suppression... | s are output. This function finds all file | s
and aggregates the warnings in to one large list
"""
# pdb.set_trace()
dir_path = os.path.expanduser(dir_path)
# find all files that exist in given directory
files_in_dir = [
f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))
]
warnings_files = []
... |
dbnicholson/merge-our-misc | publish_patches.py | Python | gpl-3.0 | 4,618 | 0.001516 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# publish-patches.py - publish patches for the given distribution
#
# Copyright © 2008 Canonical Ltd.
# Author: Scott James Remnant <scott@ubuntu.com>.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of version 3 of the GNU Gene... | un
from model import Distro
logger = logging.getLogger('publish_patches')
def options(parser):
parser.add_option("-t", "--target", type="string", metavar="TARGET",
default=None,
help="Distribution target to publish patches for")
def main(options, args):
logger.info... | targets = [options.target]
else:
targets = DISTRO_TARGETS.keys()
# Write to a new list
list_filename = patch_list_file()
tree.ensure(list_filename)
list_file = open(list_filename + ".new", "w")
try:
# For latest version of each package in the distribution, check for a patch f... |
kierangraham/dotfiles | Sublime/Packages/Arduino-like IDE/app/compiler.py | Python | bsd-2-clause | 24,678 | 0.025691 | #-*- coding: utf-8 -*-
# stino/compiler.py
import os
import re
import threading
import subprocess
import sublime
from . import fileutil
from . import textutil
from . import constant
from . import serial
from . import base
from . import preprocess
from . import sketch
from . import console
ram_size_dict = {}
ram_siz... | command = command
def setOutputText(self, text):
self.out_text = text
class Compiler:
def __init__(self, arduino_info, cur_project, args):
self.arduino_info = arduino_info
self.cur_project = cur_project
self.args = args.getArgs()
self.output_console = console.Console(cur_project.getName())
self.no_error... | False
self.prepare()
def getOutputConsole(self):
return self.output_console
def isFinished(self):
return self.is_finished
def noError(self):
return self.no_error
def prepare(self):
self.command_list = []
if self.args:
self.command_list = genCommandList(self.args, self.cur_project, self.arduino_i... |
puruckertom/qed_tests | tests/testing_ground.py | Python | unlicense | 14,478 | 0.005526 | import requests
from bs4 import BeautifulSoup
import unittest
import numpy.testing as npt
import unicodedata
from selenium import webdriver
# from selenium.webdriver.support.ui import WebDriverWait
import os
import time
from tabulate import tabulate
import linkcheck_helper
phantomjs_path = "C://Python27//Lib//site-pac... | webdriver.PhantomJS(executable_path=phantomjs_path, service_log_path=os.path.devnull)
browser.get(m)
# login and authenticate
username = browser.find_element_by_name("username")
| username.send_keys("betatester")
password = browser.find_element_by_name("password")
password.send_keys("ubertool")
with WaitForPageLoad(browser):
login = browser.find_element_by_xpath("//form[@name='auth']")
login.submit(... |
chriscannon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers | ExamplesFromChapters/Chapter1/SMS_behaviour.py | Python | mit | 905 | 0.049724 | import pymc as mc
import numpy as np
count_data = np.loadtxt("../../Chapter1_Introduction/data/txtdata.csv")
n_count_data = len(count_data)
alpha = 1.0/count_data.mean() #recall count_data is
#the variable that holds our txt counts
lambda_1 = mc.Exponentia... | ambda_2", alpha )
tau = mc.DiscreteUniform( "tau", lower = 0, upper = n_count_data )
@mc.deterministic
def lambda_( tau = tau, lambda_1 = lambda_1, lambda_2 = lambda_2 ):
out = np.zeros( n_count_data )
o | ut[:tau] = lambda_1 #lambda before tau is lambda1
out[tau:] = lambda_2 #lambda after tau is lambda1
return out
observation = mc.Poisson( "obs", lambda_, value = count_data, observed = True)
model = mc.Model( [observation, lambda_1, lambda_2, tau] )
mcmc = mc.MCMC(model)
mcmc.sample( 100000, 50000, 1 ) |
dylan-reeves/Simple-Plant-MS | simpleplantms/urls.py | Python | mit | 1,905 | 0.007874 | """simpleplantms URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2 | . Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to url... | admin
urlpatterns = [
#home page
url(r'^$', 'home.views.index'),
#this will send requests to the sites app example /simpleplantms/sites/
url(r'^sites/', include('sites.urls')),
#this will send requests to the departments app example /simpleplantms/departments/
url(r'^departments/', include('de... |
Yadnyawalkya/integration_tests | cfme/tests/openstack/infrastructure/test_host_lifecycle.py | Python | gpl-2.0 | 7,824 | 0.003451 | import pytest
from cfme.exceptions import ItemNotFound
from cfme.infrastructure.provider.openstack_infra import OpenstackInfraProvider
from cfme.utils.appliance.implementations.ui import navigate_to
from cfme.utils.wait import wait_for
pytestmark = [
pytest.mark.usefixtures("setup_provider_modscope"),
pytest... | ession
def test_introspect_host(host, provider, has_mistral_service):
"""Introspect host
Metadata:
test_flag: openstack_scale
Polarion:
assignee: rhcf3_machine
casecomponent: Infra
initialEstimate: 1/4h
"""
host.run_introspection()
wait_for(lambda: provider.mgmt.... | imeout=600)
host.browser.refresh()
view = navigate_to(host, 'Details')
wait_for(
lambda: view.entities.summary('Openstack Hardware').get_text_of('Introspected') ==
'true', delay=15, timeout=600, fail_func=host.browser.refresh,
message="Introspected state of host {} is true".format(ho... |
openstack/python-openstackclient | openstackclient/network/v2/network_meter_rule.py | Python | apache-2.0 | 7,644 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distrib... | ('Label to associate with this metering rule (name or ID)'),
)
return parser
def take_action(self, parsed_args):
client = self.app.client_manager.network
_meter = client.find_metering_label(parsed_args.meter,
ignore_missing=False)
... | , parsed_args)
attrs.update(
self._parse_extra_properties(parsed_args.extra_properties))
obj = client.create_metering_label_rule(**attrs)
display_columns, columns = _get_columns(obj)
data = utils.get_item_properties(obj, columns, formatters={})
return (display_column... |
stevelle/rpc-openstack | maas/plugins/rabbitmq_status.py | Python | apache-2.0 | 7,579 | 0 | #!/usr/bin/env python
# Copyright 2014, Rackspace US, 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 applicabl... | .add_option('-P', '--port', action='store', dest='port',
| default='15672',
help='Port to use when connecting')
parser.add_option('-U', '--username', action='store', dest='username',
default='guest',
help='Username to use for authentication')
parser.add_option('-p', '--password', act... |
Polarcraft/KbveBot | commands/wikipath.py | Python | gpl-2.0 | 3,242 | 0.002468 | # Copyright (C) 2013-2015 Samuel Damashek, Peter Foley, James Forcier, Srijay Kasturi, Reed Koser, Christopher Reffett, and Fox Wilson
#
# 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 ve... | nd('pre')
if path is None:
return False
output = []
for x in path.text.splitlines():
if '=>' in x:
output.append(x.split('=>')[1].strip())
return " -> ".join(output)
def get_article():
params = {'action': 'query', 'list': 'random', 'r | nlimit': 1, 'rnnamespace': 0, 'format': 'json'}
data = get('http://en.wikipedia.org/w/api.php', params=params).json()
data = data['query']['random']
return data[0]['title'].replace(' ', '_')
def check_article(name):
params = {'format': 'json', 'action': 'query', 'list': 'search', 'srlimit': '1', 'srse... |
swmerko/fantacalcio-asta-helper | FANTA/urls.py | Python | mit | 886 | 0.001129 | """FANTA URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based... | as_view(), name='home')
Including another URLconf
1. Add an import: from blog import | urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
admin.site.site_header = 'Fantacalcio Asta Helper 2016/2017'
urlpatterns = [
url(r'^admin/', include(admin.site.urls)), # admin site
url(r'', ... |
sander76/home-assistant | homeassistant/components/essent/sensor.py | Python | apache-2.0 | 3,897 | 0.00077 | """Support for Essent API."""
from __future__ import annotations
from datetime import timedelta
from pyessent import PyEssent
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, ENERGY_KILO_WATT_HOUR
import h... | ype}-{self._tariff}"
@property
def name(self):
"""Return the name of the sensor."""
return f"Essent {self._type} ({self._tariff})"
@property
def native_value(self):
"""Return the state of the sensor."""
return self._state
@property
def native_unit_of_measuremen... | HOUR
return self._unit
def update(self):
"""Fetch the energy usage."""
# Ensure our data isn't too old
self._essent_base.update()
# Retrieve our meter
data = self._essent_base.retrieve_meter_data(self._meter)
# Set our value
self._state = next(
... |
DemocracyClub/yournextrepresentative | ynr/apps/uk_results/migrations/0030_populate_postresult_post_election.py | Python | agpl-3.0 | 3,360 | 0 | from collections import defaultdict
from django.db import migrations
def set_post_election_from_post(apps, schema_editor):
"""
This is far from ideal. Try to guess the PostExtraElection
that this PostResult relates to. This will have to be done by looking
and the related memberships and assuming they... | )
post_result.post_election = pee
post_result.save()
else:
# We have results for more than one election, but only
# a single PostResult object.
# Split the result_sets up in to a new PostResult per election
... | pee = PostExtraElection.objects.get(
election=election, postextra=post_result.post.extra
)
pr = PostResult.objects.create(
post_election=pee,
post=post_result.post,
confi... |
comsaint/legco-watch | app/raw/scraper/items.py | Python | mit | 4,319 | 0.004631 | # Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
# A reminder: The 2 fields, 'file_urls' and 'files' are special fields
# required by scrapy pipeline for storing files to local disk.
# See https://groups.google.com/forum/print/msg/scrapy-user... | e_name = "HansardMinutes"
date = Field()
source_url = Field()
file_urls = Field()
files = Field()
class HansardRecord(TypedItem):
""" This will contain a DOC file for the record for the date """
type_name = "HansardRecord"
date = Field()
source_url = Field()
file_urls = Field()
... | ng agenda and hansard at the moment
#####
#Common item for Library database
class LibraryResultPage(TypedItem):
"""
Stores individual results pages, for debugging
"""
type_name = "LibraryResultPage"
# Title of the link
title = Field()
link = Field()
# Page the link was found on
brow... |
bwhmather/python-payment-terminal | payment_terminal/drivers/bbs/tests/test_frames.py | Python | bsd-3-clause | 1,484 | 0 | import io
import unittest
from payment_terminal.drivers.bbs.connection import read_frame, write_frame
class TestBBSFrames(unittest.TestCase):
def test_read_one(self):
port = io.BytesIO(b'\x00\x0512345')
self.assertEqual(read_frame(port), b'12345')
def test_read_two(self):
port = io.B... | more specific
| self.assertRaises(Exception, read_frame, port)
def test_read_truncated_header(self):
port = io.BytesIO(b'a')
# TODO more specific
self.assertRaises(Exception, read_frame, port)
def test_read_truncated_body(self):
port = io.BytesIO(b'\x00\x09trunca')
# TODO more spe... |
gpetretto/pymatgen | pymatgen/ext/cod.py | Python | mit | 5,037 | 0.000796 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
"""
This module provides classes to interface with the Crystallography Open
Database. If you use data from the COD, please cite the following works (as
stipulated by the COD developers)::
Merkys, A., Vaitk... | e formula to the version used by COD.
sql = 'select file from data where formula="- %s -"' % \
Composition(formula).hill_formula
text = self.query(sql).split("\n")
cod_ids = []
for l in text:
m = re.search(r"(\d+)", l)
if m:
cod_ids.ap... | cture_by_id(self, cod_id, **kwargs):
"""
Queries the COD for a structure by id.
Args:
cod_id (int): COD id.
kwargs: All kwargs supported by
:func:`pymatgen.core.structure.Structure.from_str`.
Returns:
A Structure.
"""
... |
miltmobley/PatchTools | patchtools/examples/tscadc/test_tscadc.py | Python | apache-2.0 | 3,432 | 0.020396 | '''
Created on May 4, 2014
@copyright 2014, Milton C Mobley
Use the Helper to investigate tsc_adc issues.
The relevant DTS source files include:
am335x-boneblack.dts
am335x-bone-common.dtsi
am33xx.dtsi
am33xx-clocks.dtsi
tps65217.dtsi
'''
from patchtools.lib.strings import Strings
from patcht... | print("Checking " + patch)
m = h.check(patch, p)
h.write(m, cf)
h.vcpf(cf, r + patch, p, { "wait" : True })
if __name__ == '__main__':
global c, h
exception_handler = ExceptionHandler()
| try:
h = Helper('config.json')
c = h.config
# Find patches that reference tscadc terms
print('find_patch_refs')
find_patch_refs()
# Find patches that reference tscadc files
print('find_patch_refs_2')
find_patch_refs_2()
... |
JaviMerino/trappy | setup.py | Python | apache-2.0 | 2,559 | 0.001172 | #!/usr/bin/env python
# Copyright 2015-2016 ARM Limited
#
# 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... | tation).The goal is to
allow developers easy and systematic access to FTrace data and leverage
the flexibility of PANDAS for the analysis.
TRAPpy also provides | functionality to build complex statistical analysis
based on the underlying FTrace data.
"""
REQUIRES = [
"numpy",
"pyparsing",
"pandas>=0.13.1",
]
EXTRAS = {
"notebook": ["matplotlib>=1.3.1",
"ipython>=3.0.0",
"jupyter>=1.0.0",
],
}
data_files = {"trappy... |
luisgustavoneves/facesworkshop | faceblend.py | Python | gpl-3.0 | 274 | 0.014599 | from PIL import Image
from glob import glob
imgs = glob('i | mgs/*.jpg')
i1 = Image.open(imgs[0])
i2 = Image.open(imgs[1])
i0 = Image.blend(i1,i2,1./2)
for i, img_path in enumerate(imgs[2:]):
img = Image.open(img_path)
i0 = Image.blend(i0,img,1./(i+3))
i0.show() | |
ulule/django-courriers | courriers/settings.py | Python | mit | 1,595 | 0.002508 | from django.conf import settings
BACKEND_CLASS = getattr(
settings, "COURRIERS_BACKEND_CLASS", "courriers.backends.simple.SimpleBackend"
)
MAILCHIMP_API_KEY = getattr(settings, "COURRIERS_MAILCHIMP_API_KEY", "")
MAILJET_API_KEY = getattr(settings, "COURRIERS_MAILJET_API_KEY", "")
MAILJET_CONTACTSLIST_LIMIT = g... | ILJET_CONTACTFILTER_LIMIT", 1000
)
MAILJET_API_SECRET_KEY = getattr(settings, "COURRIERS_MAILJET_API_SECRET_KEY", "")
DEFAULT_FROM_EMAIL = getattr(
settings, "COURRIERS_DEFAULT_FROM_EMAIL", settings.DEFAULT_FROM_EMAIL
)
DEFAULT_FROM_NAME = getattr(settings, "COURRIERS_DEFAULT_FROM_NAME", "")
ALLOWED_LANGUAGES =... | E_BY = getattr(settings, "COURRIERS_PAGINATE_BY", 9)
FAIL_SILENTLY = getattr(settings, "COURRIERS_FAIL_SILENTLY", False)
NEWSLETTERLIST_MODEL = getattr(
settings,
"COURRIERS_NEWSLETTERLIST_MODEL",
"courriers.models.newsletterlist.NewsletterList",
)
NEWSLETTER_MODEL = getattr(
settings, "COURRIERS_NEW... |
szpytfire/django-api-tools | django_api_tools/tests/tests.py | Python | mit | 24,690 | 0.002066 | import json
from django_api_tools.APIModel import APIModel, UserAuthCode
from django_api_tools.APIView import APIUrl, ReservedURL, StatusCode
from django_api_tools.tests.models import Foo, Bar, Baz, Qux, TestProfile
from django_api_tools.tests.views import TestAPIView
from django.test import TestCase
from django.test... | ctify(['bar1', 'bar2'], False), {})
# Test defaults to public user
self.assertDictKeysEqual(foo.dictify(Foo.long_description_fields, False), list(Foo.public_fields))
# Test correct registered user fields returned
foo. | _user_auth = UserAuthCode.REGISTERED_USER
self.assertDictKeysEqual(foo.dictify(Foo.long_description_fields, False), list(Foo.public_fields + Foo.registered_user_fields))
# Test correct owner fields returned
foo._user_auth = UserAuthCode.OWNER
self.assertDictKeysEqual(foo.dictify(Foo.lon... |
google/layered-scene-inference | lsi/loss/loss.py | Python | apache-2.0 | 4,153 | 0.004093 | #!/usr/bin/python
#
# Copyright 2018 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 ag... | ,
zbuf_scale=10):
"""Depth+Mask based composition loss between predictions and target.
First computes per-pixel layer assignment probs using depth+masks based
normalization, and then penalizes inconsistency in a weighed ma | nner.
Assumes a default white background image (to penalize the ray escaping).
Args:
layer_imgs: are L X [...] X C, typically RGB images per layer
layer_masks: L X [...] X 1, indicating which layer pixels are valid
layer_disps: L X [...] X 1, laywewise per pixel disparity
trg_imgs: [...] X C target... |
home-assistant/home-assistant | homeassistant/components/google_travel_time/config_flow.py | Python | apache-2.0 | 5,526 | 0.001267 | """Config flow for Google Maps Travel Time integration."""
from __future__ import annotations
import logging
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_API_KEY, CONF_MODE, CONF_NAME
from homeassistant.core import callback
import homeassistant.helpers.config... | # If we get here, it's because we couldn't connect
errors["base"] = "cannot_connect"
return self.async_show_form(
step_id="user",
| data_schema=vol.Schema(
{
vol.Required(
CONF_NAME, default=user_input.get(CONF_NAME, DEFAULT_NAME)
): cv.string,
vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_DESTINATION): cv.s... |
neithere/monk | monk/__init__.py | Python | gpl-3.0 | 1,160 | 0 | # -*- coding: ut | f-8 -*-
#
# Monk is an unobtrusive data modeling, manipulation and validation library. |
# Copyright © 2011—2015 Andrey Mikhaylenko
#
# This file is part of Monk.
#
# Monk 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 3 of the License, or
# (at your opti... |
webeng/DeepLearningTutorials | code/dA_v2.py | Python | bsd-3-clause | 16,442 | 0.001277 | """
This tutorial introduces denoising auto-encoders (dA) using Theano.
Denoising autoencoders are the building blocks for SdA.
They are based on auto-encoders as the ones used in Bengio et al. 2007.
An autoencoder takes an input x and first maps it to a hidden representation
y = f_{\theta}(x) = s(Wx+b), paramete... | back in the input space. Please refer to Vincent et al.,2008
for | more details. If x is the input then equation (1) computes a partially
destroyed version of x by means of a stochastic mapping q_D. Equation (2)
computes the projection of the input into the latent space. Equation (3)
computes the reconstruction of the input, while equation (4) computes the
reconstructi... |
ericjang/pyN | pyn_examples/4_connectivity.py | Python | bsd-2-clause | 955 | 0.040838 | '''
Example:
'''
import os,sys
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,parentdir)
from pyN import *
A = IzhikevichPopulation(name='thalamus', N=5, a=0.02, b=0.2, c=-65, d=6, v0=-70, u0=None)#tonic spiking
B = IzhikevichPopulation(name='cortex', N=10, a=0.02, b=0.25, c... | awhile for cortex to get back to thalamus?
|
stim = [{'start':10,'stop':200,'mV':20,'neurons':[0]},{'start':50,'stop':300,'mV':30,'neurons':[i for i in range(3)]}]
results = brain.simulate(experiment_name='Reentrant Thalamocortical Circuit',T=600,dt=0.25, I_ext={'thalamus':stim}, save_data='../data/', properties_to_save=['psc','I_ext','spike_raster'],stdp=True)
... |
marcusbuffett/command-line-chess | src/King.py | Python | mit | 4,542 | 0 | from src.Coordinate import Coordinate as C
from src.Move import Move
from src.Piece import Piece
WHITE = True
BLACK = False
class King (Piece):
stringRep = 'K'
value = 100
def _ | _init__(self, board, side, position, movesMade=0):
super(King, self).__init__(board, side, position)
self.movesMade = movesMade
def getPossibleMoves(self):
currentPos = self.position
movements = [C(0, 1), C(0, -1), C(1, 0), C(-1, 0), C(1, 1),
C(1, -1), C(-1, 1)... | ent
if self.board.isValidPos(newPos):
pieceAtNewPos = self.board.pieceAtPosition(newPos)
if self.board.pieceAtPosition(newPos) is None:
yield Move(self, newPos)
elif pieceAtNewPos.side != self.side:
yield Move(self, newP... |
0ffkilter/StunfiskBot | DataAnalytics.py | Python | mit | 4,440 | 0.016892 | import praw, os, json, re
from collections import OrderedDict
from peewee import *
config_file = open('%s%s' %(os.getcwd(), '/Config.txt'), 'r')
config = config_file.read()
config_file.close
config = config.split('\n')
db = MySQLDatabase(database='stunbot', host='localhost', user='root', passwd=config[1])
db.connect... | = ''
poke_dict = OrderedDict([(k,v) for v,k in sorted([(v,k) for k,v in poke_dict.items()], reverse=True)])
for poke in poke_dict:
pokemon_string = pokemon_string + '%s : %s\n' %(poke, str(poke_dict[poke]))
file = open('Pokemon.txt', 'r+')
file.write(pokemon_string)
file.close()
prin... | .items()], reverse=True)])
for user in users:
user_string = user_string + '%s : %s\n' %(user, str(users[user]))
file = open('Users.txt', 'r+')
file.write(user_string)
file.close()
print('finished user file')
word_string = ''
words = OrderedDict([(k,v) for v,k in sorted([(v,k) for... |
RealTimeWeb/wikisite | MoinMoin/util/clock.py | Python | apache-2.0 | 2,028 | 0.001972 | # -*- coding: iso-8859-1 -*-
"""
MoinMoin - Clock
@copyright: 2001-2003 Juergen Hermann <jh@web.de>,
2003-2006 MoinMoin:ThomasWaldmann
@license: GNU GPL, see COPYING for details.
"""
import time
class Clock:
""" Helper | class for code profiling
we do not use time.clock() as this does not work across threads
This is not thread-safe when it comes to multiple starts for one timer.
It is possible to recursively call the start and stop methods, you
should just ensure that you call them often enough :)
""... | (timer, generation):
if generation == 0:
return timer
else:
return "%s|%i" % (timer, generation)
_get_name = staticmethod(_get_name)
def start(self, timer):
state = self.states.setdefault(timer, -1)
new_level = state + 1
name = Clock._get_name(tim... |
mcmaxwell/idea_digital_agency | idea/feincms/module/page/extensions/navigationgroups.py | Python | mit | 1,036 | 0 | """
Page navigation groups allow assigning pages to differing navigation lists
such as header, footer and what else.
"""
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
from feincms import extensions
class Extension(exten... | ,
('footer', _('Footer')),
]
def handle_model(self):
self.model.add_to_class(
'navigation_group',
models.CharField(
_('navigation group'),
choices=self.groups,
default=self.groups[0][0],
max_length=20,
... | x=True))
def handle_modeladmin(self, modeladmin):
modeladmin.add_extension_options('navigation_group')
modeladmin.extend_list('list_display', ['navigation_group'])
modeladmin.extend_list('list_filter', ['navigation_group'])
|
vedujoshi/os_tempest | tempest/services/volume/json/snapshots_client.py | Python | apache-2.0 | 7,293 | 0.000274 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | ss SnapshotsClientJSON(rest_client.RestClient):
"""Client class to send CRUD Volume API requests."""
def __init__(self, auth_provider):
super(SnapshotsClientJSON, self).__init__(auth_provider)
self.service = CONF.volume.catalog_type
self.build_interval = CONF.volume.build_interval
... | list_snapshots(self, params=None):
"""List all the snapshot."""
url = 'snapshots'
if params:
url += '?%s' % urllib.urlencode(params)
resp, body = self.get(url)
body = json.loads(body)
return resp, body['snapshots']
def list_snapshots_with_detail(sel... |
rajathkumarmp/BinPy | BinPy/combinational/__init__.py | Python | bsd-3-clause | 48 | 0 | from BinPy.combinationa | l.combinational im | port *
|
hendrikx-itc/python-minerva | integration_tests/test_data_loading.py | Python | gpl-3.0 | 5,876 | 0.00017 | # -*- coding: utf-8 -*-
"""
Comprehensive tests of loading data into a Minerva database.
"""
import datetime
from contextlib import closing
import pytz
from minerva.storage.inputdescriptor import InputDescriptor
from minerva.storage.trend.trendstorepart import TrendStorePart
from minerva.test import clear_database
fr... | abase(start_db_container)
data_descr = [
{
'name': 'x',
'data_type': 'integer',
'description': 'some integer value',
},
{
'name': 'y',
'data_type': 'double precision',
'description': 'some floating point value',
... |
'name': 'y',
'parser_config': {
'null_value': 'NULL'
}
}
]
input_descr_lookup = {d['name']: d for d in input_descr}
data = [
('test_nulls=001', ['45', '4.332']),
('test_nulls=002', ['10', '1.001']),
('test_nulls=003', ['... |
dimagi/commcare-hq | scripts/kafka-administer.py | Python | bsd-3-clause | 1,633 | 0.001225 | #!/usr/bin/env python
"""
Utilities for administering kafka.
This can be run locally when connected to the VPN.
"""
import json
from string import ljust
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from kafka import KafkaClient
def get_num_partitions(client, broker):
return len([partition for... | of all avail | able topics, suitable for the
`kafka-reassign-partitions.sh `--topics-to-move-json-file` file.
"""
topics_dict = {
'topics': [{'topic': topic} for topic in client.topics],
'version': 1,
}
print(json.dumps(topics_dict, indent=4))
def main():
parser = ArgumentParser(description=_... |
jabesq/home-assistant | homeassistant/components/mysensors/climate.py | Python | apache-2.0 | 6,774 | 0 | """MySensors platform that offers a Climate (MySensors-HVAC) component."""
from homeassistant.components import mysensors
from homeassistant.components.climate import ClimateDevice
from homeassistant.components.climate.const import (
ATTR_TARGET_TEMP_HIGH, ATTR_TARGET_TEMP_LOW, DOMAIN, HVAC_MODE_AUTO,
HVAC_MODE... | | SUPPORT_FAN_MODE
if (set_req.V_HVAC_SETPOINT_COOL in self._values and
set_req.V_HVAC_SETPOINT_HEAT in self._values):
features = (
features | SUPPORT_TARGET_TEMPERATURE_RANGE)
else:
features = features | SUPPORT_TARGET_TEMPERATURE
return ... | lf):
"""Return True if unable to access real state of entity."""
return self.gateway.optimistic
@property
def temperature_unit(self):
"""Return the unit of measurement."""
return TEMP_CELSIUS if self.gateway.metric else TEMP_FAHRENHEIT
@property
def current_temperature(... |
biddellns/litsl | players/urls.py | Python | gpl-3.0 | 437 | 0.004577 | from django.conf.urls import url
from .views import HomePage, PlayerList, PlayerDetail, SignUpForm
urlpatterns = [
url(r'^$', HomePage.as_v | iew(),
name='home'),
url(r'^list$', PlayerList.as_vi | ew(),
name='player_list'),
url(r'signup/$', SignUpForm.as_view(),
name="signup"),
url(r'^(?P<pk>[0-9]+)/$', PlayerDetail.as_view(), name='player_detail'),
]
|
maniero/SOpt | Python/Function/Sugar.py | Python | mit | 86 | 0.011905 | var.index('André')
index(var, 'André')
#https://pt.stackoverflow.c | om/q/1997 | 37/101
|
ishgroup/lightbook | ldap_api/ldap_auth.py | Python | apache-2.0 | 1,914 | 0 | from functools import wraps
import ldap3
from flask import request, g, Response
from .settings import SiteSettings
from urllib.parse import urlparse
config = SiteSettings()
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not authent... | p3.ALL_ATTRIBUTES
)
dn = unauthenticated_conn.response[0]['dn']
# now let's bind with this employee
auth_conn = ldap3.Connection(s, user=dn, password=password)
if not auth_conn.bind():
raise OSError('No such user')
g.ldap_connection = auth_conn
retur... | n False
def need_auth_response():
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
|
lafactura/datea-api | datea_api/apps/seo/views.py | Python | agpl-3.0 | 5,300 | 0.029834 | # -*- coding: utf-8 -*-
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.utils.text import Truncator
from django.utils.html import strip_tags
import os
from account.models import User
from tag.models import Tag
from dateo.models import Dateo
from campaign.models im... | f campaign_detail(request, username, slug):
try:
campa | ign = Campaign.objects.get(user__username=username, slug=slug)
ctx = default_meta.copy()
ctx.update({
'title': '#'+campaign.main_tag.tag+', '+campaign.name + ' | Datea',
'description': campaign.short_description,
'url': app_url+'/'+campaign.user.username+'/'+campaign.slug
})
if campaign.image:
ctx[... |
arrti/proxypool | proxypool/proxy_crawler.py | Python | apache-2.0 | 4,906 | 0.004688 | import asyncio
from itertools import compress
import traceback
from proxypool.rules.rule_base import CrawlerRuleBase
from proxypool.utils import page_download, page_download_phantomjs, logger, Result
class ProxyCrawler(object):
"""Crawl proxies according to the rules."""
def __init__(self, proxies, rules=No... | cio.get_event_loop()
try:
loop.run_until_complete(pc.start())
count.value = proxies.qsize()
except:
logger.error(traceb | ack.format_exc())
finally:
loop.close()
if __name__ == '__main__':
proxies = asyncio.Queue()
proxy_crawler_run(proxies)
|
Azure/azure-sdk-for-python | sdk/apimanagement/azure-mgmt-apimanagement/azure/mgmt/apimanagement/aio/operations/_gateway_certificate_authority_operations.py | Python | mit | 19,672 | 0.005134 | # 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 may ... | e
:return: An iterator like instance of either GatewayCertificateAuthorityCollection or the
result of cls(response) |
:rtype:
~azure.core.async_paging.AsyncItemPaged[~api_management_client.models.GatewayCertificateAuthorityCollection]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.GatewayCertificateAuthorityCollection"]
err... |
avanov/assignment | setup.py | Python | mit | 2,111 | 0.000947 | import os
import sys
from pathlib import Path
from setuptools import setup
from setuptools import find_packages
from setuptools.command.test import test as TestCommand
here = Path(os.pat | h.abspath(os.path.dirname(__file__) | ))
with here.joinpath('README.rst').open() as f:
README = f.read()
with here.joinpath('requirements.txt').open() as f:
rows = f.read().strip().split('\n')
requires = []
for row in rows:
row = row.strip()
if row and not (row.startswith('#') or row.startswith('http')):
requir... |
xyuanmu/XX-Net | python3.8.2/Lib/site-packages/pip/_internal/req/req_set.py | Python | bsd-2-clause | 7,860 | 0 | from __future__ import absolute_import
import logging
from collections import OrderedDict
from pip._internal.exceptions import InstallationError
from pip._internal.utils.logging import indent_log
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
from pip._internal.wheel import Wheel
if MYPY_CHECK_RUNNING:
... | ts.values()
if not req.comes_from]
reqs.sort(key=lambda req: req.name.lower())
return ' '.join([str(req.req) for req in reqs])
def __repr__(self):
# type: () -> str
reqs = [req for req in self.requirements.values()]
reqs.sort(key=lambda req: req.name.lower())... | def add_requirement(
self,
install_req, # type: InstallRequirement
parent_req_name=None, # type: Optional[str]
extras_requested=None # type: Optional[Iterable[str]]
):
# type: (...) -> Tuple[List[InstallRequirement], Optional[InstallRequirement]] # noqa: E501
"""... |
apache/libcloud | libcloud/common/providers.py | Python | apache-2.0 | 4,027 | 0.000745 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | vider_name.lower():
_mod = __import__(mod_name, globals(), locals(), [driver_name])
return getattr(_mod, driver_name)
raise AttributeError("Provider %s does not exist" % (provider))
def set_driver(drivers, provider, module, klass):
"""
Sets a driver.
:param drivers: Dictionar... | he driver
:type module: L
:param klass: The driver class name
:type klass:
"""
if provider in drivers:
raise AttributeError("Provider %s already registered" % (provider))
drivers[provider] = (module, klass)
# Check if this driver is valid
try:
driver = get_driver(dri... |
useEvil/flickr-photo-sync | flickrphotosync/photosync/models.py | Python | mit | 4,333 | 0.001154 | import datetime as date
from django.db import models
from mixins.models import ModifiedDate
from photosync.flickr import Flickr
# Create your models here.
class Collection(ModifiedDate):
title = models.CharField(max_length=250)
slug = models.CharField(max_length=250)
total = models.PositiveIntegerField(... | ifiedDate):
IMAGE_TYPES = (
(0, 'JPG'),
(1, 'GIF'),
(2, 'PNG'),
(3, 'TIFF'),
)
title = models.CharField(max_length=250)
slug = models.CharField(max_length=250)
file_name = models.CharField(max_length=500)
full_path = models.CharField(max_length=1000)
width =... | False, default=0)
type = models.PositiveIntegerField(blank=False, default=0, choices=IMAGE_TYPES)
farm = models.PositiveIntegerField(blank=False, default=0)
server = models.PositiveIntegerField(blank=False, default=0)
description = models.TextField(max_length=65000, blank=True, null=True)
photoset =... |
RNAcentral/rnacentral-webcode | rnacentral/portal/migrations/0018_auto_20171214_1524.py | Python | apache-2.0 | 511 | 0.001957 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portal', '0 | 017_auto_20171214_1138'),
]
operations = [
migrations.AlterField(
model_name='ensemblinsdcmapping',
name='assembly_id',
field=models.ForeignKey(related_name | ='assembly', db_column=b'assembly_id', to='portal.EnsemblAssembly', on_delete=models.CASCADE),
),
]
|
Splawik/pytigon | pytigon/prj/schodf/apps.py | Python | lgpl-3.0 | 77 | 0 | APPS = [
| "schodfupload",
]
APPS_E | XT = []
PUBLIC = False
MAIN_PRJ = False
|
soad241/django-haystack | tests/core/tests/views.py | Python | bsd-3-clause | 7,147 | 0.005177 | from threading import Thread
import Queue
from django.core.urlresolvers import reverse
from django.conf import settings
from django import forms
from django.http import HttpRequest
from django.test import TestCase
import haystack
from haystack.forms import model_choices, SearchForm, ModelSearchForm
from haystack.query ... | e):
urls = 'core.tests.results_per_page_urls'
def test_custom_results_per_page(self):
response = | self.client.get('/search/', {'q': 'hello world'})
self.assertEqual(response.status_code, 200)
self.assertEqual(len(response.context[-1]['page'].object_list), 1)
self.assertEqual(response.context[-1]['paginator'].per_page, 1)
response = self.client.get('/search2/', {'q': 'hello w... |
itsmemattchung/speedcurve.py | docs/conf.py | Python | mit | 9,566 | 0.005959 | # -*- coding: utf-8 -*-
#
# Speedcurve.py documentation build configuration file, created by
# sphinx-quickstart on Mon Nov 16 12:29:28 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.... | t.autodoc',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding... |
author = u'Matt Chung'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1.1'
# The full version, including alpha/beta/rc tags.
release = '0.0.1'
# The l... |
andresailer/DIRAC | RequestManagementSystem/Agent/RequestOperations/ForwardDISET.py | Python | gpl-3.0 | 2,709 | 0.021041 | ########################################################################
# $HeadURL $
# File: ForwardDISET.py
# Author: Krzysztof.Ciba@NOSPAMgmail.com
# Date: 2013/03/22 12:40:06
########################################################################
""" :mod: ForwardDISET
==================
.. module: Forwa... | ion.Error = forward["Message"]
return for | ward
self.log.info( "DISET forwarding done" )
self.operation.Status = "Done"
return S_OK()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.