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 |
|---|---|---|---|---|---|---|---|---|
AJAnderson/pychallonge | challonge/matches.py | Python | bsd-2-clause | 662 | 0.001511 | from challonge import api
def index(t | ournament, **params):
"""Retrieve a tournament's match list."""
return api.fetch_and_parse(
"GET",
"tournaments/%s/matches" % tournament,
**params)
def show(tournament, match_id):
"""Retrieve a single match record | for a tournament."""
return api.fetch_and_parse(
"GET",
"tournaments/%s/matches/%s" % (tournament, match_id))
def update(tournament, match_id, **params):
"""Update/submit the score(s) for a match."""
api.fetch(
"PUT",
"tournaments/%s/matches/%s" % (tournament, match_id), ... |
stefan2904/activismBot | botManager/__init__.py | Python | mit | 56 | 0 | default_app_config = 'botManager.apps.Botmanager | Config | '
|
thiagopena/PySIGNFe | pysignfe/cte/v300/modais_300.py | Python | lgpl-2.1 | 25,635 | 0.0126 | # -*- coding: utf-8 -*-
from pysignfe.corr_unicode import *
from pysignfe.xml_sped import *
from pysignfe.cte.v300 import ESQUEMA_ATUAL
import os
DIRNAME = os.path.dirname(__file__)
class EmiOcc(XMLNFe):
def __init__(self):
super(EmiOcc, self).__init__()
self.CNPJ = TagCaracter(nome='CNPJ', tam... | grupo('//CTe/infCte/infCTeNorm/infModal/rodo/occ', Occ, sigla_ns='cte')
xml = property(get_xml, set_xml)
class InfTotAP(XMLNFe):
def __init__(self):
super(InfTotAP, self).__ini | t__()
self.qTotProd = TagCaracter(nome='qTotProd' , tamanho=[ 1, 1, 1], raiz='//infTotAP', namespace=NAMESPACE_CTE, namespace_obrigatorio=False)
self.uniAP = TagCaracter(nome='uniAP' , tamanho=[ 1, 4], raiz='//infTotAP', namespace=NAMESPACE_CTE, namespace_obrigatorio=False)
def get_xml(self... |
Yukarumya/Yukarum-Redfoxes | js/src/gdb/mozilla/prettyprinters.py | Python | mpl-2.0 | 14,426 | 0.00305 | # mozilla/prettyprinters.py --- infrastructure for SpiderMonkey's auto-loaded pretty-printers.
import gdb
import re
# Decorators for declaring pretty-printers.
#
# In each case, the decoratee should be a SpiderMonkey-style pretty-printer
# factory, taking both a gdb.Value instance and a TypeCache instance as
# argume... | _printer(fn)
add_to_subprinter_list(fn, type_name)
printers_by_tag[type_name] = fn
return fn
return add
# a dictionary mapping gdb.Type tags to pretty-printer functions for pointers to
# that type.
ptr_printers_by_tag = {}
# A decorator: add the decoratee as a pretty-printer lookup functio... | _to_subprinter_list(fn, "ptr-to-" + type_name)
ptr_printers_by_tag[type_name] = fn
return fn
return add
# a dictionary mapping gdb.Type tags to pretty-printer functions for
# references to that type.
ref_printers_by_tag = {}
# A decorator: add the decoratee as a pretty-printer lookup function for
... |
rosudrag/Freemium-winner | VirtualEnvironment/Lib/site-packages/nose/config.py | Python | mit | 25,277 | 0.000752 | import logging
import optparse
import os
import re
import sys
import configparser
from optparse import OptionParser
from nose.util import absdir, tolist
from nose.plugins.manager import NoPlugins
from warnings import warn, filterwarnings
log = logging.getLogger(__name__)
# not allowed in config files
option_blacklist... | ity = int(env.get('NOSE_VERBOSE', 1))
self.where = ()
self.py3where = ()
self.workingDir = os.getcwd()
self.traverseNamespace = False
self.firstPackageWins = False
self.parserClass = OptionParser
self.worker = | False
self._default = self.__dict__.copy()
self.update(kw)
self._orig = self.__dict__.copy()
def __getstate__(self):
state = self.__dict__.copy()
del state['stream']
del state['_orig']
del state['_default']
del state['env']
del state['logStr... |
RoboCupULaval/StrategyIA | ai/STA/Tactic/face_target.py | Python | mit | 815 | 0.009816 | # Under MIT license, see LICENSE.txt
from typing import List
from Util import Pose
from Util.ai_command import CmdBuilder
from ai.GameDomainObjects import Player
from ai.STA.Tactic.tactic im | port Tactic
from ai.STA.Tactic.tactic_constants import Flags
from ai.states.game_state import GameState
class FaceTarget(Tactic):
def __init__(self, game_state: GameState, player: Player, target: Pose=Pose(), args: List[str]=None):
super().__init__(game_sta | te, player, target, args)
self.next_state = self.exec
self.player_position = player.pose.position
def exec(self):
self.status_flag = Flags.WIP
target_orientation = (self.target.position - self.player.pose.position).angle
return CmdBuilder().addMoveTo(Pose(self.player_positio... |
fjyuu/fjgraph | ip_lp.py | Python | mit | 2,332 | 0.000452 | #!/usr/bin/env python
#coding: utf-8
"ランダムグラフアンサンブルにおける最小頂点被覆問題のIP解とLP解を比較するプログラム"
# Copyright (c) 2013 Yuki Fujii @fjyuu
# Licensed under the MIT License
from __future__ import division, print_function
import fjgraph
import fjutil
import fjexperiment
import random
def parse_arguments():
import optparse
im... | random.seed(opts.seed)
ensemble_def = fjutil.load_json_file(json_file)
ensemble = fjgraph.GraphEnsembleFactory().create(**ensemble_def)
print("ensemble: {}".format(ensemble))
print("num_of_trials: {}".format(opts.trials))
print("seed: {}".format(opts.seed))
print()
# 結果出力
r = fjexpe... | = main result =")
print("ave_num_of_one_half: {:.4} ({:.2%})".format(
r["ave_num_of_one_half"], r["ave_num_of_one_half_ratio"]))
print("ave_opt_ration: {:.4}".format(r["ave_opt_ration"]))
print("ave_lp_opt_value: {:.4}".format(r["ave_lp_opt_value"]))
print("ave_ip_opt_value: {:.4}".format(r[... |
rs2/pandas | pandas/tests/io/test_parquet.py | Python | bsd-3-clause | 37,933 | 0.000923 | """ test parquet compat """
import datetime
from io import BytesIO
import os
import pathlib
from warnings import (
catch_warnings,
filterwarnings,
)
import numpy as np
import pytest
from pandas._config import get_option
from pandas.compat import is_platform_windows
from pandas.compat.pyarrow import (
pa_... | optional
Closed set of column names to be compared
check_like: bool, optional
If True, ignore the order of index & columns.
repeat: int, optional
How many times to repeat the test
"""
write_kwargs = write_kwargs or {"compression": None}
read_k | wargs = read_kwargs or {}
if expected is None:
expected = df
if engine:
write_kwargs["engine"] = engine
read_kwargs["engine"] = engine
def compare(repeat):
for _ in range(repeat):
df.to_parquet(path, **write_kwargs)
with catch_warnings(record=True):... |
ritchyteam/odoo | addons/mass_mailing/models/mass_mailing.py | Python | agpl-3.0 | 28,891 | 0.003392 | # -*- coding: utf-8 -*-
from datetime import datetime
from dateutil import relativedelta
import json
import random
from openerp import tools
from openerp.exceptions import Warning
from openerp.tools.safe_eval import safe_eval as eval
from openerp.tools.translate import _
from openerp.tools import ustr
from openerp.os... | 'mail.mass_mailing.category', 'mail_mass_mailing_category_rel',
'category_id', 'campaign_id', string='Categories'),
'mass_mailing_ids': fields.one2many(
'mail.mass_mailing', 'mass_mailing_campaign_id',
'Mass Mailings',
),
'unique_ab_testing': fields... | 'AB Testing',
help='If checked, recipients will be mailed only once, allowing to send'
|
xiangke/pycopia | core/pycopia/OS/Linux/IOCTL.py | Python | lgpl-2.1 | 3,107 | 0.011909 | #!/usr/bin/python2.4
# vim:ts | =4:sw=4:softtabstop=4:smarttab:expandtab
#
# $Id$
#
# Copyright (C) 1999-2006 | Keith Dart <[email protected]>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This librar... |
harshilasu/LinkurApp | y/google-cloud-sdk/platform/gcutil/lib/google_compute_engine/gcutil_lib/windows_password_test.py | Python | gpl-3.0 | 3,274 | 0.00733 | # Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | m.SystemRandom = _MockRandom(seed).GetRandomGenerator
try:
user_name = 'wind | ows_user'
# Make sure that the generated password meets strong password
# requirement.
password = windows_password.GeneratePassword(user_name)
LOGGER.info('testGeneratePassword: Generated password: %s' % password)
windows_password.ValidateStrongPasswordRequirement(password, user_name)
... |
creasyw/IMTAphy | documentation/doctools/tags/0.2/sphinx/util/smartypants.py | Python | gpl-2.0 | 9,819 | 0.000509 | r"""
This is based on SmartyPants.py by `Chad Miller`_.
Copyright and License
=====================
SmartyPants_ license::
Copyright (c) 2003 John Gruber
(http://daringfireball.net/)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitt... | ce or otherwise) arising in any way out of the use
of this software, even if advised of the possibility of such damage.
.. _Chad Miller: http://web.chad.org/
"""
import re
def sphinx_ | smarty_pants(t):
t = t.replace('"', '"')
t = educateDashesOldSchool(t)
t = educateQuotes(t)
t = t.replace('"', '"')
return t
# Constants for quote education.
punct_class = r"""[!"#\$\%'()*+,-.\/:;<=>?\@\[\\\]\^_`{|}~]"""
close_class = r"""[^\ \t\r\n\[\{\(\-]"""
dec_dashes = r"""–|&... |
hassaanm/stock-trading | src/pybrain/structure/modules/lstm.py | Python | apache-2.0 | 5,940 | 0.007239 | __author__ = 'Daan Wierstra and Tom Schaul'
from scipy import tanh
from neuronlayer import NeuronLayer
from module import Module
from pybrain.structure.parametercontainer import ParameterContainer
from pybrain.tools.functions import sigmoid, sigmoidPrime, tanhPrime
class LSTMLayer(NeuronLayer, ParameterContainer):
... | rgetgate', dim),
('ingatex', dim),
('outgatex', dim),
('forgetgatex', dim),
('state', dim),
('ingateError', dim),
('outgateError', dim),
('forgetgateError', di | m),
('stateError', dim),
]
Module.__init__(self, 4*dim, dim, name)
if self.peepholes:
ParameterContainer.__init__(self, dim*3)
self._setParameters(self.params)
self._setDerivatives(self.derivs)
def _setParameters(self, p, owner = None):
... |
ergodicbreak/evennia | evennia/locks/lockhandler.py | Python | bsd-3-clause | 19,738 | 0.002533 | """
A *lock* defines access to a particular subsystem or property of
Evennia. For example, the "owner" property can be impmemented as a
lock. Or the disability to lift an object or to ban users.
A lock consists of three parts:
- access_type - this defines what kind of access this lock regulates. This
just a stri... | ord arguments
to the function as a list and a diction | ary respectively.
Example:
perm(accessing_obj, accessed_obj, *args, **kwargs):
"Checking if the object has a particular, desired permission"
if args:
desired_perm = args[0]
return desired_perm in accessing_obj.permissions.all()
return False
Lock functions should most oft... |
bijanebrahimi/pystatus | pystatus/views/activitystreams.py | Python | gpl-3.0 | 588 | 0.008503 | from flask import Blueprint, render_template, request, abort, make_response
from pystatus.models import Us | er
bp = Blueprint('activitystreams', __name__, url_prefix='/main/activitystreams')
@bp.route('/user_t | imeline/<user_id>.atom', methods=['GET'])
def user_timeline(user_id):
print 'activity stream'
user = User.query.filter(User.id==user_id).first_or_404()
response= make_response(render_template('activitystreams/user_timeline.xml',
user=user))
response.heade... |
marook/python-crucible | src/modules/crucible/rest.py | Python | gpl-3.0 | 1,700 | 0.008235 | import urllib
import urllib2
import json
import functools
def buildUrl(url, params = []):
if(len(params) > 0):
if url.find('?') < 0:
# no '?' in the url
url += '?'
first = True
else:
first = False
for key, value in params:
... | = urllib.quote(key) + '=' + urllib.quote(str(value))
return url
class UrlOpenFactory(object):
@property
def httpParams(self):
# we have to send anyting... so why not json?
return {
'Content-Type': 'application/json',
'Accept': 'application/json',
... | rlopen(self, url, data = None):
return urllib2.urlopen(self.createRequest(url, data)).read()
class JsonUrlOpenFactory(UrlOpenFactory):
@property
def httpParams(self):
return {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
... |
gomezstevena/LSSSolver | parallel/__init__.py | Python | gpl-3.0 | 64 | 0.015625 | from .parallel import MPIComm, | MASTER, MGridParallel, SIZE, RANK | |
FluidityStokes/fluidity | tests/wetting_and_drying_balzano1_cg/plotfs_detec.py | Python | lgpl-2.1 | 5,325 | 0.020657 | #!/usr/bin/env python3
import vtktools
import sys
import math
import re
import matplotlib.pyplot as plt
import getopt
from scipy.special import erf
from numpy import poly1d
from matplotlib.pyplot import figure, show
from numpy import pi, sin, linspace
from matplotlib.mlab import stineman_interp
from numpy import exp... | k', label='Bathymetry')
#plt.legend()
if t==plot_end:
# change from meters in kilometers in the x-axis
# return locs, labels where locs is an array of tick locations and
# labels is an array of tick labels.
... | plt.xticks(locs, labels)
plt.ylim(-2.2,1.4)
#plt.title(plot_name)
plt.xlabel('Position [km]')
plt.ylabel('Free surface [m]')
if save=='':
plt.draw()
... |
huffpostdata/python-pollster | pollster/models/inline_response_200_3.py | Python | bsd-2-clause | 3,634 | 0.000826 | # coding: utf-8
from pprint import pformat
from six import iteritems
import re
class InlineResponse2003(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, cursor=None, next_cursor=None, count=None, items=No... | for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
val | ue
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
... |
sre/rubber | src/depend.py | Python | gpl-2.0 | 7,332 | 0.036007 | """
This module contains code for handling dependency graphs.
"""
import os, time
from subprocess import Popen
from rubber.util import _, msg
class Set (dict):
"""
Represents a set of dependency nodes. Nodes can be accessed by absolute
path name using the dictionary interface.
"""
pass
# constants for the retu... | = self
return ERROR
# Here we must take the integer part of the value returned by
# time.time() because the modification times for files, returned
# by os.path.getmtime(), is an integer. Keeping the fractional
# part could lead to errors in time comparison when a compilation
# is shorter than one se... | This method is called when a node has to be (re)built. It is supposed
to rebuild the files of this node, returning true on success and false
on failure. It must be redefined by derived classes.
"""
return False
def force_run (self):
"""
This method is called instead of 'run' when rebuilding this node was
... |
deggis/drinkcounter | clients/s60-python/client.py | Python | gpl-2.0 | 1,757 | 0.007968 | import urllib2
import appuifw, e32
from key_codes import *
class Drinker(object):
def __init__(self):
self.id = 0
self.name = ""
self.prom = 0.0
self.idle = ""
self.drinks = 0
def get_drinker_list():
data = urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/get_da... | 'info | ')
new_drinkers = get_drinker_list()
items = get_listbox_items(new_drinkers)
lb.set_list(items, lb.current())
#Create an instance of Listbox and set it as the application's body
lb = appuifw.Listbox(items, handle_selection)
appuifw.app.body = lb
app_lock.wait()
|
bruth/restlib2 | restlib2/params.py | Python | bsd-2-clause | 5,458 | 0.00055 | import logging
import warnings
import collections
from six import add_metaclass
from functools import partial
logger = logging.getLogger(__name__)
class Param(object):
"Describes a single parameter and defines a method for cleaning inputs."
def __init__(self, default=None, allow_list=False, description=None,... | self).__init__(*args, **kwargs)
def clean(self, value, *args, **kwargs):
value = value.lower()
if value in self.true_values:
value = True
elif value in self.false_values:
value = False
else:
raise ValueError
return super(BoolParam, self).c... | rMetaclass(type):
def __new__(cls, name, bases, attrs):
new_cls = type.__new__(cls, name, bases, attrs)
fields = getattr(new_cls, '_fields', {}).copy()
defaults = getattr(new_cls, '_defaults', {}).copy()
if hasattr(new_cls, 'param_defaults'):
warnings.warn('Resource.par... |
griimick/feature-mlsite | app/liner/views.py | Python | mit | 1,108 | 0.004513 | from flask import Blueprint, request, render_template
from ..load import processing_results
from ..abbr import get_abbr_map
abbr_map = get_abbr_map()
liner_mod = Blueprint('liner', __name__, template_folder='templates', static_folder='static')
@liner_mod.route('/liner', methods=['GET', 'POST'])
def liner():
if r... | e('projects/line.html', message='Please separate each line with "."')
abbr_expanded_text = ""
for word in query.split():
if word in abbr_map:
abbr_expanded_text += abbr_map[word]
else:
abbr_expanded_text += word
abbr_expanded_text += "... | re, line_sentiment, text, length = processing_results(text)
return render_template('projects/line.html', data=[data, emotion_sents, score, zip(text, line_sentiment), length, abbr_expanded_text])
else:
return render_template('projects/line.html')
|
catsop/CATMAID | scripts/experiment/cairo_render.py | Python | gpl-3.0 | 4,795 | 0.016684 | #!/usr/bin/python
# This script fetches treenodes from the database and renders them to
# stack-sized PNGs
from __future__ import division, print_function
from math import pi as M_PI # used by many snippets
import sys
import psycopg2
import os
import numpy as np
import yaml
import cairo
if not (cairo.HAS_IMAGE_SURF... | letons from this project
query = 'SELECT ci.id FROM class_instance ci WHERE ci.project_id = %s AND ci.class_id = %s'
c.execute(query,(pid,scid))
rows = c.fetchall()
if len(rows) == 0:
print("No skeletons found in project {0}".format(ptitle), file=sys.stderr)
sys.exit(1)
# fetch skeleton nodes
query = """
SELEC... | (tn.location).x, (tn.location).y, (tn.location).z, tn.parent_id, tci.class_instance_id as skeleton_id
FROM treenode as tn, treenode_class_instance as tci
WHERE tn.project_id = {pid} and tci.treenode_id = tn.id and tci.relation_id = {eleof}
ORDER BY tci.class_instance_id asc
""".format(pid = pid, eleof = eleofid)
c.exec... |
GoogleCloudPlatform/appengine-python-standard | src/google/appengine/api/api_testutil.py | Python | apache-2.0 | 6,637 | 0.004821 | #!/usr/bin/env python
#
# Copyright 2007 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... | stub_map.apiproxy.RegisterStub('datastore_v3', self.datastore_stub)
apiproxy_stub_map.apiproxy.RegisterStub('da | tastore_v4',
self.datastore_v4_stub)
if _CLOUD_DATASTORE_ENABLED:
helper = datastore_pbs.googledatastore.helper
disable_cred_env = helper._DATASTORE_USE_STUB_CREDENTIAL_FOR_TEST_ENV
os.environ[disable_cred_env] = 'True'
apiproxy_stub_map.apiproxy.R... |
wolrah/arris_stats | arris_scraper.py | Python | mit | 5,303 | 0.002829 | #!/usr/bin/env python
# A library to scrape statistics from Arris CM820 and similar cable modems
# Inspired by https://gist.github.com/berg/2651577
import BeautifulSoup
import requests
import time
cm_time_format = '%a %Y-%m-%d %H:%M:%S'
def get_status(baseurl):
# Retrieve and process the page from the modem
... | loat(cols[3].string.strip().split()[0])
snr = float(cols[4].string.strip().split()[0])
modulat | ion = cols[5].string.strip()
octets = int(cols[6].string.strip())
corrected_errors = int(cols[7].string.strip())
uncorrectable_errors = int(cols[8].string.strip())
channelstats = {'modem_channel': modem_channel,
'dcid': docsis_channel,
... |
TRex22/Sick-Beard | sickbeard/notifiers/growl.py | Python | gpl-3.0 | 5,949 | 0.014456 | # Author: Nic Wolfe <[email protected]>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lice... | ])
#Optional
if options['sticky']:
notice.add_header('Notification-Sticky',options['sticky'])
if options['priority']:
notice.add_header('Notification-Priority',options['priority'])
if options['icon']:
notice.add_header('Notification-Icon', 'https:... | aster/data/images/sickbeard.png')
if message:
notice.add_header('Notification-Text',message)
response = self._send(options['host'],options['port'],notice.encode(),options['debug'])
if isinstance(response,gntp.GNTPOK): return True
return False
def _send(self, host,p... |
indarsugiarto/Graceful_TG_SDP | QtForms/tgxmlParser.py | Python | gpl-3.0 | 2,868 | 0.003487 | import xml.sax
import string
class cDep(object):
def __init__(self):
self.srcId = None
self.nTriggerPkt = None
class cTarget(object):
def __init__(self):
self.destId = None
self.nPkt = None
self.nDependant = 0
self.Dep = list() # this will contain a list o... | = "dependency":
self.Dependencie | s[self.CurrentDep] = self.D
self.CurrentDep += 1
self.CurrentElement = ""
# call when a character is read
def characters(self, content):
if self.CurrentElement == "nodeId":
self.Nodes[self.NumberOfNodes].Id = int(content)
if self.CurrentElement == "targetId":
... |
knuu/competitive-programming | codeforces/cdf256_2d.py | Python | mit | 308 | 0.006494 | def calc(x):
ret = 0
for i in range(N):
ret += min(M, x // (i+1))
retu | rn ret
N, M, K = map(int, input().split())
N, M = sorted([N, M])
low, hig | h = 0, K+1
while high - low > 1:
mid = (low + high) // 2
if calc(mid) < K:
low = mid
else:
high = mid
print(high)
|
usc-isi-i2/graph-keyword-search | src/resourceGraph.py | Python | apache-2.0 | 2,182 | 0.030247 | from collections import OrderedDict
# Model class for resource elements
class Resource:
def __init__(self,uri,label,support,keyword):
self.uri = uri # URI of the resource.
self.label = label # Label of the resource
self.support = int(support) # Importance/ represents the number ... | sources
# Eg.
# Fact_node triple -> dbPedia:Bill_Gates dbPedia:spouse dbPedia:Melinda_Gates
# dbPedia:Bill_Gates covers colors 2,3
# dbPedia:spouse covers colours 1
# dbPedia:Melinda_Gates covers | 1,2,3
# then the fact node covers 1,2,3
def set_colors(self):
for color in self.subject.colors:
if(color not in self.colors):
self.colors.append(color)
for color in self.predicate.colors:
if(color not in self.colors):
self.colors.append(color)
for color in self.object.colors:
if(c... |
simonenkong/python_training_mantis | fixture/signup.py | Python | gpl-2.0 | 928 | 0.003233 | __author__ = 'Nataly'
import re
class SignupHelper:
def __init__(self, app):
self.app = app
def new_user(self, username, email, password):
wd = self.a | pp.wd
wd.get(self.app.base_url + "/signup_page.php")
wd.find_element_by_name("username").send_keys(username)
wd.find_e | lement_by_name("email").send_keys(email)
wd.find_element_by_css_selector('input[type="submit"]').click()
mail = self.app.mail.get_mail(username, password, "[MantisBT] Account registration")
url = self.extract_confirmation_url(mail)
wd.get(url)
wd.find_element_by_name("password"... |
tzhaoredhat/automation | pdc/apps/package/tests.py | Python | mit | 88,111 | 0.00286 | #
# Copyright (c) 2015 Red Hat
# Licensed under The MIT License (MIT)
# http://opensource.org/licenses/MIT
#
from django.test import TestCase
from rest_framework.test import APITestCase
from rest_framework import status
from django.core.urlresolvers import reverse
from django.core.exceptions import ValidationError
fro... | version='3.19.3', release='100',
arch='src', srpm_name='kernel', filename='kernel-3.19.3-100.src.rpm',
srpm_nevra='kernel-0:3.19.3-100.src')
self.assertEqual(0, models.RPM.objects.count())
def test_empty_srpm_nevr | a_with_arch_is_not_src(self):
with self.assertRaises(ValidationError):
models.RPM.objects.create(name='kernel', epoch=0, version='3.19.3', release='100',
arch='x86_64', srpm_name='kernel', filename='kernel-3.19.3-100.x86_64.rpm')
self.assertEqual(0, mode... |
DemocracyClub/EveryElection | every_election/apps/elections/tests/factories.py | Python | bsd-3-clause | 2,998 | 0.000334 | import datetime
import factory
from django.db.models import signals
from elections.models import (
Election,
ModerationHistory,
ElectionType,
ElectedRole,
ModerationStatus,
ModerationStatuses,
)
from organisations.tests.factories import (
OrganisationFactory,
OrganisationDivisionFactor... | name = "Local elections"
election_type = "local"
# default_voting_syst | em
class ElectedRoleFactory(factory.django.DjangoModelFactory):
class Meta:
model = ElectedRole
django_get_or_create = ("election_type",)
election_type = factory.SubFactory(ElectionTypeFactory)
organisation = factory.SubFactory(OrganisationFactory)
elected_title = "Councillor"
ele... |
sergeyshilin/Kaggle-Carvana-Image-Masking-Challenge | params.py | Python | mit | 749 | 0.018692 | from model.u_net import get_unet_128, get_unet_256, get_unet_512, get_unet_1024, get_unet_1024_hq, get_unet_1024_heng
import cv2
### These parameters might be changed ###
input_size = 1024
max_epochs = 150
threshold = 0.49
downscale = cv2.INTER_CUBIC
upscale = cv2.INTER_AREA
### These parameters might be changed | ###
orig_width = 1918
orig_height = 1280
batch_size = 12
model_factory = get_unet_128
if input_size == 128:
batch_size = 24
model_factory = get_unet_128
elif input_size == 256:
batch_size = 12
model_factory = get_unet_256
elif input_size == 512:
batch_size = 6
model_factory = get_unet_512
elif input_size == 10... | ze = 3
model_factory = get_unet_1024_hq
downscale = cv2.INTER_LINEAR
upscale = cv2.INTER_LINEAR
|
authurlan/amdfin | server/database/amdfin/tmp_animts.py | Python | gpl-2.0 | 686 | 0 | # -*- coding: utf-8 -*-
from sqlalchemy import select, desc
import const
from ..sqlalchemy_table import SqlTable
class TmpAnimts(SqlTable):
def __init__(self, engine, table):
self.engine = engine
self.table = table
SqlTable.__init__(self, self.engine, self.table, (cons | t.NAME_TAN,))
def add(self, name, start_date, over_date, state, provider_id):
values = {
const.NAME_TAN: name,
const.ST_DATE_TAN: start_date,
const.OV_DATE_TAN: over_date,
const.STATE_TAN: state,
const.PROVIDER_ID_TAN: provider_id
}
... | |
mjabri/holoviews | holoviews/plotting/bokeh/element.py | Python | bsd-3-clause | 24,459 | 0.002126 | from io import BytesIO
import numpy as np
import bokeh
import bokeh.plotting
from bokeh.models import Range, HoverTool
from bokeh.models.tickers import Ticker, BasicTicker, FixedTicker
from bokeh.models.widgets import Panel, Tabs
try:
from bokeh import mpl
except ImportError:
mpl = None
import param
from ...... | param.Boolean(default=False, doc="""
Whether the x-axis of the plot will be a log axis.""")
xrotation = param.Integer(default=None, bounds=(0, 360), doc="""
Rotation angle of the xticks.""")
xticks = param.Parameter(default=None, doc="""
Ticks along x-axis specified as an integer, expl... | bokeh ticking behavior is applied.""")
yaxis = param.ObjectSelector(default='left',
objects=['left', 'right', 'bare', 'left-bare',
'right-bare', None], doc="""
Whether and where to display the yaxis, bare options allow sup... |
gdestuynder/rra2json | rra_parsers/parse_253.py | Python | mpl-2.0 | 6,540 | 0.006422 | from parselib import *
def parse_rra(gc, sheet, name, version, rrajson, data_levels, risk_levels):
'''
called by parse_rra virtual function wrapper
@gc google gspread connection
@sheet spreadsheet
@name spreadsheet name
@version RRA version detected
@rrajson writable template for the JSON fo... | ationales', xmoves=0, ymoves=4)
A.productivity.rationale = cell_value_near(sheet_data, 'Threats, use-cases, rationales', xmoves=0, ymoves=5)
A.finances.rationale = cell_value_near(sheet_data, 'Threats, use-cases, | rationales', xmoves=0, ymoves=6)
I.reputation.rationale = cell_value_near(sheet_data, 'Threats, use-cases, rationales', xmoves=0, ymoves=7)
I.productivity.rationale = cell_value_near(sheet_data, 'Threats, use-cases, rationales', xmoves=0, ymoves=8)
I.finances.rationale = cell_value_near(sheet_data, 'Threats... |
ojengwa/pyScss | conftest.py | Python | mit | 684 | 0.016082 | """py.test plugin configuration."""
def pytest_addoption(parser):
"""Add options for filtering which file tests run.
This has to be done in the project root; py.test doesn't (and can't)
recursively look for conftest.py files until after it's parsed the c | ommand
line.
"""
parser.addoption('--include-ruby',
help='run tests imported from Ruby and sassc, most of which fail',
action='store_true',
dest='include_ruby',
)
parser.addoption('--test-file-filter',
help='comma-separated regexes to select test files',
acti... | re',
type='string',
dest='test_file_filter',
default=None,
)
|
rhdedgar/openshift-tools | scripts/remote-heal/remote-healer.py | Python | apache-2.0 | 7,272 | 0.0022 | #!/usr/bin/python
# vim: expandtab:tabstop=4:shiftwidth=4
'''
Tool to process and take action on incoming zabbix triggers.
'''
# Disabling invalid-name because pylint doesn't like the naming conention we have.
# pylint: disable=invalid-name
# pylint: disable=line-too-long
import argparse
import ConfigParser
import... | .group(0)
def main(self):
''' Entry point for | class '''
logging.info("host: " + self._args.host + " trigger: " +
self._args.trigger + " trigger value: " +
self._args.trigger_val)
# Validate passed in host arg since it will be used for ssh cmds
self.validate_host()
#
# Here we will ... |
mcgonagle/ansible_f5 | library/bigip_qkview.py | Python | apache-2.0 | 12,748 | 0.000784 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | )
if self.want.exclude:
choices = ['all', 'audit', 'secure', 'bash_history']
if not all(x in choices for x in self.want.exclude_raw):
ra | ise F5ModuleError(
"The specified excludes must be in the following list: "
"{0}".format(','.join(choices))
)
self.execute()
def exists(self):
ls = self.client.api.tm.util.unix_ls.exec_cmd(
'run', utilCmdArgs=self.remote_dir
... |
Kriechi/netlib | netlib/http/request.py | Python | mit | 11,925 | 0.002432 | from __future__ import absolute_import, print_function, division
import warnings
import six
from six.moves import urllib
from netlib import utils
from netlib.http import cookies
from netlib.odict import ODict
from .. import encoding
from .headers import Headers
from .message import Message, _native, _always_bytes, M... | self.port = port
self.path = path
self.http_version = http_version
self.headers = headers
self.content = content
self.timestamp_start = timestamp_start
self.timestamp_end = timestamp_end
class Request(Message):
"""
An HTTP request.
"""
def __init__(self,... | *args, **kwargs)
super(Request, self).__init__(data)
def __repr__(self):
if self.host and self.port:
hostport = "{}:{}".format(self.host, self.port)
else:
hostport = ""
path = self.path or ""
return "Request({} {}{})".format(
self.method, ... |
msabramo/PyUMLGraph | src/Gatherer.py | Python | gpl-2.0 | 1,616 | 0.031559 | # $Id: Gatherer.py,v 1.2 2003/10/16 17:25:26 adamf Exp $ $
import types
class Gatherer:
def __init__(self, classesToCollectInfoAbout, classesToIgnore):
self.classesToCollectInfoAbout = classesToCollectInfoAbout
self.classesToIgnore = classesToIgnore
def __repr__(self):
raise "This method sho... | className == "NoneType":
return "None"
else:
return className
def getClassAttributes(self, object):
"private"
re | turn object.__class__.__dict__
def getInstanceAttributes(self, object):
"private"
return object.__dict__
def getMethodName(self, frame):
"private"
return frame.f_code.co_name
def demangleName(self, object, name):
"private"
if type(name) != type(""):
r... |
jeffery9/mixprint_addons | stock_location/procurement_pull.py | Python | agpl-3.0 | 6,951 | 0.005179 | ##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public L... | artner_id': line.partner_address_id.id,
'note': _('Picking for pulled procurement coming from original location %s, pull rule %s, via original Procurement %s (#%d)') % (proc.location_id.name, line.name, proc.name, proc.id),
'invoic | e_state': line.invoice_state,
})
move_id = move_obj.create(cr, uid, {
'name': line.name,
'picking_id': picking_id,
'company_id': line.company_id and line.company_id.id or False,
'product_id': proc.product_id.id,
'da... |
JioCloud/cinder | cinder/volume/drivers/emc/emc_vmax_fc.py | Python | apache-2.0 | 13,846 | 0 | # Copyright (c) 2015 EMC Corporation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | = self.common.initialize_connection(
volume, connector)
device_number = device_info['hostlunid']
storage_system = device_info['storagesystem']
target_wwns, init_targ_map = self._build_initiator_target_map(
storage_system, volume, connector)
data = {'driver_volume... | number,
'target_discovered': True,
'target_wwn': target_wwns,
'initiator_target_map': init_targ_map}}
LOG.debug("Return FC data for zone addition: %(data)s.",
{'data': data})
return data
@fczm_utils.Remov... |
Jean-Simon-Barry/djangoproject | djangoproject/settings.py | Python | gpl-2.0 | 2,131 | 0 | """
Django settings for djangoproject project.
For more information on this file, see
https://docs.djangoproject.c | om/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build pat | hs inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in productio... |
Zulan/PBStats | tests/Updater/Mods/Updater/Assets/Python/Extras/simplejson.py | Python | gpl-2.0 | 33,784 | 0.007134 | import sre_parse, sre_compile, sre_constants
from sre_constants import BRANCH, SUBPATTERN
from re import VERBOSE, MULTILINE, DOTALL
import re
import cgi
import warnings
_speedups = None
class JSONFilter(object):
def __init__(self, app, mime_type='text/x-json'):
self.app = app
self.mi... | | int, long, float | number |
+-------------------+---------------+
| True | true |
+-------------------+---------------+
| False | false |
+-------------------+---------------+
| None | null |
+----------------... | r ``o`` if possible, otherwise it should call the superclass
implementation (to raise ``TypeError``).
"""
item_separator = ', '
key_separator = ': '
def __init__(self, skipkeys=False, ensure_ascii=True,
check_circular=True, allow_nan=True, sort_keys=False,
indent=None,... |
sklam/numba | numba/core/imputils.py | Python | bsd-2-clause | 14,752 | 0.000542 | """
Utilities to simplify the boilerplate for native lowering.
"""
import collections
import contextlib
import inspect
import functools
from enum import Enum
from numba.core import typing, types, utils, cgutils
from numba.core.typing.templates import BaseRegistryLoader
class Registry(object):
"""
A registr... | return wrapper
class _IternextResult(object):
| """
A result wrapper for iteration, passed by iternext_impl() into the
wrapped functio |
m-labs/llvmlite | llvmlite/ir/module.py | Python | bsd-2-clause | 4,930 | 0 | from __future__ import print_function, absolute_import
from . import context, values, types, _utils
class Module(object):
def __init__(self, name='', context=context.global_context):
self.context = context
self.name = name # name is for debugging/informational
self.globals = {}
s... | on type if omitted for common cases
elif len(tys) == 0 and intrinsic == 'llvm.assume':
fnty = types.FunctionType(types.VoidType(), [t | ypes.IntType(1)])
elif len(tys) == 1:
if intrinsic == 'llvm.powi':
fnty = types.FunctionType(tys[0], [tys[0], types.IntType(32)])
elif intrinsic == 'llvm.pow':
fnty = types.FunctionType(tys[0], tys*2)
else:
fnty = types.Function... |
timvideos/flumotion | flumotion/test/test_component_padmonitor.py | Python | lgpl-2.1 | 3,361 | 0.000298 | # -*- Mode: Python; test-case-name: flumotion.test.test_feedcomponent010 -*-
# vi:si:et:sw=4:sts=4:ts=4
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L.
# Copyright (C) 2010,2011 Flumotion Services, S.A.
# All rights reserved.
#
# This file may be distributed and/or mo... | 'src')
# Now give the reactor a chance to process the callFromThread()
def finished():
monitor.detach()
d.callback(True)
def hasInactivated(name):
# We can't detach the monitor from this callback safely, so do
# it from a reactor.callLater()
... | def hasActivated():
self.assertEquals(monitor.isActive(), True)
# Now, we don't send any more data, and after our 0.5 second
# timeout we should go inactive. Pass our test if that happens.
# Otherwise trial will time out.
monitor = padmonitor.PadMonitor(srcpa... |
ArabellaTech/drf_tweaks | tests/test_lock_limiter.py | Python | mit | 2,776 | 0.001081 | # -*- coding: utf-8 -*-
import pytest
from django.conf.urls import url
from django.http import HttpResponse
from django.test import override_settings
from drf_tweaks.test_utils import (
query_lock_limiter,
DatabaseAccessLintingApiTestCase,
WouldSelectMultipleTablesForUpdate,
)
from tests.models import Samp... | ng_whitelisted_multiple_tables():
whitelist = [["tests_samplemodel", "tests_samplemodelwithfk"]]
with query_lock_limiter(enable=True, whitelisted_table_sets=whitelist):
list(SampleModelWithFK.objects.filter(parent__ | a="").select_for_update())
@pytest.mark.django_db
def test_query_select_related_and_for_update():
with pytest.raises(WouldSelectMultipleTablesForUpdate):
with query_lock_limiter(enable=True):
list(SampleModelWithFK.objects.select_related().select_for_update())
def grabby_select_view(request)... |
hotsyk/conferencio | conferencio/event/tests/factories.py | Python | bsd-3-clause | 1,534 | 0.001956 | import datetime
from django.contrib.auth import get_user_model
import factory
from .. import models
class UserFactory(factory.Factory):
class Meta:
model = get_user_model()
first_name = 'John'
last_name = 'Doe'
email = '[email protected]'
class EventCountryFactory(factory.Factory):
class ... | ityFactory.create()
| context = {'some_context': 1}
kind = EventKindFactory.create()
ts_start = datetime.datetime.now() + datetime.timedelta(days=5)
ts_end = ts_start + datetime.timedelta(days=7)
schedule = {'Day 1': {'Stage 1': [{'9:00': "Registration"}]}}
series = EventSeriesFactory.create()
venue = {'title': 'My... |
azilya/Zaliznyak-s-grammatical-dictionary | gdictionary/postprocessing.py | Python | lgpl-3.0 | 7,574 | 0.008666 | #Special rules for nouns, to avoid suggesting wrong lemmas. Nothing is done for other POS.
import pymorphy2
blacklist1 = ['ъб', 'ъв', 'ъг', 'ъд', 'ъж', 'ъз', 'ък', 'ъл', 'ъм', 'ън', 'ъп', 'ър', 'ъс', 'ът', 'ъф', 'ъх', 'ъц', 'ъч', 'ъш', 'ъщ', 'йй', 'ьь', 'ъъ', 'ыы', 'чя', 'чю', 'чй', 'щя', 'щю', 'щй', 'шя', 'шю', 'шй',... | ound[i][-4:] in female3):
fixednames.append(found[i][:-4] + 'ева')
elif (found[i].istitle()) and (found[i][-4:] in female4):
fix | ednames.append(found[i][:-4] + 'ина')
elif (found[i].istitle()) and (found[i][-4:] in male1):
fixednames.append(found[i][:-2] + 'ий')
elif (found[i].istitle()) and (found[i][-5:] in male2):
fixednames.append(found[i][:-3] + 'ий')
elif (found[i].istitle... |
fintech-circle/edx-platform | lms/djangoapps/mobile_api/admin.py | Python | agpl-3.0 | 946 | 0.002114 | """
Django admin dashboard configuration for LMS XBlock infrastructure.
"""
from django.contrib import admin
from config_models.admin import ConfigurationModelAdmin
from .models import (
AppVersionConfig,
MobileApiConfig,
IgnoreMobileAvailableFlagConfig
)
admin.site.register(MobileApiConfig, Configuration... | ersion', 'expire_at', 'enabled')
list_filter = ['platform']
class Meta(object):
| ordering = ['-major_version', '-minor_version', '-patch_version']
def get_list_display(self, __):
""" defines fields to display in list view """
return ['platform', 'version', 'expire_at', 'enabled', 'created_at', 'updated_at']
admin.site.register(AppVersionConfig, AppVersionConfigAdmin)
|
sametmax/Django--an-app-at-a-time | ignore_this_directory/django/contrib/auth/decorators.py | Python | mit | 2,892 | 0.000692 | from functools import wraps
from urllib.parse import urlparse
from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.core.exceptions import PermissionDenied
from django.shortcuts import resolve_url
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_... | red(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
"""
Decorator for views that checks that the user is logged in, redirecting
to the log-in page if necessary.
"""
actual_decorator = user_passes_test(
lambda u: u.is_authenticated,
login_url=login_url,
... | orator(function)
return actual_decorator
def permission_required(perm, login_url=None, raise_exception=False):
"""
Decorator for views that checks whether a user has a particular permission
enabled, redirecting to the log-in page if necessary.
If the raise_exception parameter is given the Permissi... |
jacobtomlinson/datapoint-python | datapoint/_version.py | Python | gpl-3.0 | 18,444 | 0 |
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains t... | EnvironmentError:
pass
return keywords
@register_vcs_handler("git", "keywords")
def git_versions_from_keywords(keywords, tag_prefix, verbose):
"""Get version information from git keywords."""
if not keywords:
raise NotThisMethod("no keywords at all, weird")
date = keywords.get("date")... | O-8601
# -like" string, which we must then edit to make compliant), because
# it's been around since git-1.5.3, and it's too difficult to
# discover which version we're using, or to work around using an
# older one.
date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
... |
brenolf/myfriend | dogs/migrations/0017_auto__add_field_dog_abandoned__chg_field_dog_gender__chg_field_dog_bre.py | Python | apache-2.0 | 14,562 | 0.008035 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Dog.abandoned'
db.add_column(u'dogs_dog', 'abandoned',
self.gf('django... | ('django.db.mode | ls.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", '... |
tum-pbs/PhiFlow | phi/jax/_jax_backend.py | Python | mit | 16,438 | 0.002008 | import numbers
import warnings
from functools import wraps, partial
from typing import List, Callable
import logging
import numpy as np
import jax
import jax.numpy as jnp
import jax.scipy as scipy
from jax.core import Tracer
from jax.interpreters.xla import DeviceArray
from jax.scipy.sparse.linalg import cg
from jax i... |
return jax_fun
def divide_no_nan(self, x, y):
return jnp.nan_to_num(x / y, copy=True, nan=0)
def random_uniform(self, shape):
self._check_float64()
self.rnd_key, subkey = jax.random.split(self.rnd_key)
return random.uniform(subkey, shape, dtype=to_numpy_dtype(self.floa... | om_normal(self, shape):
self._check_float64()
self.rnd_key, subkey = jax.random.split(self.rnd_key)
return random.normal(subkey, shape, dtype=to_numpy_dtype(self.float_type))
def range(self, start, limit=None, delta=1, dtype: DType = DType(int, 32)):
if limit is None:
st... |
Kagiso-Future-Media/django-intercom | docs/conf.py | Python | bsd-3-clause | 9,137 | 0.007771 | # -*- coding: utf-8 -*-
#
# django-intercom documentation build configuration file, created by
# sphinx-quickstart on Mon Jan 23 13:50:08 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.... | here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master | toctree document.
master_doc = 'index'
# General information about the project.
project = u'django-intercom'
copyright = u'2012, Ken Cochrane'
# 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.
... |
google-research/google-research | genomics_ood/images_ood/train.py | Python | apache-2.0 | 8,869 | 0.006765 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | x'],
use_weight_norm=params['use_weight_norm'],
rescale_pixel_value=params['rescale_pixel_value'],
)
# Define the training loss and optimize | r
log_prob_i = dist.log_prob(tr_in_im['image'], return_per_pixel=False)
loss = -tf.reduce_mean(log_prob_i)
log_prob_i_val_in = dist.log_prob(val_in_im['image'])
loss_val_in = -tf.reduce_mean(log_prob_i_val_in)
global_step = tf.compat.v1.train.get_or_create_global_step()
learning_rate = tf.compat.v1.train.... |
jmdevince/cifpy3 | lib/cif/client/formatters/csv.py | Python | gpl-3.0 | 573 | 0.001745 | import csv
__author__ = "Aaron Eppert <[email protected]>"
de | f process(options, results, output_handle):
headers = options['select'].split(',')
writer = csv.writer(output_handle)
writer.writerow(headers)
for result in results:
row = []
for header in headers:
if header in result:
if isinstance(result[header], list):
... | )
writer.writerow(row) |
Dawny33/Code | HackerEarth/BeCoder 2/nine.py | Python | gpl-3.0 | 882 | 0.014739 |
from itertools import combinations
def is_good(n):
return 1 + ((int(n) - 1) % 9) == 9
def generate_subsequences(n):
subsequences = | []
combinations_list = []
index = 4
#Generate all combinations
while index > 0:
combinations_list.append(list(combinations(str(n), index)))
index -= 1
#Formatting combinations
for index in combinations_list:
for combination in index:
subsequences.append(''.join(combin... | )
#Get number of cases
cases = int(raw_input())
while cases > 0:
value = raw_input()
good_subsequences = 0
for sub in generate_subsequences(value):
if is_good(sub):
good_subsequences += 1
print (good_subsequences % modulo)-1
cases -= 1
|
xbmc/atv2 | xbmc/lib/libPython/Python/Lib/plat-mac/Carbon/Aliases.py | Python | gpl-2.0 | 407 | 0.002457 | # Generated from 'Aliases.h'
def FOUR_CH | AR_CODE(x): return x
true = True
false = False
rAliasType = FOUR_CHAR_CODE('alis')
kARMMountVol = 0x00000001
kARMNoUI = 0x00000002
kARMMultVols = 0x00000008
kARMSearch = 0x00000100
kARMSearchMore = 0x00000200
kARMSearchRelFirst = 0x00000400
asiZoneName = -3
asiServerName = -2
asiVolumeName = -1
asiAliasName | = 0
asiParentName = 1
kResolveAliasFileNoUI = 0x00000001
|
Guanghan/ROLO | update/unit_test/test_utils_io_list.py | Python | apache-2.0 | 2,578 | 0.003491 | import sys, os
sys.path.append(os.path.abspath("../utils/"))
from utils_io_list import *
from test_utils_io_folder import *
def test_generate_pairs_for_each_folder():
images_folder_path= "folder/path/example"
num_of_frames = 2
pairs = generate_pairs_for_each_folder(images_folder_path, num_of_frames)
... | else:
return False
def test_generate_num_of_frames_list():
folders_paths_list = ['../temp_folder_1', '../temp_folder_2']
for folder_path in folders_paths_list:
create_folder(folder_path)
create_dummy_files_in_folder(folder_path)
num_of_frames_list = generate_num_of_frames_li | st(folders_paths_list)
for folder_path in folders_paths_list:
shutil.rmtree(folder_path)
expected_list = [10, 10]
if expected_list == num_of_frames_list:
return True
else:
return False
def test_generate_pairs_with_two_lists():
folders_paths_list = ['../temp_folder_1', '..... |
apehua/pilas | pilasengine/actores/bala.py | Python | lgpl-3.0 | 1,431 | 0.000702 | # -*- encoding: utf-8 -*-
# Pilas engine - A video game framework.
#
# Copyright 2010 - Hugo Ruscitti
# License: LGPLv3 (see http://www.gnu.org/licenses/lgpl.html)
#
# Website - http://www.pilas-engine.com.ar
from pilasengine.actores.actor import Actor
class Bala(Actor):
""" Representa una bala que va en línea ... | :param x: Posición x del proyectil.
:param y: Posición y del proyectil.
:param velocidad_maxima: Velocidad máxima que alcanzará el proyectil.
:param angulo_de_movimiento: Angulo en que se moverá el Actor..
"""
super(Bala, self).__init__(pilas=pilas, x=x, y=y)
self.imag... | png')
self.rotacion = rotacion
self.radio_de_colision = 5
self.hacer(pilas.comportamientos.Proyectil,
velocidad_maxima=velocidad_maxima,
aceleracion=1,
angulo_de_movimiento=angulo_de_movimiento,
gravedad=0)
se... |
SamWhited/photoshell | photoshell/views/photo_exporter.py | Python | mit | 1,432 | 0 | import os
from gi.repository import Gtk
from wand.image import Image
class PhotoExporter(Gtk.FileChooserDialog):
def __init__(self, window):
super(PhotoExporter, self).__init__(
'Export photo',
window,
Gtk.FileChooserAction.SAVE,
| (
Gtk.STOCK_CANCEL,
Gtk.ResponseType.CANCEL,
'Save',
Gtk.ResponseType.OK,
),
)
self._window = window
def export_photo(self, photo):
# TODO: photo is actually an photoshell.image.Image
response = s... | filename = None
def write_image(photo, format, filename):
# TODO: Export the full sized photo, not the preview.
with Image(filename=photo.developed_path) as image:
image.format = format
image.save(filename=filename)
if filename and resp... |
quantumlib/Cirq | cirq-core/cirq/work/observable_grouping.py | Python | apache-2.0 | 3,492 | 0.001432 | # Copyright 2020 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | )
new_max_weight_obs = _max_weight_observable(
stg.observable for stg in trial_grouped_settings
)
compatible_init_state = new_max_weight_state is not None
com | patible_observable = new_max_weight_obs is not None
can_be_inserted = compatible_init_state and compatible_observable
if can_be_inserted:
new_max_weight_state = cast(value.ProductState, new_max_weight_state)
new_max_weight_obs = cast(ops.PauliString, new_max_weigh... |
AustinTSchaffer/DailyProgrammer | AdventOfCode/2018/src/day-04/app.py | Python | mit | 4,830 | 0.004141 | import os
import re
from collections import defaultdict
from datetime import datetime
class Event(object):
def __init__(self, log_text):
# [1518-09-17 23:48] Guard #1307 begins shift
# [1518-09-17 23:48] falls asleep
# [1518-09-17 23:48] wakes up
self.raw_log = log_text
ma... |
class Guard(object):
def __init__(self, guard_id, shifts):
self.id = guard_id
self.shifts = shifts
def total_minutes_asleep(self):
return sum(map(
lambda shift: len(shift.minutes_asleep),
self.shifts
))
def minute_asleep_frequency(self):
... | h
minute. `{25: 4}` means that the guard was asleep at 12:25 on 4
separate occasions.
"""
minutes_asleep = defaultdict(int)
for shift in self.shifts:
for minute in shift.minutes_asleep:
minutes_asleep[minute] += 1
return minutes_asleep
def... |
skirpichev/omg | diofant/solvers/solvers.py | Python | bsd-3-clause | 50,763 | 0.000296 | """
This module contain solvers for all kinds of equations,
algebraic or transcendental.
"""
import warnings
from collections import defaultdict
from types import GeneratorType
from ..core import (Add, Dummy, E, Equality, Expr, Float, Function, Ge, I,
Integer, Lambda, Mul, Symbol, expand_log, expa... | : bool, optional
If False, don't do any testing of solutions. Default is
True, i.e. the solutions are checked and those that doesn't
satisfy given assumptions on symbols solved for or make any
denominator zero - are automatically excluded.
warn : bool, optional
... | (default) for all but polynomials of
order 3 or greater before returning them and (if check is
not False) use the general simplify function on the solutions
and the expression obtained when they are substituted into the
function which should be zero.
rational : bo... |
HewlettPackard/python-hpICsp | setup.py | Python | mit | 1,625 | 0.000615 | ###
# (C) Copyright 2014 Hewlett-Packard Development Company, L.P
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, cop... | e, and/or sell
# copies of the Software, and to permit persons to whom the S | oftware is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED T... |
mediawiki-utilities/python-mwbase | mwbase/statement.py | Python | mit | 987 | 0 | from . import claim, util
from .attr_dict import AttrDict
class Statement(AttrDict):
@classmethod
def from_json(cls, statement_doc):
return normalize(statement_doc)
def normalize(statement_doc):
statement_doc = util.ensure_decoded_json(statement_doc)
references = {}
f | or item in statement_doc.get('references', []):
for pid, ref_docs in item['snaks'].items():
references[pid] = [claim.normalize(ref_doc)
for ref_doc in ref_docs]
return Statement({
'id': statement_doc.get('id'),
'hash': statement_doc.get('hash'),
... | k']),
'rank': statement_doc.get('rank', None),
'references': references,
'qualifiers': {
prop: [claim.normalize(qualifier_doc)
for qualifier_doc in statement_doc['qualifiers'][prop]]
for prop in statement_doc.get('qualifiers-order', [])}
})
|
delron-kung/Tornado-iHome | handlers/verfiycode.py | Python | gpl-3.0 | 3,911 | 0.00141 | # coding:utf-8
import logging
import constants
import types
import random
import re
from utils.captcha.captcha import captcha
from lib.yuntongxun import sms
from handlers.base import BaseHandler
from utils.response_code import RET
class ImageCodeHandler(BaseHandler):
"""图片验证码"""
def get(self):
# 获取前... | try:
self.redis.delete("ImageCode" + image_code_id)
except Exception as e:
logging.error(e)
# 判断验证码是否正确
if not isinstance(image_code, types.StringType):
image_code = str(image_code)
if not isinstance(real_image_code, types.StringType):
... | r():
return self.write({"errno": RET.PARAMERR, "errmsg": "图片验证码错误"})
# 判断手机号是否注册过
try:
sql = "select count(*) counts from ih_user_profile where up_mobile=%(mobile)s"
res = self.db.get(sql, mobile=mobile)
except Exception as e:
logging.error(e)
... |
albert-decatur/gis-utils | selectByAttributes.py | Python | mit | 909 | 0.009901 | #!/usr/bin/python
# use ogr to make a new shapefile with select by attributes
# note that 'ogr2ogr -sql' is way awesomer
# t | his script was nearly written by http://gis.stackexchange.com/ user Luke: http://gis.stackexchange.com/questions/68650/ogr-how-to-save-layer-from-attributefilter-to-a-shape-filter
# example use: selectByAttributes.py parks.shp 'PARK_TYPE2 = "Park"' new.shp
from osgeo import ogr
import sys
import os
inds = ogr.Open(sys... | utes
inlyr.SetAttributeFilter(sys.argv[2])
drv = ogr.GetDriverByName( 'ESRI Shapefile' )
# if output shp exists delete it
if os.path.exists(sys.argv[3]):
drv.DeleteDataSource(sys.argv[3])
outds = drv.CreateDataSource(sys.argv[3])
# get basename (layer name) of output shp
basename = os.path.basename(sys.argv[3])
outlyr... |
tensorflow/tensorflow | tensorflow/python/ops/ragged/ragged_eager_test.py | Python | apache-2.0 | 2,223 | 0.002699 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 1999]]'),
dict(pylist=[[[0, 1]], [np.arange(2, 2000)]],
expected_str='[[[0, 1]],\n [[2, 3, 4, ..., 1997, 1998, 1999]]]'),
])
def testRaggedTensorStr(self, pylist, expected_str):
rt = ragged_factory_ops.constant(pylist)
self.a | ssertEqual(str(rt), f'<tf.RaggedTensor {expected_str}>')
if __name__ == '__main__':
ops.enable_eager_execution()
googletest.main()
|
bonsai-team/matam | scripts/fasta_name_filter.py | Python | agpl-3.0 | 4,067 | 0.001475 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
FastaNameFilter
Description: Filter a fasta file based on a string to find in the
sequences headers, or given a file with a list of id
fastaNameFilter.py -i input.fa -o output.fa -s "stringtofind"
fastaNameFilter.py -i input.fa -o output.fa -f seq... | right 2014-2016 Pierre Pericard
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License | , or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even 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 ... |
jfsantos/maracas | tests/test_add_noise.py | Python | mit | 663 | 0.003017 | from maracas import add_noise, asl_meter, rms_energy
from maracas.utils import wavread
import numpy as np
def test_add_noise_rms():
x, fs = wavread('tests/sp10.wav')
n, _ = wavread('tests/ssn.wav')
y, n_scaled = add_noise(x, n, fs, 5.0)
snr = rms_energy(x) - rms_energy(n_scaled)
assert np.isclos... |
y, n_scaled = add_noise(x, n, fs, 5.0, spee | ch_energy='P.56')
snr = asl_meter(x, fs) - rms_energy(n_scaled)
assert np.isclose(snr, 5.0)
if __name__ == '__main__':
test_add_noise_rms()
test_add_noise_p56()
|
antoniov/tools | zerobug/tests/conftest.py | Python | agpl-3.0 | 1,553 | 0 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
# content of conftest.py
from future import standard_library
# from builtins import * # noqa: F403
from python_plus import _u
f... | trip().strip('"').strip("'")
def _version_to_test(package, version, mode=None):
"""check for version of module/p | ackage
@package: pypi package or external command
@version: version to test
@mode may be:
'' = use package.version() - This is the default mode
'.' = use grep to find 1st occurrence of __version__=
'-V' = exec 'package -V'
'-v' = exec 'package -v'
... |
tomkelly000/youtubeAlbumConverter | youtubeAlbumParser.py | Python | mit | 1,807 | 0.016602 | ''' youtubeAlbumParser.py
A python script for parsing a youtube album into individual songs
First argument is url of video
Second argument is the name for the songs
Tom Kelly '''
from bs4 import * # beautiful soup
import sys
import urllib2
import re
try:
url = sys.argv[1]
except:
url = raw_input('... | .string):
times.append(tag.string)
newLine = False
index = url.find('=')
videoID = url[index+1:]
index = videoID.find('&')
if index > 0:
videoID = videoID[:i | ndex]
import subprocess
subprocess.call(['youtube-dl', '--extract-audio', '--id', url]) # convert the video
def seconds(time):
digits = time.split(':')
if len(digits) < 2:
return int(time)
if len(digits) < 3:
return 60 * int(digits[0]) + int(digits[1])
else:
return 60 * 60 * int(digits[0]) + 60 *... |
jpriebe/qooxtunes | addon/python/file_exporter.py | Python | gpl-3.0 | 2,670 | 0.011236 | import shutil
import os
import errno
class file_exporter:
def __init__(self):
self.error_message = ''
def get_error_message (self):
return self.error_message
def tally_path_segments (self, file):
while (file != ''):
(first, last) = os.path.split (file)
if... | ying file..."
try:
shutil.copy2(file.encode ('utf-8'), export_file.encode ('utf-8'))
except OSError as e:
self.error_message = " | Could not copy '" + file.encode ('utf-8') + "' to '" + export_file.encode ('utf-8') + "': " + e.strerror
return False
return True
|
alviproject/alvi | alvi/client/containers/binary_tree.py | Python | mit | 2,017 | 0.000496 | from . import tree
class Node:
def __init__(self, container, parent, value=None):
self._node = tree.Node(container, parent, value)
@property
def _container(self):
return self._node._container
@property
def id(self):
return self._node.id
@property
def value(self):... | lue):
self._node.value = value
def _create_children(self):
left = Node(self._container, self)
right = Node(self._container, self)
self._children = [left, right]
return self._children
def _create_child(self, index, value):
try:
children = self._childr... | = self._create_children()
children[index].value = value
return children[index]
def create_left_child(self, value):
return self._create_child(0, value)
def create_right_child(self, value):
return self._create_child(1, value)
def _child(self, index):
try:
... |
aaronjwood/multilib | Python/http/request/Get.py | Python | gpl-3.0 | 550 | 0.016364 | import urllib2
import HttpRequest
class Get(HttpRequest.HttpRequest):
data = None
def __i | nit__(self, data):
self.data = self._setData(data)
def sendRequest(self, url):
return urllib2.urlopen(url+self.data).read()
def _setData(self, data):
queryString = "?"
for(key, value) in data.iteritems():
queryString += urllib2.quote(key) + ... | rip("&")
return queryString |
PieterMostert/Lipgloss | model/lipgloss/restrictions.py | Python | gpl-3.0 | 13,939 | 0.020159 | # LIPGLOSS - Graphical user interface for constructing glaze recipes
# Copyright (C) 2017 Pieter Mostert
# 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, version 3 of the License.
# This progra... | ptions
for widget in [self.left_label, self.lower_bound, self.upper_bound, self.calc_bounds[-1], self.calc_bounds[1],
self.right_label]:
widget.grid_forget()
def display_calc_bounds(self):
for eps | in [-1, 1]:
self.calc_bounds[eps].config(text=('%.' + str(self.dec_pt) + 'f') % self.calc_value[eps])
# SECTION 3
#
# Define Other_Attribute class and initialize other attributes
##
##class Other_Attribute:
##
## def __init__(self, name, pos):
## 'LOI, cost, clay, etc'
##
## self.n... |
pri22296/yaydoc | modules/scripts/extensions/blog.py | Python | gpl-3.0 | 1,407 | 0.013504 | from docutils import nodes
from docutils.parsers import rst
from uuid import uuid4
class feed(nodes.General, nodes.Element):
pass
def visit(self, node):
id = str(uuid4())
tag =u'''
<h4>Latest blogs</h4>
<div id="{0}"></div>
<script>
feednami.load("{1}")
.then(function (resul... | eednami/feednami-client-v1.1.js")
app.add_node(feed, html=(visit, depart))
app. | add_directive('feed', feedDirective)
|
newsters/coinrail | sell.py | Python | mit | 1,249 | 0.022562 | """
일반매도
"""
import base64
import simplejson as json
import hashlib
import hmac
import httplib2
import time
ACCESS_KEY = ''
SECRET_KEY = ''
currency = 'btc-krw'
def get_encoded_payload(payload):
dumped_json = json.dumps(payload)
encoded_json = base64.b64encode(dumped_json)
return encoded_json
def get_signature... | }
response = get_response(url, payload)
print response
content = json.loads(response)
return content
if | __name__ == "__main__":
print limit_sell() |
prio/pyconie | wordcount/multilang/resources/wordcount.py | Python | bsd-3-clause | 326 | 0.006135 | from collections import defaultdict
import storm
class WordCountBolt(storm.BasicBolt):
| def initialize(self, conf, context):
self._count = defaultdict(int)
def process(self, tup):
word = tup.values[0]
self._count[word] += 1
storm.emit([word, self._count[word]] | )
WordCountBolt().run()
|
carthage-college/django-djspace | djspace/bin/applications.py | Python | mit | 543 | 0.009208 | import django
django.setup()
from django.contrib.auth.models import User
users = User.objects.all().order_by("last_name")
program = None
exports = []
for user in users:
try:
apps = user.profile.applications.all()
except:
apps = None
if apps:
for a in apps:
#print a
... | #print a.all()
# #print a.get_related_models() | |
pepeportela/edx-platform | cms/djangoapps/contentstore/push_notification.py | Python | agpl-3.0 | 2,773 | 0.001803 | """
Helper methods for push notifications from Studio.
"""
from logging import exception as log_exception
from uuid import uuid4
from django.conf import settings
from contentstore.models import PushNotificationConfig
from contentst | ore.tasks import push_course_update_task
from parse_rest.connection import register
from parse_rest.core import ParseError
from parse_rest.installation import Push
from xmodule.modulestore.django import modulestore
def push_notification_enabled():
"""
Returns whether the push notification feature is enabled. |
"""
return PushNotificationConfig.is_enabled()
def enqueue_push_course_update(update, course_key):
"""
Enqueues a task for push notification for the given update for the given course if
(1) the feature is enabled and
(2) push_notification is selected for the update
"""
if push_not... |
hzlf/openbroadcast.org | website/apps/atracker/api/event.py | Python | gpl-3.0 | 4,386 | 0.001368 | import logging
from atracker.models import Event
from atracker.util import create_event
from django.conf.urls import url
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from tastypie.authentication import (
MultiAuthentication,
Authentication,
Sessi... | t)
return self.create_resp | onse(request, bundle)
|
open-austin/influence-texas | src/config/wsgi.py | Python | gpl-2.0 | 1,920 | 0.001563 | """
WSGI config for influencetx project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATIO... | daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production")
# This application object is used by any WSGI server configured to use this
# file. This | includes Django's development server, if the WSGI_APPLICATION
# setting points here.
application = get_wsgi_application()
#if os.environ.get('DJANGO_SETTINGS_MODULE') == 'config.settings.production':
# application = Sentry(application)
# Apply WSGI middleware here.
#from influencetx.wsgi import influencetx
#applica... |
GuessWhoSamFoo/pandas | pandas/tests/indexes/datetimes/test_astype.py | Python | bsd-3-clause | 13,785 | 0 | from datetime import datetime
import dateutil
from dateutil.tz import tzlocal
import numpy as np
import pytest
import pytz
import pandas as pd
from pandas import (
DatetimeIndex, Index, Int64Index, NaT, Period, Series, Timestamp,
date_range)
import pandas.util.testing as tm
class TestDatetimeIndex(object):
... | f test_astype_datetime64(self):
# GH 13149, GH 13209
idx = DatetimeIndex(['2016-05-16 | ', 'NaT', NaT, np.NaN])
result = idx.astype('datetime64[ns]')
tm.assert_index_equal(result, idx)
assert result is not idx
result = idx.astype('datetime64[ns]', copy=False)
tm.assert_index_equal(result, idx)
assert result is idx
idx_tz = DatetimeIndex(['2016-05-... |
dockerera/func | funcweb/funcweb/tests/test_client_rendering.py | Python | gpl-2.0 | 1,853 | 0.013492 | from funcweb.widget_validation import WidgetSchemaFactory
from funcweb.widget_automation import WidgetListFactory,RemoteFormAutomation,RemoteFormFactory
from func.overlord.client import Overlord, Minions
import socket
import func.utils
class TestClientWidgetRender(object):
minion = None
def test_all_minions(s... | : %s**********"%(self.minion)
fc = Overlord(self.minion)
modules = fc.system.list_modules()
display_modules={}
print "Getting the modules that has exported arguments"
for mo | dule in modules.itervalues():
for mod in module:
#if it is not empty
exported_methods = getattr(fc,mod).get_method_args()[self.minion]
if exported_methods:
print "%s will be rendered"%(mod)
display_modules[mod]=exported_... |
ampafdv/ampadb | importexport/forms.py | Python | mit | 3,163 | 0 | from ampadb.support import Forms
from django import forms
from django.core.exceptions import ValidationError
from . import ies_format
from .ampacsv import InvalidFormat
from .import_fmts import IEFormats
class ExportForm(Forms.Form):
FORMAT_CHOICES = [(IEFormats.CSV, 'CSV (E-mail)'), (IEFormats.AMPACSV,
... | s.PasswordInput)
repeteix_la_contrasenya = forms.CharField(
required=False, widget=forms.PasswordInput)
def clean(self):
cleaned_data = super().clean()
contrasenya = cleaned_data.get('contrasenya')
if contrasenya an | d (contrasenya !=
cleaned_data.get('repeteix_la_contrasenya')):
self.add_error('repeteix_la_contrasenya',
ValidationError('La contrasenya no coincideix'))
class ImportForm(Forms.Form):
FORMAT_CHOICES = [(IEFormats.AUTO, 'Autodetectar'),
... |
thoreg/quiz | quizshowdown/quizshowdown/settings.py | Python | mit | 1,757 | 0 | """
Django settings for quizshowdown project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
INST... | lar-cookie#4.0.2',
'angular-sanitize#1.2.20',
)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.co | ntrib.staticfiles.finders.AppDirectoriesFinder',
'djangobower.finders.BowerFinder',
'compressor.finders.CompressorFinder',
)
|
tojon/treeherder | treeherder/etl/management/commands/publish_to_pulse.py | Python | mpl-2.0 | 1,737 | 0.001727 | import logging
from urlparse import urlparse
from django.core.management.base import BaseCommand
from kombu import (Connection,
E | xchange)
from kombu.messaging import Producer
logger = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Management command to publish a job to a pulse exchange.
This is primarily intended as a mechanism to test new or changed jobs
to ensure they validate and will show as expected in the T... | _arguments(self, parser):
parser.add_argument('routing_key', help="The routing key for publishing. Ex: 'mozilla-inbound.staging'")
parser.add_argument('connection_url', help="The Pulse url. Ex: 'amqp://guest:guest@localhost:5672/'")
parser.add_argument('payload_file', help="Path to the file that... |
endlessm/chromium-browser | tools/nocompile_driver.py | Python | bsd-3-clause | 18,515 | 0.008264 | #!/usr/bin/env python
# Copyright (c) 2011 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.
"""Implements a simple "negative compile" test for C++ on linux.
Sometimes a C++ API needs to ensure that various usages cannot co... | one, then this specifi | es a compiler sanity check test, which
should expect a SUCCESSFUL compilation.
"""
sourcefile = open(sourcefile_path, 'r')
# Start with at least the compiler sanity test. You need to always have one
# sanity test to show that compiler flags and configuration are not just
# wrong. Otherwise, having a mi... |
pointhi/kicad-footprint-generator | scripts/Connector/Connector_JST/conn_jst_VH_tht_side-stabilizer.py | Python | gpl-3.0 | 12,839 | 0.027962 | #!/usr/bin/env python3
'''
kicad-footprint-generator 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.
kicad-footprint-generator is distribut... | configuration['silk_line_width']))
kicad_mod.append(PolygoneLine(polyg | one=[{'x':x4-0.44,'y':-1.6},{'x':x4-0.44,'y':y1},{'x':x2,'y':y1},{'x':x2,'y':y4},{'x':x4,'y':y4}], layer='F.SilkS', width=configuration['silk_line_width']))
kicad_mod.append(PolygoneLine(polygone=[{'x':x4-0.44,'y':y3},{'x':x4-0.44,'y':1.6}], layer='F.SilkS', width=configuration['silk_line_width']))
kicad_mod.ap... |
enthought/etsproxy | enthought/preferences/i_preferences.py | Python | bsd-3-clause | 103 | 0 | # proxy modul | e
from __future__ import absolute_import
from apptools.preferences.i_preferences import * | |
eyassug/au-water-sanitation-template | dashboard/forms.py | Python | mit | 3,400 | 0.019706 | from django import forms
from dashboard.models import CountryDemographic, FacilityAccess, SectorPerformance, PriorityAreaStatus, Technology
from dashboard.models import Country, PriorityArea, SectorCategory, TenderProcedurePerformance, TenderProcedureProperty
class CountryStatusForm(forms.ModelForm):
class Meta:
... | ices=(('-1','Select Priority Area'),))
class DTenderProcPerformanceForm(forms.ModelForm):
| class Meta:
model = TenderProcedurePerformance
exclude = ['tender_procedure_property','country']
sector_category = forms.ModelChoiceField(required=True,queryset=SectorCategory.objects.all(), widget=forms.Select(attrs={'onchange':'FilterTenderProcProperties();'}))
tender_procedure_property = ... |
EasyCTF/easyctf-2015 | api/problems/recon/ioexception/ioexception_grader.py | Python | mit | 461 | 0.034707 | def grade(tid, answe | r):
if answer.find("failed_up_is_the_best_fail_you_are_ctf_champion") != -1:
return { "correct": False, "message": "It's not going to be the same as last year's...." }
if answer.find("yeee3ee3ew_sha44aal11l1l1l_bE#eeee_azzzzzsimmileitted!!") != -1:
return { "correct": True, "message": "Now send the writeup to <co... | harder............." } |
gunan/tensorflow | tensorflow/python/feature_column/sequence_feature_column_integration_test.py | Python | apache-2.0 | 10,486 | 0.00391 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | se_example)
ds = ds.batch(20)
# Test on a single batch
features = dataset_ops.make_one_shot_iterator(ds).get_next()
# Tile the context features across the sequence features
sequence_input_layer = sfc.SequenceFeatures(seq_cols)
| seq_layer, _ = sequence_input_layer(features)
input_layer = dense_features.DenseFeatures(ctx_cols)
ctx_layer = input_layer(features)
input_layer = sfc.concatenate_context_input(ctx_layer, seq_layer)
rnn_layer = recurrent.RNN(recurrent.SimpleRNNCell(10))
output = rnn_layer(input_layer)
with sel... |
lk-geimfari/expynent | tests/test_compiled.py | Python | bsd-3-clause | 774 | 0 | import re
from expynent import compiled
from expynent import patterns
from e | xpynent.shortcuts import is_private
def assert_is_compiled(obj):
assert isinstance(obj, type(re.compile('')))
def test_patterns_are_compiled():
def walk(dictionary):
for value in dictionary.values():
if isinstance(value, dict):
walk(value)
else:
... | me in dir(patterns):
if is_private(pattern_name):
continue
compiled_variable = getattr(compiled, pattern_name)
if isinstance(compiled_variable, dict):
for value in walk(compiled_variable):
assert_is_compiled(value)
else:
assert_is_comp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.