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 |
|---|---|---|---|---|---|---|---|---|
beyoungwoo/C_glibc_Sample | _Algorithm/ProjectEuler_python/euler_17.py | Python | gpl-3.0 | 1,631 | 0.045984 | #!/usr/bin/python -Wall
# -*- coding: utf-8 -*-
"""
<div id="content">
<div style="text-align:center;" class="print"><img src="images/print_page_logo.png" alt="projecteuler.net" style="border:none;" /></div>
<h2>Number letter counts</h2><div id="problem_info" class="info"><h3>Problem 17</h3><span>Published on Friday, 1... | the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? </p>
<br />
<p class="note"><b>NOTE:</b> Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "an... | ven",8:"eight",9:"nine",10:"ten",11:"eleven",12:"twelve",13:"thirteen",14:"fourteen",15:"fifteen",16:"sixteen",17:"seventeen",18:"eighteen",19:"nineteen",20:"twenty",30:"thirty",40:"forty",50:"fifty",60:"sixty",70:"seventy",80:"eighty",90:"ninety"}
for i in range(1,1000):
if(not i in s.keys()):
if(i<100):
... |
lyuboshen/Pose-Estimation-on-Depth-Images-of-Clinical-Patients-V2.0 | src/load_data.py | Python | mit | 9,257 | 0.013179 | import os
import numpy as np
import cv2
import json
start_index = 0
image_path = 'images/trial_3_autoencoder/'
test_path = 'test/trial_3_autoencoder/'
json_file = 'annotations/all_patient.json'
image_rows = 376
image_cols = 312
image_rows_map = 46
image_cols_map = 38
with open(json_file) as jf:
dict = json.load(... | g_resized = cv2.resize(depth_img, (image_cols, image_rows), interpolation=cv2.INTER_NEAREST)
ir_img_resized = cv2.resize(ir_img, (image_cols, image_rows), interpolation=cv2.INTER_NEAREST)
depth_img_resized = np.asarray(depth_img_resized)
depth_imgs[i,:,:,0] = depth_img_resized
... | ized, 1)
depth_imgs[i+1,:,:,1] = cv2.flip(depth_img_resized, 1)
depth_imgs[i+1,:,:,2] = cv2.flip(depth_img_resized, 1)
ir_imgs[i] = ir_img_resized
ir_imgs[i+1] = cv2.flip(ir_img_resized, 1)
center_map = np.zeros((int(img_info["img_height"]), int(img_info["img_... |
neulab/compare-mt | compare_mt/cache_utils.py | Python | bsd-3-clause | 642 | 0.018692 | def extract_cache_dicts(cache_dicts, key_list, num_out):
if cache_dicts is not None:
if len(cache_dicts) != num_out:
raise ValueError(f'Length of cache_dic | ts should be equal to the number of output files!')
if len(key_list) == 1:
return [c[key_list[0]] for c in cache_dicts]
return zip(*[[c[k] for k in key_ | list] for c in cache_dicts])
return [None]*len(key_list)
def return_cache_dict(key_list, value_list):
for v in value_list:
if len(v) != 1:
raise ValueError(f'Only support caching for one system at a time!')
cache_dict = {k:v[0] for (k, v) in zip(key_list, value_list)}
return cache_dict
|
Sonictherocketman/metapipe | test/mocks.py | Python | mit | 673 | 0 | """ A series of mocks for metapipe. """
from metapipe.models import Job
class MockJob(Job):
def __init__(self, alias, command, depends_on=[]):
super(MockJob, self).__init__(alias, command, depends | _on)
self._submitted = False
self._done = False
self._step = 0 |
def __repr__(self):
return '<MockJob: {}>'.format(self.alias)
def submit(self):
self._step += 1
def is_running(self):
self._step += 1
return self._step > 1 and self._step < 10
def is_queued(self):
return False
def is_complete(self):
return self._... |
IsacEkberg/crag-finder | django_api/migrations/0019_auto_20160420_2323.py | Python | gpl-3.0 | 2,068 | 0.00436 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-20 21:23
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django_api.models
class Migration(migrations.Migration):
dependencies = [
('django_api', '0018_auto_20160420_23... | 'verbose_name': 'områdes bild',
'verbose_name_plural': 'områdes bild',
},
),
migrations.CreateModel(
name='RockFaceImage',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | ('name', models.CharField(max_length=255, null=True, verbose_name='namn')),
('description', models.TextField(blank=True, null=True, verbose_name='kort beskrivning av bilden')),
('rockface', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='image', to='django_a... |
lanky/fabrik | fabrik/snippets/betterforms.py | Python | gpl-2.0 | 8,496 | 0.005532 | """
Copyright (c) 2008, Carl J Meyer
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions ... | scription)
| self.name = name
def __iter__(self):
for bf in self.boundfields:
yield _mark_row_attrs(bf, self.form)
def __repr__(self):
return "%s('%s', %s, legend='%s', description='%s')" % (
self.__class__.__name__, self.name,
[f.name for f in self.boundf... |
Abhayakara/minder | smtpd/smtpd.py | Python | gpl-3.0 | 27,553 | 0.013283 | #!/usr/bin/env python3
import dns.resolver
import dns.rdatatype
# This shouldn't be necessary, but for some reason __import__ when
# called from a coroutine, doesn't always work, and I haven't been
# able to figure out why. Possibly this is a 3.4.0 bug that's fixed
# later, but googling for it hasn't worked.
import ... | p(smtp.server):
userdb = None
mailbox = None
connections = {}
connection_list = []
message = None
# If we are authenticated, make sure the mail is from
# the authenticated user; if not, make sure that the
# sender passes basic anti-spam checks.
def validate_mailfrom(self, address):
if self.authen... | f.validate_fromuser(address)
else:
return self.validate_sender(address)
def validate_sender(self, address):
# Add sender validation fu here:
return True
@asyncio.coroutine
def validate_fromuser(self, address):
addr = self.userdb.parse_address(address)
# First just check that it's a va... |
luo-chengwei/utilitomics | utils/align.PE.py | Python | gpl-3.0 | 826 | 0.029056 | import sys
import os
import re
from subprocess import PIPE, Popen, call
fq1, fq2, db, prefix = sys.argv[1:]
bowtie2_logfh = open(prefix+'.bowtie2.log','w')
bamfile = prefix+'.bam'
bowtie2_cmd = ['bowtie2', '-x', db, '-1', fq1, '-2', fq2]
samtools_view = ['samtools', 'view', '-bhS', '-']
samtools_sort = ['samtools', 's... | ut = PIPE, stderr = bowtie2_logfh)
p2 = Popen(samtools_view, stdin = p1.stdout, stdout = PIPE, stderr = bowtie2_logfh)
p3 = Popen(samtools_sort, stdin = p2.stdout, stdout = | PIPE, stderr = bowtie2_logfh)
p1.stdout.close()
p2.stdout.close()
output, err = p3.communicate()
samtools_index = ['samtools', 'index', bamfile]
call(samtools_index, stderr = bowtie2_logfh, stdout = bowtie2_logfh)
bowtie2_logfh.close()
|
josiah-wolf-oberholtzer/consort | consort/tools/TimespanSpecifier.py | Python | mit | 1,111 | 0.0036 | import abjad
from abjad.tools import abctools
class TimespanSpecifier(abctools.AbjadValueObject):
### CLASS VARIABLES ###
__slots__ = (
'_forbid_fusing',
'_forbid_splitting',
'_minimum_duration',
)
### INITIALIZER ###
def __init__(
self,
forbid_fusin... | if forbid_splitting is not Non | e:
forbid_splitting = bool(forbid_splitting)
self._forbid_splitting = forbid_splitting
if minimum_duration is not None:
minimum_duration = abjad.Duration(minimum_duration)
self._minimum_duration = minimum_duration
### PUBLIC PROPERTIES ###
@property
def forb... |
gamingrobot/SpockBot | spockbot/plugins/helpers/keepalive.py | Python | mit | 451 | 0 | """
KeepalivePlugin is a pretty cool guy. Eh reflects keep alive packets and doesnt
afraid of anything.
"""
from spockbot.plugins.base import PluginBase
class KeepalivePlugin(PluginBase):
requires = 'Net'
events = {
'PLAY<Keep Alive': 'handle_keep_alive',
}
# Keep Alive - Reflect | s data | back to server
def handle_keep_alive(self, name, packet):
packet.new_ident('PLAY>Keep Alive')
self.net.push(packet)
|
ivecera/gentoo-overlay | dev-python/python-krbV/files/setup.py | Python | apache-2.0 | 714 | 0.068627 | from distutils.core import setup, Extension
setup (name = 'krbV',
version = '1.0.90',
description = 'Kerberos V Bindings for Python',
long_description = """
python-krbV allows python programs to use Kerberos 5 auth | entication/security
""",
author = 'Test',
author_email = 'mikeb@redhat.com',
classifiers = [
'Development Status :: 4 - Beta',
'License :: OSI Approved :: GNU General Public License (LGPL)',
'Operating System :: POSIX :: Linux',
'Programming Language :: C',
'Topic :: System :: Sys | tems Administration :: Authentication/Directory'
],
ext_modules = [Extension ('krbV',
[ 'krb5util.c', 'krb5module.c', 'krb5err.c' ],
libraries = ['krb5', 'com_err']
)
]
)
|
daviddrysdale/python-phonenumbers | python/tests/testdata/region_RU.py | Python | apache-2.0 | 630 | 0.009524 | """Auto-generated file, do not edit by hand. RU metadata"""
from pho | nenumbers.phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_RU = PhoneMetadata(id='RU', country_code=7, international_prefix='810',
general_desc=PhoneNumberDesc(national_number_pattern='[347-9]\\d{9}', possible_length=(10,)),
fixed_line=PhoneNumberDesc(national_number_pattern='[3... | honeNumberDesc(national_number_pattern='9\\d{9}', example_number='9123456789', possible_length=(10,)),
national_prefix='8',
national_prefix_for_parsing='8')
|
Eric89GXL/scikit-learn | sklearn/neural_network/tests/test_rbm.py | Python | bsd-3-clause | 4,240 | 0.000236 | import sys
import re
import numpy as np
from numpy.testing import assert_almost_equal, assert_array_equal
from sklearn.datasets import load_digits
from sklearn.externals.six.moves import cStringIO as StringIO
from sklearn.neural_network import BernoulliRBM
from sklearn.utils.validation import assert_all_finite
np.se... | e=rng)
rbm2.fit(X)
assert_almost_equal(rbm2.components_,
np.array([[0.02649814], [0.02009084]] | ), decimal=4)
assert_almost_equal(rbm2.gibbs(X), X.toarray())
assert_almost_equal(rbm1.components_, rbm2.components_)
def test_gibbs_smoke():
""" just seek if we don't get NaNs sampling the full digits dataset """
rng = np.random.RandomState(42)
X = Xdigits
rbm1 = BernoulliRBM(n_components=42,... |
zhouqilin1993/IntelliDE | crawler/ForumSpider/ForumSpider/valide/picget.py | Python | gpl-3.0 | 3,264 | 0.034007 | # This is a program for IP limit using picture recognition.
# URL: http://bbs.csdn.net/human_validations/new
# Input: human validations page
# Get the jpeg from the url.
# use picture recognition to get the string from the picture.
# Authentication pass!
#
# this is try to use selenuim to login
import re,os,sys
import... | h'])
bottom = int(picItem.location['y'] + picItem.size['height'])
im = Image.open(picname)
# print (left,top,right,bottom)
im = im.crop((left, top, right, bottom))
im.save(picname)
# validcode picture recognize
time.sleep(0.5)
validcode = self.imageToString(picname)
print (validcode)
validcode = ... | idcode):
if self.validlogin(sel,cookie,validcode):
print ('Auth Success!')
else:
print ('Auth Fail!')
#picItem.send_keys(Keys.TAB)
#submit_button.send_keys(Keys.ENTER)
#submit_button.click()
# try:
# submit_button.click()
# except Exception,e:
# print (Exception,":",e)
# validcode... |
freieslabor/info-display | info_display/screens/event_schedule/apps.py | Python | mpl-2.0 | 158 | 0 | from django.apps import | AppConfig
class CalendarFeedConfig(AppConfig):
n | ame = 'info_display.screens.event_schedule'
verbose_name = 'Event Schedule'
|
ChromiumWebApps/chromium | tools/telemetry/telemetry/page/cloud_storage.py | Python | bsd-3-clause | 6,562 | 0.012496 | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrappers for gsutil, for basic interaction with Google Cloud Storage."""
import cStringIO
import hashlib
import logging
import os
import subprocess
i... | allation.
gsutil_path = _FindExecutableInPath(
os.path.join('third_party', 'gsutil', 'gsutil'), _DOWNLOAD_PATH)
if gsutil_path:
return gsutil_path
# Look for a gsutil installation.
gsutil_path = _FindExecutableInPath('gsutil', _DOWNLOAD_PATH)
if gsutil_path:
return gsutil_path
# Failed to fi... | il_path):
def GsutilSupportsProdaccess():
with open(gsutil_path, 'r') as gsutil:
return 'prodaccess' in gsutil.read()
return _FindExecutableInPath('prodaccess') and GsutilSupportsProdaccess()
def _RunCommand(args):
gsutil_path = FindGsutil()
gsutil = subprocess.Popen([sys.executable, gsutil_path] +... |
jrmendozat/mtvm | Sede/models.py | Python | gpl-2.0 | 1,385 | 0.005776 | from django.db import models
#from Cliente.models import Cliente_Direccion
# Create your models here.
class Tipo_sede(models.Model):
nombre = models.CharField(max_length=50, unique=True)
def __unicode__(self):
return self.nombre
class Meta:
verbose_name = "Tipo de sede"
verbose_n... | dels.OneToOneField(Cliente_Direccion)
def __unicode__(self):
return u'%s'%(self.tipo)
class Meta:
verbose_name = "Sede"
verbose_name_plural = "Sedes"
class Tipo_Ambiente(models.Model):
tipo_ambiente = models.CharField(max_length=50, unique=True)
def __unicode__(self):
... | entes"
class Ambiente(models.Model):
ambiente = models.ForeignKey(Tipo_Ambiente)
sede = models.ForeignKey(Sede)
def __unicode__(self):
return u'%s - %s'%(self.ambiente, self.sede)
class Meta:
verbose_name = "Ambiente"
verbose_name_plural = "Ambientes"
|
apdjustino/DRCOG_Urbansim | src/opus_gui/data_manager/data_manager_functions.py | Python | agpl-3.0 | 1,946 | 0.004111 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington
# See opus_core/LICENSE
import lxml
'''
A set of functions related to Data Manager and the <data_manager> node
in Opus Project Configuration files.
'''
def get_tool_nodes(projec... | OpusProject) project to operate on
@return the text representing the path or | None if not found
'''
node = project.find('data_manager/path_to_tool_modules')
if node is not None: return node.text
return None
|
mrfesol/easyAI | easyAI/AI/TT.py | Python | mit | 2,413 | 0.007874 | """
This module implements transposition tables, which store positions
and moves to speed up the AI.
"""
import pickle
from easyAI.AI.DictTT import DictTT
class TT:
"""
A tranposition table made out of a Python dictionnary.
It can only be used on games which have a method
game.ttentry() -> string, or ... | # maybe save for later ?
>>> # later...
>>> table = TT.fromfile('saved_tt.data')
>>> ai = Negamax(8, scoring, tt = table) # boosted Negamax !
Transposition tables can also be used as an AI (``AI_player(tt)``)
| but they must be exhaustive in this case: if they are asked for
a position that isn't stored in the table, it will lead to an error.
"""
def __init__(self, own_dict = None):
self.d = own_dict if own_dict != None else dict()
def lookup(self, game):
""" Requests the entr... |
craigatron/freedoge | freedoge/wsgi.py | Python | mit | 426 | 0.004695 | """
WSGI config for freedoge project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdef | ault("DJANGO_SETTINGS_MODULE", "freedoge.settings") |
from dj_static import Cling
from django.core.wsgi import get_wsgi_application
application = Cling(get_wsgi_application())
|
danielsunzhongyuan/my_leetcode_in_python | search_a_2d_matrix_ii_240.py | Python | apache-2.0 | 895 | 0.001117 | # @author: Zhongyuan Sun
# time: O(log(m*n)), space: O(1)
class Solution(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
# Solution One: 122ms, beats 50.00%
# if not matrix or not matrix[0]... | ix[i][j] < target:
# j += 1
# else:
# return True
# return False
# Solution Two: 216ms | , beats 21.36%
if not matrix or not matrix[0]:
return False
for line in matrix:
if target in line:
return True
return False
|
rooshilp/CMPUT410Lab6 | virt_env/virt1/lib/python2.7/site-packages/django/contrib/staticfiles/storage.py | Python | apache-2.0 | 14,802 | 0.000608 | from __future__ import unicode_literals
from collections import OrderedDict
import hashlib
import os
import posixpath
import re
import json
from django.conf import settings
from django.core.cache import (caches, InvalidCacheBackendError,
cache as default_cache)
from django.core.ex | ceptions import ImproperlyConfigured
from django.core.files.base import ContentFile
from django.core.files.storage import FileSystemStorage, get_storage_class
from django.utils.encoding import force_bytes, force_text
from django.utils.functional import LazyObject
from django.utils.six.moves.urllib.parse import unquote,... |
from django.contrib.staticfiles.utils import check_settings, matches_patterns
class StaticFilesStorage(FileSystemStorage):
"""
Standard file system storage for static files.
The defaults for ``location`` and ``base_url`` are
``STATIC_ROOT`` and ``STATIC_URL``.
"""
def __init__(self, locatio... |
bnsantos/python-junk-code | tests/math/abacusTest.py | Python | gpl-2.0 | 5,476 | 0.000183 | __author__ = 'bruno'
import unittest
import algorithms.math.abacus as Abacus
class TestAbacus(unittest.TestCase):
def setUp(self):
pass
def test_abacus1(self):
abacus = Abacus.generate_abacus(0)
self.assertEqual(['|00000***** |',
'|00000***** |',
... | self):
abacus = Abacus.generate_abacus(13)
self.assertEqual(['|00000***** |',
'|00000***** |',
'|00000***** |',
| '|00000***** |',
'|00000***** |',
'|00000***** |',
'|00000***** |',
'|00000***** |',
'|00000**** *|',
'|00000** ***|'], abacus)
def test_abacus... |
JanHendrikDolling/configvalidator | configvalidator/tools/basics.py | Python | apache-2.0 | 6,745 | 0.00089 | # -*- coding: utf-8 -*-
"""
:copyright: (c) 2015 by Jan-Hendrik Dolling.
:license: Apache 2.0, see LICENSE for more details.
"""
import abc
import six
import json
import logging
from six import string_types
from collections import namedtuple
from configvalidator.tools.exceptions import LoadException, ValidatorExceptio... | LIDATOR[validator_name]
except KeyError:
raise LoadException("no validator with the name {name}".format(name=validator_name))
def load_section_feature(feature_name):
try:
return DATA_SECTION_FEATURE[feature_name]
except KeyError:
raise LoadException(
"no Section feature... | .format(name=feature_name))
def load_option_feature(feature_name):
try:
return DATA_OPTION_FEATURE[feature_name]
except KeyError:
raise LoadException(
"no option feature with the name {name}".format(name=feature_name))
def load_validator_form_dict(option_dict):
validator_clas... |
refeed/coala | tests/results/result_actions/ResultActionTest.py | Python | agpl-3.0 | 1,388 | 0 | import unittest
from coalib.results.Result import Result
from coalib.results.result_actions.ResultAction import ResultAction
from coalib.settings.Section import Section
class ResultActionTest(unittest.TestCase):
def test_api(self):
uut = ResultAction()
result = Result('', '')
self.asser... | {},
{},
Section('name'))
self.assertRaises(TypeError, uut.apply_from_section, '', {}, {}, 5)
self.assertRaises(TypeError,
uut.apply_from_section,
'',
| 5,
{},
Section('name'))
self.assertRaises(TypeError,
uut.apply_from_section,
'',
{},
5,
Section('name'))
s... |
trelay/multi-executor | main/main_fio.py | Python | mit | 1,282 | 0.013261 | #!/usr/bin/python
import os, re,sys
from remote_exe import create_thread
from subprocess import Popen, PIPE
from main import base_fun
fio_cmd = "fio --name=global --ioengine=sync --bs=4k --rw=read --filename=/dev/{0} --runtime={1} --direct=1 -numjobs=1 -iodepth=4 --name=job"
stress_time = 60
class FIO_FUN(base_fun... | 0','nvme | 0n1', 'nvme1','nvme10','nvme10n1','nvme11','nvme11n1']
p= re.compile(r'nvme\d+n\d')
for dev in dev_list:
match = p.search(dev)
if match:
self.nvme_list.append(dev)
return self.nvme_list
def run(self):
#argv_list = [{'log_name': 'log_path', 'co... |
ChristianTremblay/BAC0 | BAC0/core/functions/cov.py | Python | lgpl-3.0 | 5,711 | 0.001926 | from bacpypes.apdu import SubscribeCOVRequest, SimpleAckPDU, RejectPDU, AbortPDU
from bacpypes.iocb import IOCB
from bacpypes.core import deferred
from bacpypes.pdu import Address
from bacpypes.object import get_object_class, get_datatype
from bacpypes.constructeddata import Array
from bacpypes.primitivedata import Tag... | equest))
iocb = IOCB(request)
self._log.debug("IOCB : {}".format(iocb))
iocb.add_callback(self.subscription_acknowledged)
# pass to the BACnet stack
d | eferred(self.this_application.request_io, iocb)
def subscription_acknowledged(self, iocb):
if iocb.ioResponse:
self._log.info("Subscription success")
if iocb.ioError:
self._log.error("Subscription failed. {}".format(iocb.ioError))
def cov(self, address, objectID, confi... |
stackforge/networking-bagpipe-l2 | networking_bagpipe/objects/bgpvpn.py | Python | apache-2.0 | 15,705 | 0 | # Copyright (c) 2017 Orange. # 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 b... | 'project_id',
'type',
'port_id']
foreign_keys = {'BGPVPNNetAssociation': {'id': 'bgpvpn_id'},
'BGPVPNRouterAssociation': {'id': 'bgpvpn_id'},
'BGPVPNPortAssociation': {'id': 'bgpvpn_id'},
| 'BGPVPNPortAssociationRoute': {'id': 'bgpvpn_id'},
}
@classmethod
def modify_fields_from_db(cls, db_obj):
result = super(BGPVPN, cls).modify_fields_from_db(db_obj)
for field in ['route_targets',
'import_targets',
'expor... |
rtts/qqq | qqq/views.py | Python | gpl-3.0 | 3,044 | 0.012155 | from django.http import HttpResponse, Http404
from django.template.loader import get_template
from django.template import RequestContext
from django.core.paginator import Paginator, EmptyPage
from django.utils.translation import ugettext as _
from tagging.models import Tag
from messages.models import Message
from sett... | er of results to paginate by
RESULTS_PER_PAGE = 25
def home(request):
"""
Serves the home page, which depends on whether the user is logged in or not.
"""
if request.user.is_authenticated():
return participate(request)
else:
c = RequestContext(request)
if lang == "nl":
c['frontpage'] = 'fro... | ] = Tag.objects.cloud_for_model(Question, steps=9, min_count=None)
return HttpResponse(t.render(c))
###################################################################################
#################################### MEMBERS ONLY #################################
###############################################... |
opinkerfi/nago | nago/extensions/checkresults.py | Python | agpl-3.0 | 4,996 | 0.003203 | # -*- coding: utf-8 -*-
""" Get and post nagios checkresults between nago instances
This extension allows to get status data from a local nagios server.
Also pushing checkresults into a local nagios server, therefore updating nagios status.
"""
from pynag.Parsers import mk_livestatus, config
import time
import os
im... | _config.parse_maincfg()
check_result_path = nagios_config.get_cfg_value("check_result_path")
|
fd, filename = tempfile.mkstemp(prefix='c', dir=check_result_path)
if not hosts:
hosts = []
if not services:
services = []
if check_existance:
checkresults_overhaul(hosts, services, create_services=create_services, create_hosts=create_hosts)
checkresults = '### Active Chec... |
jeremiahyan/odoo | addons/l10n_ar/tests/__init__.py | Python | gpl-3.0 | 122 | 0 | # Part of Odoo. See LICENSE file for full c | opyright and licensing details.
from . import common
from . import test_manual
| |
cstewart90/kattis-python | easiest/easiest.py | Python | mit | 428 | 0 | " | ""
https://open.kattis.com/problems/easiest
"""
import sys
def sum_digits(number):
sum_of_digits = 0
while number:
sum_of_digits, number = sum_of_digits + number % 10, number // 10
return sum_of_digits
for line in sys.stdin:
n = int(line)
if n == 0:
break
p = 11
while ... | rue:
if sum_digits(n) == sum_digits(n * p):
print(p)
break
p += 1
|
IZSVenezie/VetEpiGIS-Group | plugin/export.py | Python | gpl-3.0 | 17,939 | 0.001672 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
VetEpiGIS-Group
A QGIS plugin
Spatial functions for vet epidemiology
-------------------
begin : 2016-05-06
git sha : $Format:%H$
... | # validity_end text,
# legal_framework text,
# competent_authority text,
# | biosecurity_measures text,
# control_of_vectors text,
# control_of_wildlife_reservoir text,
# modified_stamping_out text,
# movement_restriction text,
# stamping_out text,
# surveillance text,
... |
siddhika1889/Pydev-Editor | tests/pysrc/extendable/recursion_on_non_existent/__init__.py | Python | epl-1.0 | 31 | 0.032258 | from u | nexist | ent_import import * |
kabooom/plugin.video.xstream | resources/lib/download.py | Python | gpl-3.0 | 4,301 | 0.006278 | # -- coding: utf-8 --
from resources.lib.gui.gui import cGui
from resources.lib.config import cConfig
from resources.lib import common
import urllib2
import xbmc
import xbmcgui
import string
import logger
import time
import os
import sys
class cDownload:
def __createProcessDialog(self):
oDialog = xbmcgui.... | dir(temp_dir):
os.makedirs(os.path.join(temp_dir))
self.__prepareDownload(url, header, os.path.join(temp_dir, sTitle))
def __prepareDownload(self, url, header, sDownloadPath):
try:
logger.info('download file: ' + str(url) + ' to ' + str(sDownloadPath))
... | except Exception as e:
logger.error(e)
self.__oDialog.close()
def __download(self, oUrlHandler, fpath):
headers = oUrlHandler.info()
iTotalSize = -1
if "content-length" in headers:
iTotalSize = int(headers["Content-Length"])
chunk = 4096
... |
dbcli/pgcli | pgcli/magic.py | Python | bsd-3-clause | 2,270 | 0.000441 | from .main import PGCli
import sql.parse
import sql.connection
import logging
_logger = logging.getLogger(__name__)
def load_ipython_extension(ipython):
"""This is called via the ipython command '%load_ext pgcli.magic'"""
# first, load the sql magic if it isn't already loaded
if not ipython.find_line_ma... | ot pgcli.query_history:
return
q = pgcli.query_hi | story[-1]
if not q.successful:
_logger.debug("Unsuccessful query - ignoring")
return
if q.meta_changed or q.db_changed or q.path_changed:
_logger.debug("Dangerous query detected -- ignoring")
return
ipython = get_ipython()
return ipython.run_cell_magic("sql", line, q.q... |
ChinaMassClouds/copenstack-server | openstack/src/nova-2014.2/nova/virt/ovirt/dmcrypt.py | Python | gpl-2.0 | 2,226 | 0 | # Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory
# 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/l... | dev/mapper'):
return path.rpartition('/')[2].endswith(_dmcrypt_suffix)
else:
return False
def create_volume(target, device, cipher, key_size, key):
"""Sets up a dmcrypt mapping
:param target: device mapper logical device name
:param device: underlying block device
:param cipher: e... |
cmd = ('cryptsetup',
'create',
target,
device,
'--cipher=' + cipher,
'--key-size=' + str(key_size),
'--key-file=-')
key = ''.join(map(lambda byte: "%02x" % byte, key))
utils.execute(*cmd, process_input=key, run_as_root=True)
def delete_vol... |
endlessm/chromium-browser | third_party/chromite/cros_bisect/autotest_evaluator_unittest.py | Python | bsd-3-clause | 24,070 | 0.0027 | # -*- coding: utf-8 -*-
# Copyright 2017 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Test autotest_evaluator module."""
from __future__ import print_function
import os
from chromite.cros_bisect import autotest... | lf.options and self.evaluator.
Based on updated self.options, it creates a new AutotestEvaluator instance
and assigns to self.evaluator.
Args:
options_to_update: a dict to update self.options.
" | ""
self.options.update(options_to_update)
self.evaluator = autotest_evaluator.AutotestEvaluator(self.options)
def testInit(self):
"""Tests that AutotestEvaluator() works as expected."""
base_dir = self.tempdir
self.assertEqual(base_dir, self.evaluator.base_dir)
self.assertEqual(os.path.join(b... |
rh-marketingops/dwm | dwm/test/test_records.py | Python | gpl-3.0 | 11,832 | 0.008874 | record_lookupAll_genericLookup_caught = [{"emailAddress": "test@test.com", "field1": "badvalue"}]
record_lookupAll_genericLookup_uncaught = [{"emailAddress": "test@test.com", "field1": "badvalue-uncaught"}]
record_lookupAll_genericLookup_notChecked = [{"emailAddress": "test@test.com", "field2": "badvalue"}]
record_l... | ld1": "badvalue"}]
record_regexAll_fieldSpe | cificRegex_uncaught = [{"emailAddress": "test@test.com", "field1": "badvalue-uncaught"}]
record_regexAll_fieldSpecificRegex_notChecked = [{"emailAddress": "test@test.com", "field2": "badvalue"}]
record_regexAll_normRegex_caught = [{"emailAddress": "test@test.com", "field1": "badvalue"}]
record_regexAll_normRegex_unc... |
ncbray/pystream | bin/util/application/async.py | Python | apache-2.0 | 1,436 | 0.021588 | # Copyright 2011 Nicholas Bray
#
# 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... | ctools.wraps(func)
def async_wrapper(*args, **kargs):
t = threading.Thread(target=func | , args=args, kwargs=kargs)
t.start()
return t
if enabled:
return async_wrapper
else:
return func
def async_limited(count):
def limited_func(func):
semaphore = threading.BoundedSemaphore(count)
# closure with func and semaphore
def thread_wrap(*args, **kargs):
result = func(*args, **kargs)
sema... |
scheib/chromium | third_party/blink/web_tests/external/wpt/webdriver/tests/get_title/iframe.py | Python | bsd-3-clause | 2,183 | 0.000916 | import pytest
from tests.support.asserts import assert_success
"""
Tests that WebDriver can transcend site origins.
Many modern browsers impose strict cross-origin checks,
and WebDriver should be able to transcend these.
Although an implementation detail, certain browsers
also enforce process isolation based on si... |
return inline("<title>foo</title>< | iframe src='%s'></iframe>" % one_frame_doc)
def get_title(session):
return session.transport.send(
"GET", "session/{session_id}/title".format(**vars(session)))
def test_no_iframe(session, inline):
session.url = inline("<title>Foobar</title><h2>Hello</h2>")
result = get_title(session)
assert... |
lukecwik/incubator-beam | sdks/python/apache_beam/testing/test_stream_test.py | Python | apache-2.0 | 38,080 | 0.002784 | #
# 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 license | s this file to You und | er the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is d... |
umyuu/Sample | src/Python3/Q113190/exsample.py | Python | mit | 512 | 0.007813 | # -*- coding: utf8 -*-
import subprocess
import os
from pathlib import Path
| cwd = os.getcwd()
try:
print(os.getcwd())
subprocess.call(['make'])
# res = subprocess.check_output('uname -a', | shell=True)
res = subprocess.check_output(
r"./darknet detector test cfg/coco.data cfg/yolo.cfg yolo.weights /home/zaki/NoooDemo/0001.jpg", shell=True)
except Exception as ex:
print(ex)
finally:
os.chdir(cwd)
print(res)
def main() -> None:
pass
if __name__ == '__main__':
main()
|
OverTheWireOrg/OverTheWire-website | patreon/patreon.py | Python | mit | 745 | 0.004027 | #!/usr/bin/env python
import sy | s, json, csv, pprint
patrons = []
with open(sys.argv[1]) as csvfile:
csvrows = csv.DictReader(csvfile)
for row in csvrows:
name = row["Name"]
pledge = float(row["Pledge $"].replace("$",""))
lifetime = float(row["Lifetime $"].replace("$",""))
status = row["Patron Status"]
... | nal Details"]
since = row["Patronage Since Date"]
if details != "":
name = details
if status == "Active patron":
if lifetime > 0 and pledge >= 5:
patrons += [(name, lifetime, since)]
patreons = sorted(patrons, key=lambda x: x[2])
for (name, lifetime, s... |
monsta-hd/ml-mnist | ml_mnist/nn/rbm.py | Python | mit | 8,597 | 0.002326 | import numpy as np
import env
from base import BaseEstimator
from utils import RNG, print_inline, width_format, Stopwatch
from layers import FullyConnected
from activations import sigmoid
class RBM(BaseEstimator):
"""
Examples
--------
>>> X = RNG(seed=1337).rand(32, 256)
>>> rbm = RBM(n_hidden=1... | elf.hb
| return sigmoid(z)
def sample_h_given_v(self, v0_sample):
"""Infer state of hidden units given visible units."""
h1_mean = self.propup(v0_sample)
h1_sample = self._rng.binomial(size=h1_mean.shape, n=1, p=h1_mean)
return h1_mean, h1_sample
def propdown(self, h):
"""Propa... |
cfelton/rhea | rhea/cores/video/vga/vga_intf.py | Python | mit | 1,435 | 0 |
from myhdl import *
class VGA:
def __init__(self, color_depth=(10, 10, 10,)):
"""
color_depth the number of bits per RGB
"""
self.N = color_depth
# the sync signals
self.hsync = Signal(bool(1))
self.vsync = Signal(bool(1))
# the RGB signals to the... | elf.blue = Signal(intbv(0)[cd[2]:])
# logic VGA timing signals, used internally only
self.pxlen = Signal(bool(0))
self.active = Signal(bool(0))
# @todo: move this to the `vga_sync` this is specific to the
# VGA driver and not the intefaces ???
# these are used fo... | 'VER_FRONT_PORCH', 'VSYNC', 'VER_BACK_PORCH')
self.state = Signal(self.states.ACTIVE)
def assign(self, hsync, vsync, red, green, blue, pxlen=None, active=None):
""" in some cases discrete signals are connected """
self.hsync = hsync
self.vsync = vsync
self.red = red
... |
pwicks86/adventofcode2016 | day03/p1.py | Python | mit | 190 | 0.010526 | f = open('input.txt')
triangle | s = [map(int,l.split()) for l in f.rea | dlines()]
possible = 0
for t in triangles:
t.sort()
if t[0] + t[1] > t[2]:
possible += 1
print(possible)
|
wangqiang8511/troposphere | examples/EC2Conditions.py | Python | bsd-2-clause | 2,279 | 0 | from __future__ import print_function
from troposphere import (
Template, Parameter, Ref, Condition, Equals, And, Or, Not, If
)
from troposphere import ec2
parameters = {
"One": Parameter(
"One",
Type="String",
),
"Two": Parameter(
"Two",
Type="String",
),
"Thr... | quals(Ref("Three"), "Pft")
),
"OneIsQuzAndThreeEqualsFour": And(
Equals(Ref("One"), "Quz"),
Condition("ThreeEqualsFour")
),
"LaunchInstance": And(
Condition("OneEqualsFoo"),
Condition("NotOneEqualsFoo"),
Condition("BarEqualsTwo"),
Condition("OneEqualsFooAn... | on("OneIsQuzAndThreeEqualsFour")
),
"LaunchWithGusto": And(
Condition("LaunchInstance"),
Equals(Ref("One"), "Gusto")
)
}
resources = {
"Ec2Instance": ec2.Instance(
"Ec2Instance",
Condition="LaunchInstance",
ImageId=If("ConditionNameEqualsFoo", "ami-12345678", "am... |
knyghty/bord | bord/urls.py | Python | mit | 413 | 0 | """Root | URL definitions."""
from django.conf import settings
from django.conf.urls import include, url
from django.conf. | urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^accounts/', include('accounts.urls', namespace='accounts')),
url(r'^admin/', admin.site.urls),
url(r'^', include('core.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
|
hitaian/dogSpider | runSpider.py | Python | bsd-2-clause | 1,090 | 0.013889 | from Spider import *
from config import *
class run():
def __init__(self):
pass
#获取所有列表
def get_list(self):
list = cfg.getType()
for l in list.keys():
print(l)
return list
#获取用户选择的分类
def input_type(self):
start = spider(url)
list = self.... | istLink = list[type]
#攻取列表链接
oneList = start.openLink(listLink,type)
# 开始解析内容页面
#oneContent = start.getContent(oneList,type)
elif type in cfg.getType() and type == '成人小说':
| pass
else :
print('没有或者暂时不支持此类型下载')
if __name__ == '__main__':
cfg = config()
url = cfg.url
a = run()
a.input_type()
|
pipermerriam/perjury | setup.py | Python | bsd-2-clause | 565 | 0.021239 | #!/usr/bin/env python
from setuptools import setup, find_packages
__doc__ = """
Falsify data
"""
version = '0.0.1'
setup(name='perjury',
version=version,
description=__doc__,
author='Aaron Merriam',
| author_email='aaronmerriam@gmail.com',
keywords='content',
long_description=__doc__,
url='https://github.com/aaronmerriam/foundry',
packages=find_packages(),
platforms="any",
license='BSD',
test_suite='tests',
classifiers=[
'Development Status :: 3 - Alpha',
'Natural ... | ],
)
|
rgtjf/Semantic-Texual-Similarity-Toolkits | stst/features/features_nn.py | Python | mit | 4,605 | 0.001533 | # coding: utf8
"""
1. 每个文档自己训练一个Doc2Vec
2. 所有文档一起训练一个Doc2Vec
"""
import json
from gensim.models import Doc2Vec
from gensim.models.doc2vec import TaggedDocument
from stst.modules.features import Feature
from stst import utils
from stst import config
from stst.data import dict_utils
from stst.libs.kernel import vector_... | ces = []
for idx, train_instance in enumerate(train_instances):
sa, sb = train_instance.get_word(type='lemma', lower=True)
sentences.append(TaggedDocument(words=sa, tags=['sa_%d' % idx]))
sentences. | append(TaggedDocument(words=sb, tags=['sb_%d' % idx]))
model = Doc2Vec(sentences, size=25, window=3, min_count=0, workers=10, iter=1000)
features = []
infos = []
for idx in range(len(train_instances)):
vec_a = model.docvecs['sa_%d' % idx]
vec_b = model.docvecs['... |
bowen0701/algorithms_data_structures | lc0796_rotate_string.py | Python | bsd-2-clause | 1,408 | 0.00071 | """Leetcode 796. Rotate String
Easy
URL: https://leetcode.com/problems/rotate-string/
We are given two strings, A and B.
A shift on A consists of taking string A and moving the leftmost character to
the rightmost position. For example, if A = 'abcde', then it will be 'bcdea'
after one shift on A. Return True if and ... | ubstring of concated string A + A.
AA = A + A
if B in AA:
return True
else:
return False
def main():
# Input: A = 'abcde', B = 'cdeab'
# Output: true
A = 'abcde'
B = 'cdeab'
print SolutionStringConcatSubstring().rotateString(A, B)
# Input: A = '... | # Output: false
A = 'abcde'
B = 'abced'
print SolutionStringConcatSubstring().rotateString(A, B)
if __name__ == '__main__':
main()
|
cloudnull/bookofnova | bookofnova/logger.py | Python | apache-2.0 | 3,372 | 0.000593 | # ==============================================================================
# Copyright [2013] [Kevin Carter]
#
# 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/l... | ser if not log to working directory
"""
if os.path.isfile(filename):
return filename
else:
user = os.getuid()
logname = ('%s' % filename)
if not user == 0:
logfile = logname
else:
if os.path.isdir('/var/log'):
log_loc = '/var/lo... | name)
except Exception:
logfile = '%s' % logname
return logfile
def load_in(log_file=None, log_level='info', output=None):
"""
Load in the log handler. If output is not None, systen will use the default
Log facility.
"""
if not output:
if log_fil... |
scottbarstow/iris-python | iris_sdk/models/maps/cities.py | Python | mit | 142 | 0.014085 | #!/usr/bin/env python
from ir | is_sdk.models.maps.base_map import BaseMap
class CitiesMap(BaseMap):
result_count | = None
cities = None |
braincorp/robustus | robustus/tests/test_robustus.py | Python | mit | 8,887 | 0.006414 | # =============================================================================
# COPYRIGHT 2013 Brain Corporation.
# License under MIT license (see LICENSE file)
# =============================================================================
import doctest
import logging
import os
import pytest
import robustus
from r... | content = open(changed_filepath, 'r').read()
f = open(changed_filepath, 'w')
f.write('junk')
f.close()
run_shell([robustus_executable, 'reset', '-f'])
assert original_content == open(changed_filepath, 'r').read()
def test_install_with_tag(tmpdir):
"""Crea | te a package with some editable requirements and install using a tag."""
base_dir = str(tmpdir.mkdir('test_perrepo_env'))
test_env = os.path.join(base_dir, 'env')
working_dir = os.path.join(base_dir, 'working_dir')
# create env and install some packages
logging.info('creating ' + test_env)
os.... |
dhoffman34/django | django/db/backends/mysql/base.py | Python | bsd-3-clause | 23,595 | 0.00267 | """
MySQL database backend for Django.
Requires MySQLdb: http://sourceforge.net/projects/mysql-python
"""
from __future__ import unicode_literals
import datetime
import re
import sys
import warnings
try:
import MySQLdb as Database
except ImportError as e:
from django.core.exceptions import ImproperlyConfigur... | if e.args[0] in self.codes_for_integrityerror:
| six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
raise
def __getattr__(self, attr):
if attr in self.__dict__:
return self.__dict__[attr]
else:
return getattr(self.cursor, attr)
def __iter__(self):
return i... |
gjost/foxtabs | tests/test_foxtabs.py | Python | bsd-3-clause | 382 | 0.005236 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_foxtabs
----------------------------------
Tests for `foxtabs` module.
"""
import unittest
from foxtabs import foxtabs
class TestFoxtabs(unittest.TestCase):
def setUp(self):
| pass
def test_somethin | g(self):
pass
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main() |
naitoh/py2rb | tests/basic/while.py | Python | mit | 271 | 0.01107 | """ while case """
x = 1
while x<10:
print(x)
x = x + 1
""" while and else case """
x = 1
while x<10:
print(x)
x = x + 1
else:
print("ok")
""" while and else break ca | se "" | "
x = 1
while x<10:
print(x)
x = x + 1
break
else:
print("ok")
|
mitdbg/modeldb | client/verta/verta/_swagger/_public/modeldb/model/ModeldbUpdateDatasetDescriptionResponse.py | Python | mit | 638 | 0.010972 | # THIS FILE IS AUTO-GENERATED. DO NOT EDIT
from verta._swagger.base_type import BaseType
class ModeldbUpdateDatasetDescriptionResponse(BaseType):
def __init__(self, dataset=None):
required = {
"dataset": False,
}
self.dataset = dataset
for k, v in required.items():
if self[k] is None and... | from_json(d):
from .ModeldbDataset import ModeldbDataset
tmp = d.get('dataset', None)
if tmp is not None:
d['da | taset'] = ModeldbDataset.from_json(tmp)
return ModeldbUpdateDatasetDescriptionResponse(**d)
|
openhatch/oh-mainline | vendor/packages/mechanize/mechanize/_msiecookiejar.py | Python | agpl-3.0 | 14,694 | 0.002178 | """Microsoft Internet Explorer cookie loading on Windows.
Copyright 2002-2003 Johnny Lee <typo_pl@hotmail.com> (MSIE Perl code)
Copyright 2002-2006 John J Lee <jjl@pobox.com> (The Python port)
This code is free software; you can redistribute it and/or modify it
under the terms of the BSD or ZPL 2.1 licenses (see the ... | filetime(filetime)
if expires < now:
discard = True
else:
discard = | False
domain = cookie["DOMAIN"]
initial_dot = domain.startswith(".")
if initial_dot:
domain_specified = True
else:
# MSIE 5 does not record whether the domain cookie-attribute
# was specified.
# Assuming it ... |
freeworldxbmc/pluging.video.Jurassic.World.Media | resources/lib/resolvers/clicknupload.py | Python | gpl-3.0 | 2,319 | 0.012937 | # -*- coding: utf-8 -*-
'''
Genesis Add-on
Copyright (C) 2015 lambda
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 ... | lient
from resources.lib.libraries import captcha
def resolve(url):
try:
result = client.request(url)
if '>File Not Found<' in result: raise Exception()
post = {}
f = client.parseDOM(result, 'Form', attrs = {'action': ''})
k = client.parseDOM(f, 'input', ret='name', attrs... | for i in k: post.update({i: client.parseDOM(f, 'input', ret='value', attrs = {'name': i})[0]})
post.update({'method_free': 'Free Download'})
post = urllib.urlencode(post)
result = client.request(url, post=post, close=False)
post = {}
f = client.parseDOM(result, 'Form', att... |
aruizramon/alec_erpnext | erpnext/selling/doctype/used_sales_order/used_sales_order.py | Python | agpl-3.0 | 276 | 0.01087 | # Copyright (c) 2013, Web Notes Technologies Pvt | . Ltd. and Co | ntributors and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class UsedSalesOrder(Document):
pass
|
jadjay/GestionBoissonDj | gestionboisson/consommateurs/models.py | Python | gpl-3.0 | 1,011 | 0.023739 | from __future__ import unicode_literals
from django.db import models
from django.forms import ModelForm
from django.contrib.auth.models import User
from boissons.models import boissons
# Create your models here.
class consommateurs(models.Model):
def __str__(self):
return "%s" % (self.user.username)
user = models... | key_expires = models.DateTimeField()
class consommation(models.Model):
def __str__(self):
manuel = "MANUEL" if self.manuel else ""
return "%s %s %s %s" % (self.date.strftime("%F"),self.consommateur.user.username,self.boisson.name,manuel)
date = models.DateField(auto_now_add=True)
consommateur = models.ForeignK... | ult=True)
class ConsommateursForm(ModelForm):
class Meta:
model = User
fields = ('username', 'email', 'password')
|
sonusz/PhasorToolBox | phasortoolbox/parser/common.py | Python | mit | 9,531 | 0.002833 | # This is modified from a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
import array
import struct
import zlib
from enum import Enum
from pkg_resources import parse_version
from kaitaistruct import __version__ as ks_version, KaitaiStruct, KaitaiStream, BytesIO
if parse_version... | class FrameTypeEnum(Enum):
data = 0
header = 1
cfg1 = 2
cfg2 = 3
cmd = 4
cfg3 = 5
| class VersionNumberEnum(Enum):
c_37_118_2005 = 1
c_37_118_2_2011 = 2
def __init__(self, _io, _parent=None, _root=None):
self._io = _io
self._parent = _parent
self._root = _root if _root else self
self.magic = self._io.ensure_fixed_... |
saisankargochhayat/algo_quest | leetcode/155. Min Stack/soln.py | Python | apache-2.0 | 664 | 0 | class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
from collections import deque
self.stack = deque()
self.stack.append((None, float('inf')))
| def push(self, x: int) -> None:
self.stack.append((x, min(x, self.stack[-1][1])))
def pop(self) -> None:
return self.stack.pop()[0]
def top(self) -> int:
return self.stack[-1][0]
def getMin(self) -> int:
return self.stack[-1][1]
# Your MinStack object will be instantia... | inStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
|
meidli/yabgp | yabgp/message/attribute/mpunreachnlri.py | Python | apache-2.0 | 9,951 | 0.002311 | # Copyright 2015-2017 Cisco Systems, Inc.
# All rights reserved.
#
# Licensed under t | he 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.ap | ache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissio... |
tuwiendsg/MELA | MELA-Extensions/MELA-ComplexCostEvaluationService/tests/mela-clients/submitServiceDescription.py | Python | apache-2.0 | 589 | 0.050934 | import urllib, urllib2, sys, httplib
url = "/MELA/REST_WS"
HOST_IP="109.231.126.217:8180"
#HOST_IP="localhost:8180"
if __name__=='__main__':
connection = httplib.HTTPConnection(HOST_IP)
description_file = open("./costTest.xml", "r")
body_content = description_file.read()
headers={
... | lication/xml; charset=utf-8',
'Accept':'application/json, multipart/related'
}
connection.request('PUT', url+'/service', body=body_content,headers=headers,)
result = connection.getresponse()
print result.read()
| |
Eveler/libs | __Python__/edv/edv/imagescanner/backends/sane/__init__.py | Python | gpl-3.0 | 1,278 | 0.008607 | """SANE backend.
$Id$"""
import sane
from imagescanner.backends import base
class ScannerManager(base.ScannerManager):
def _refresh(self):
sel | f._devices = []
sane.init()
devices = sane.get_devices()
for dev in devices:
# Check if sane is able to open this device, if not just skip
try:
scanner = sane.open(dev[0])
scanner.close()
except:
con... | _devices.append(scanner)
sane.exit()
class Scanner(base.Scanner):
def __init__(self, scanner_id, device, manufacturer, name, description):
self.id = scanner_id
self.manufacturer = manufacturer
self.name = name
self.description = description
self._device = device
... |
naototty/devstack-vagrant-Ironic | boot-cirros.py | Python | apache-2.0 | 2,863 | 0.002445 | #!/usr/bin/env python -u
'''
This script does the following
1. Connect the router to the public network
2. Add a public key
3. Boot a cirros instance
4. Attach a floating IP
'''
from __future__ import print_function
import datetime
import os.path
import socket
import sys
import time
from novaclient.v1_1 import cl... | ist_networks()['networks']
if x['router:external']]
# Get the port corresponding to the instance
port, = [x for x in neutron.list_ports()['ports']
if x['device_id'] == instance.id]
# Create the floating ip
args = dict(floating_network_id=ext_net['id'],
port_id=port['id... | to be ready on cirros instance...", end='')
start = datetime.datetime.now()
timeout = 120
end = start + datetime.timedelta(seconds=timeout)
port = 22
connect_timeout = 5
# From utilities/wait_for of ansible
while datetime.datetime.now() < end:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(... |
vgrem/Office365-REST-Python-Client | office365/sharepoint/userprofiles/profileLoader.py | Python | mit | 1,190 | 0.004202 | from office365.runtime.client_object import ClientObject
from office365.runtime.queries.service_operation_query import ServiceOperationQuery
from office365.runtime.paths.resource_path import ResourcePath
from office365.sharepoint.userprofiles.userProfile import UserProfile
class ProfileLoader(ClientObject):
def ... | urce_path))
q | ry = ServiceOperationQuery(self, "GetUserProfile", None, None, None, result)
self.context.add_query(qry)
return result
@property
def entity_type_name(self):
return "SP.UserProfiles.ProfileLoader"
|
Ernsting/django-treebeard | treebeard/tests/tests.py | Python | apache-2.0 | 71,903 | 0.000793 | "Unit/Functional tests"
import os
from django.contrib.admin.options import ModelAdmin
from django.contrib.admin.sites import AdminSite
from django.test import TestCase
from django.db import models, transaction
from django.contrib.auth.models import User
from django.db.models import Q
from django.conf import settings
f... | 5, 0),
(u'3', 4, 0),
(u'4', 4, 1),
| (u'41', 5, 0),
(u'24', 2, 0),
(u'3', 1, 0),
(u'4', 1, 1),
(u'41', 2, 0)]
expected_descs = [u'1', u'2', u'21', u'22', u'23', u'231', u'24',
u'3', u'4', u'41']
got_descs = [obj.desc
... |
FedoraScientific/salome-yacs | src/salomeloader/salomeloader.py | Python | gpl-2.0 | 43,462 | 0.030578 | # -*- coding: iso-8859-1 -*-
# Copyright (C) 2006-2014 CEA/DEN, EDF R&D
#
# 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 lat... | createNode()
class Container:
"""Class that defines a Salome Container"""
def __init__(self,mach,name):
self.mach=mach
self.name=name
self.components={}
def getName(self):
return self.mach+"/"+self.name
def getContainer(name):
if not name:
name="localhost/FactoryServer"
elif "/" not in n... | host
name="localhost/"+name
return _containers.get(name)
def addContainer(name):
if not name:
mach="localhost"
name="FactoryServer"
elif "/" not in name:
#no machine name: use localhost for mach
mach="localhost"
else:
mach,name=name.split("/")
c=Container(mach,name)
_containers[mach... |
qguv/loadaverage | load/__init__.py | Python | gpl-3.0 | 107 | 0 | #!/usr/bin/env python3
# for | more | info, see github.com/qguv/loadaverage
from load.loadaverage import main
|
LonamiWebs/Py-Utils | logicmind/token_parser.py | Python | mit | 3,318 | 0.003617 | from tokens.andd import And
from tokens.expression import Expression
from tokens.iff import Iff
from tokens.kfalse import ConstantFalse
from tokens.ktrue import ConstantTrue
from tokens.nop import Not
from tokens.orr import Or
from tokens.then import Then
from tokens.variable import Variable
class TokenParser:
""... | l the representations on the string and add surrou | nding spaces,
# this will allow us to call 'string.split()' to separate variable names
# from the operators so the user doesn't need to enter them separated
for operator in operators:
for representation in operator.representations:
string = string.replace(representati... |
cpe/VAMDC-VALD | nodes/cdms/node/forms.py | Python | gpl-3.0 | 1,963 | 0 | from node import models
from django.forms import ModelForm
from . import cdmsportalfunc as cpf
from django.core.exceptions import ValidationError
from django import forms
class MoleculeForm(ModelForm):
class Meta:
model = models.Molecules
fields = '__all__'
class SpecieForm(ModelForm):
datea... | 'title': 'Paste here a URL that delivers an XSAMS '
'document.',
}))
infile = forms.FileField()
format = forms.ChoiceField(
choices=[("RAD 3D", "RAD 3D"), ("CSV", "CSV")], )
def clean(self):
infile = self.cleaned_... | .cleaned_data.get('inurl')
if (infile and inurl):
raise ValidationError('Give either input file or URL!')
if inurl:
try:
data = cpf.urlopen(inurl)
except Exception as err:
raise ValidationError('Could not open given URL: %s' % err)
... |
bzhou26/leetcode_sol | p675_Cut_Off_Trees_for_Golf_Event.py | Python | mit | 3,256 | 0.002764 | '''
- Leetcode problem: 675
- Difficulty: Hard
- Brief problem description:
You are asked to cut off trees in a forest for a golf event. The forest is represented as a non-negative 2D map, in this map:
0 represents the obstacle can't be reached.
1 represents the ground can be walked through | .
The place with number bigger than 1 represents a tree can be walked through, and this positive number represents the tree's height.
In one step you can walk in any of the four directions top, bottom, left and r | ight also when standing in a point which is a tree you can decide whether or not to cut off the tree.
You are asked to cut off all the trees in this forest in the order of tree's height - always cut off the tree with lowest height first. And after cutting, the original place has the tree will become a grass (value 1).... |
oyamad/QuantEcon.py | quantecon/game_theory/tests/test_random.py | Python | bsd-3-clause | 2,411 | 0 | """
Tests for game_theory/random.py
"""
import numpy as np
from numpy.testing import assert_allclose, assert_raises
from nose.tools import eq_, ok_
from quantecon.game_theory import (
random_game, covariance_game, random_pure_actions, random_mixed_actions
)
def test_random_game():
nums_actions = (2, 3, 4)
... | e():
nums_actions = (2, 3, 4)
N = len(nums_actions)
rho = 0.5
g = covariance_game(nums_actions, rho=rho)
eq_(g.nums_actions, nums_actions)
rho = 1
g = covariance_game(nums_actions, rho=rho)
for a in np.ndindex(*nums_actions):
for i in range(N-1 | ):
payoff_profile = g.payoff_profile_array[a]
assert_allclose(payoff_profile[i], payoff_profile[-1], atol=1e-8)
rho = -1 / (N - 1)
g = covariance_game(nums_actions, rho=rho)
for a in np.ndindex(*nums_actions):
assert_allclose(g.payoff_profile_array.sum(axis=-1),
... |
Yash3667/CipherAnalysis | Analysis/Frequency.py | Python | mit | 3,272 | 0.034535 | """
FREQUENCY FILE
-> Contains function pertaining to analyze a file based on frequency of characters or words.
"""
def call(Arguments):
"""
Entry point for all calls pertaining to frequency analysis
"""
# Storing arguments in a dictionary for easier reference
ArgumentsDictionary = {
"NAME" : Arguments[0... | t two letter are "-" and "f" respectively
Option = ArgumentsDictionary["OPTION"][2:]
# Call the frequencyWork function to do the actual work
if Option in FunctionsDictionary:
return fr | equencyWork(FunctionsDictionary[Option], ArgumentsDictionary["FILE"], ArgumentsDictionary["KEY"])
else:
return 0
def frequencyWork(FunctionObject, FileName, Key):
"""
This function stores the data inside FILE into a List. Then calls the FunctionObject with the List and the Key
"""
# Read the enitre file and st... |
rackerlabs/python-proboscis | proboscis/compatability/exceptions_2_5.py | Python | apache-2.0 | 1,186 | 0.000843 | # Copyright (c) 2011 Rackspace
# 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... | in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either expre | ss or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
def capture_exception(body_func, *except_type):
try:
body_func()
return None
except except_type, e:
return e
def capture_type_error(func):
try:
func... |
MaximeBiset/care4care | main/migrations/0036_auto_20141204_1818.py | Python | agpl-3.0 | 1,581 | 0.001898 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import easy_thumbnails.fields
import multiselectfield.db.fields
class Migration(migrations.Migration):
dependencies = [
('main', '0035_auto_20141204_1708'),
]
operations = [
migratio... | hoto',
field=easy_thumbnails.fields.ThumbnailerImageField(upload_to='photos/', default='photos/default_avatar.png'),
preserve_default=True,
| ),
migrations.AlterField(
model_name='verifieduser',
name='offered_job',
field=multiselectfield.db.fields.MultiSelectField(choices=[('1', 'Visit home'), ('2', 'Companionship'), ('3', 'Transport by car'), ('4', 'Shopping'), ('5', 'House sitting'), ('6', 'Manual jobs'), ... |
qianqians/meter | xlrd/xldate.py | Python | lgpl-2.1 | 7,895 | 0.004813 | # -*- coding: cp1252 -*-
# No part of the content of this file was derived from the works of David Giffin.
##
# <p>Copyright © 2005-2008 Stephen John Machin, Lingfo Pty Ltd</p>
# <p>This module is part of the xlrd package, which is released under a BSD-style licence.</p>
#
# <p>Provides function(s) for dealing with M... | rsion from days to (year, month, day) starts with
# an integral "julian day number" aka JDN.
# FWIW, JDN 0 corresponds to noon on M | onday November 24 in Gregorian year -4713.
# More importantly:
# Noon on Gregorian 1900-03-01 (day 61 in the 1900-based system) is JDN 2415080.0
# Noon on Gregorian 1904-01-02 (day 1 in the 1904-based system) is JDN 2416482.0
import datetime
_JDN_delta = (2415080 - 61, 2416482 - 1)
assert _JDN_delta[1] - _JDN_d... |
Comunitea/CMNT_004_15 | project-addons/custom_partner/__manifest__.py | Python | agpl-3.0 | 1,917 | 0.000522 | ##############################################################################
#
# Copyright (C) 2015 Comunitea Servicios Tecnológicos All Rights Reserved
# $Omar Castiñeira Saavedra <omar@pcomunitea.com>$
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the G... | rvicios Tecnológicos',
'website': 'www.comunitea.com',
"depends": ['base', 'sale', 'l10n_es_partner', 'account',
'base_partner_sequence', 'stock', 'account_credit_control',
'purchase', 'prospective_customer', 'account_due_list',
'customer_lost', 'sale_margin_perce... | 'commercial_rules', 'account_fiscal_position_partner_type'],
"data": ["views/invoice_pending_sales_view.xml",
"views/partner_view.xml",
"views/sale_view.xml",
"security/ir.model.access.csv",
"data/custom_partner_data.xml",
"security/groups.xml",
... |
botswana-harvard/microbiome | microbiome/apps/mb_list/models/infant_vaccines.py | Python | gpl-2.0 | 224 | 0 | from edc_base.model.models import BaseListModel
class InfantVaccines (BaseListModel):
class Met | a:
app_label = ' | mb_list'
verbose_name = "Infant Vaccines"
verbose_name_plural = "Infant Vaccines"
|
w1ll1am23/home-assistant | homeassistant/components/tile/device_tracker.py | Python | apache-2.0 | 4,346 | 0.00046 | """Support for Tile device trackers."""
import logging
from homeassistant.components.device_tracker.config_entry import TrackerEntity
from homeassistant.components.device_tracker.const import SOURCE_TYPE_GPS
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import ATTR_ATTRIBUTION, CONF_P... | ed by Tile"
DEFA | ULT_ICON = "mdi:view-grid"
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up Tile device trackers."""
async_add_entities(
[
TileDeviceTracker(
hass.data[DOMAIN][DATA_COORDINATOR][entry.entry_id][tile_uuid], tile
)
for tile_uuid,... |
vganapath/rally | tests/unit/plugins/common/hook/test_sys_call.py | Python | apache-2.0 | 4,165 | 0 | # Copyright 2016: Mirantis 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 b... | }
}
}
self.assertRaises(
jsonschema.ValidationError, hook.Hook.validate, conf)
@mock.patch("rally.common.utils.Timer", side_ | effect=fakes.FakeTimer)
@mock.patch("subprocess.Popen")
def test_run(self, mock_popen, mock_timer):
popen_instance = mock_popen.return_value
popen_instance.returncode = 0
task = mock.MagicMock()
sys_call_hook = sys_call.SysCallHook(task, "/bin/bash -c 'ls'",
... |
DownGoat/PyFeedReader | db_init.py | Python | gpl-3.0 | 79 | 0 | __autho | r__ = 'DownGoat'
from pyfeedreader import database
database.i | nit_db()
|
aequitas/munerator | tests/test_context.py | Python | mit | 566 | 0 | import pytest
from munerator.context import GameContext
from mock import Mock
@pytest.fixture
def gc():
gc = GameContext(Mock(), Mock(), Mock())
return gc
def test_player_name_client_id_translation(gc):
client_id = '1'
player_name = 'testplayer'
gc. | clients = {
client_id: {
'name': player_name,
'client_id': client_id
}
}
data = {
'kind': 'say',
'player_name': player_name
}
contexted_data = gc.handle_event(data)
assert contexted_data[' | client_id'] == client_id
|
ctrlaltdel/neutrinator | vendor/keystoneauth1/tests/unit/loading/test_v3.py | Python | gpl-3.0 | 16,308 | 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
# distributed under t... | , 'openid-scope']).issubset(
set([o.name for o in options]))
| )
def test_basic(self):
access_token_endpoint = uuid.uuid4().hex
username = uuid.uuid4().hex
password = uuid.uuid4().hex
scope = uuid.uuid4().hex
identity_provider = uuid.uuid4().hex
protocol = uuid.uuid4().hex
scope = uuid.uuid4().hex
client_id... |
VerifiableRobotics/LTLMoP | src/lib/configEditor.py | Python | gpl-3.0 | 64,636 | 0.003992 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# generated by wxGlade 0.6.3 on Fri Dec 16 03:13:38 2011
import wx, wx.richtext, wx.grid, wx.lib.intctrl
import sys, os, re
# Climb the tree to find out where we are
p = os.path.abspath(__file__)
t = ""
while t != "src":
(p, t) = os.path.split(p)
if p == "":
... | s param_controls[p]:
this_param = p
break
if this_param is None:
# Ignore; from another control (e.g. calib matrix)
return
this_param.setValue(param_controls[this_param].GetValue())
target.Bind(wx.EVT_TEXT, paramPaneCa | llback)
target.Bind(wx.EVT_COMBOBOX, paramPaneCallback)
target.Bind(wx.EVT_CHECKBOX, paramPaneCallback)
target.Bind(wx.lib.intctrl.EVT_INT, paramPaneCallback)
target.SetSizer(list_sizer)
target.Layout()
label_info.Wrap(list_sizer.GetSize()[0])
class regionTagsDialog(wx.Dialog):
def __in... |
akohlmey/lammps | lib/mesont/Install.py | Python | gpl-2.0 | 3,025 | 0.006942 | #!/usr/bin/env python
"""
Install.py tool to do a generic build of a library
soft linked to by many of the lib/Install.py files
used to automate the steps described in the corresponding lib/README
"""
from __future__ import print_function
import sys, os, subprocess
from argparse import ArgumentParser
sys.path.append... | = args.machine
extraflag = args.extramake
if extraflag:
suffix = args.extramake
else:
suffix = 'empty'
# set lib from working dir
cwd = fullpath('.')
lib = os.path.b | asename(cwd)
# create Makefile.auto as copy of Makefile.machine
# reset EXTRAMAKE if requested
if not os.path.exists("Makefile.%s" % machine):
sys.exit("lib/%s/Makefile.%s does not exist" % (lib, machine))
lines = open("Makefile.%s" % machine, 'r').readlines()
fp = open("Makefile.auto", 'w')
has_extramake = False... |
midvalestudent/jupyter | docker/base/jupyter_notebook_config.py | Python | mit | 1,414 | 0.004243 | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from jupyter_core.paths import jupyter_data_dir
import subprocess
import os
import errno
import stat
PEM_FILE = os.path.join(jupyter_data_dir(), 'notebook.pem')
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.p... | 888
c.NotebookApp.open_browser = False
# Set a certificate if USE_HTTPS is set to any value
if 'USE_HTTPS' in os.environ:
if not os.path.isfile(PEM_FILE):
# Ensure PEM_FILE direc | tory exists
dir_name = os.path.dirname(PEM_FILE)
try:
os.makedirs(dir_name)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(dir_name):
pass
else: raise
# Generate a certificate if one doesn't exist on... |
DheerendraRathor/ldap-oauth2 | application/views.py | Python | gpl-3.0 | 4,953 | 0.003836 | from braces.views import LoginRequiredMixin
from django.views.generic import UpdateView
from oauth2_provider.exceptions import OAuthToolkitError
from oauth2_provider.http import HttpResponseUriRedirect
from oauth2_provider.models import get_application_model as get_oauth2_application_model
from oauth2_provider.settings... | .id).all().delete()
# check past authorizations regarded the same scopes as the current one
if token.allow_scopes(scopes):
uri, headers, body, statu | s = self.create_authorization_response(
request=self.request, scopes=" ".join(scopes),
credentials=credentials, allow=True)
return HttpResponseUriRedirect(uri)
return self.render_to_response(self.get_context_data(**kwargs))
... |
jokajak/itweb | data/env/lib/python2.6/site-packages/SQLAlchemy-0.6.7-py2.6.egg/sqlalchemy/pool.py | Python | gpl-3.0 | 33,545 | 0.002832 | # sqlalchemy/pool.py
# Copyright (C) 2005-2011 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Connection pooling for DB-API connections.
Provides a number of connection poo... | when DB-API
connections are created, checked out and checked in to the
pool.
"""
if logging_name:
self.logging_name = self._or | ig_logging_name = logging_name
else:
self._orig_logging_name = None
self.logger = log.instance_logger(self, echoflag=echo)
self._threadconns = threading.local()
self._creator = creator
self._recycle = recycle
self._use_threadlocal = use_threadlocal
se... |
ggtracker/sc2reader | sc2reader/events/game.py | Python | mit | 25,673 | 0.002454 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals, division
from sc2reader.utils import Length
from sc2reader.events.base import Event
from sc2reader.log_utils import loggable
from itertools import chain
@loggable
class GameEvent(Event):
"""
This is the base cl... | ex of the ability in the ability group
self.command_index = (
data["ability"]["ability_command_index"] if self.has_ability else 0
)
#: Additional ability data.
self.ability_data = (
data["ability"][" | ability_command_data"] if self.has_ability else 0
)
#: Unique identifier for the ability
self.ability_id = self.ability_link << 5 | self.command_index
#: A reference to the ability being used
self.ability = None
#: A shortcut to the name of the ability being used
... |
skirsdeda/djangocms-blog | djangocms_blog/migrations/0014_auto_20160215_1331.py | Python | bsd-3-clause | 1,773 | 0.003384 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from cms.models import Page
from cms.utils.i18n import get_language_list
from django.db import migrations, models
def forwards(apps, schema_editor):
BlogConfig = apps.get_model('djangocms_blog', 'BlogConfig')
BlogConfigTranslation = apps.get_mod... | ects.drafts().filter(application_urls='BlogApp'):
config, created = BlogConfig.objects.get_or_create(namespace=page.application_namespace)
if not BlogConfigTranslation.objects.exists():
for lang in get_language_list():
| title = page.get_title(lang)
translation = BlogConfigTranslation.objects.create(language_code=lang, master_id=config.pk, app_title=title)
if config:
for model in (Post, BlogCategory, GenericBlogPlugin, LatestPostsPlugin, AuthorEntriesPlugin):
for item in model.objec... |
ifduyue/sentry | tests/sentry/integrations/vsts/test_integration.py | Python | bsd-3-clause | 12,757 | 0.000392 | from __future__ import absolute_import
from sentry.identity.vsts import VSTSIdentityProvider
from sentry.integrations.exceptions import IntegrationError
from sentry.integrations.vsts import VstsIntegration, VstsIntegrationProvider
from sentry.models import (
Integration, IntegrationExternalProject, OrganizationIn... | ins import plugins
from tests.sentry.plugins.testutils import VstsPlugin # NOQA
from .testutils import VstsIntegrationTestCase, CREATE_SUBSCRIPTION
class VstsIntegrationProviderTest(VstsIntegrationTestCase):
# Test data setup in ``VstsIntegrationTestCase``
def test_basic_ | flow(self):
self.assert_installation()
integration = Integration.objects.get(provider='vsts')
assert integration.external_id == self.vsts_account_id
assert integration.name == self.vsts_account_name
metadata = integration.metadata
assert metadata['scopes'] == list(VSTS... |
mthpower/timeline-blog | timeline/timeline/settings.py | Python | mit | 2,922 | 0.000342 | """
Django settings for timeline project.
For more information on this file, see
https://docs.djangoproject.com/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 paths inside the project like this: os.p | ath.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 production secret!
SECRET_KEY = 'nv&mfrq1ou*#1%... |
kytos/kytos-utils | kytos/cli/commands/web/api.py | Python | mit | 986 | 0 | """Translate cli commands to non-cli code."""
import logging
from urllib.error import HTTPError, URLError
import requests
from kytos.utils.config import KytosConfig
LOG = logging.getLogger(__name__)
class WebAPI: # pylint: disable=too-few-public-methods
"""An API for the command-line interface."""
@class... | _api}api/kytos/core/web/update"
version = args["<version>"]
if version:
url += f"/{version}"
try:
result = requests.post(url)
except(HTTPError, URLError, requests.exceptions.ConnectionError):
LOG.error(" | Can't connect to server: %s", kytos_api)
return
if result.status_code != 200:
LOG.info("Error while updating web ui: %s", result.content)
else:
LOG.info("Web UI updated.")
|
fredericlepied/os-net-config | os_net_config/tests/test_cli.py | Python | apache-2.0 | 4,656 | 0 | # -*- coding: utf-8 -*-
# Copyright 2014 Red Hat, 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 l... | , 'bond.yaml')
bond_json = os.path.join(SAMPLE_BASE, 'bond.json')
stdout_yaml, stderr = self.run_cli('ARG0 --pr | ovider=ifcfg --noop '
'-c %s' % bond_yaml)
self.assertEqual('', stderr)
stdout_json, stderr = self.run_cli('ARG0 --provider=ifcfg --noop '
'-c %s' % bond_json)
self.assertEqual('', stderr)
sanity_device... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.