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 |
|---|---|---|---|---|---|---|---|---|
xujun10110/AIL-framework | bin/packages/lib_words.py | Python | agpl-3.0 | 3,335 | 0.001499 | import os
import string
from pubsublogger import publisher
import calendar
from datetime import date
from dateutil.rrule import rrule, DAILY
import csv
def listdirectory(path):
"""Path Traversing Function.
:param path: -- The absolute pathname to a directory.
This function is returning all the absolut... | correct.
"""
first_day = date(year, month, 01)
last_day = date(year, month, calendar.monthrange(year, | month)[1])
words = []
with open(feederfilename, 'rb') as f:
# words of the files
words = sorted([word.strip() for word in f])
headers = ['Date'] + words
with open(csvfilename+'.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerow(headers)
# for each days
... |
Cyberbio-Lab/bcbio-nextgen | bcbio/rnaseq/count.py | Python | mit | 2,271 | 0.001321 | """
count number of reads mapping to features of transcripts
"""
import os
import sys
import itertools
import pandas as pd
import gffutils
from bcbio.utils import file_exists
from bcbio.distributed.transaction import file_transaction
from bcbio.log | import log | ger
from bcbio import bam
import bcbio.pipeline.datadict as dd
def combine_count_files(files, out_file=None, ext=".fpkm"):
"""
combine a set of count files into a single combined file
"""
assert all([file_exists(x) for x in files]), \
"Some count files in %s do not exist." % files
for f in ... |
rajeevs1992/pyhealthvault | src/healthvaultlib/itemtypes/height.py | Python | mit | 2,163 | 0.001387 | from lxml import etree
from healthvaultlib.itemtypes.healthrecorditem import HealthRecordItem
from healthvaultlib.utils.xmlutils import XmlUtils
class Height(HealthRecordItem):
def __init__(self, thing_xml=None):
super(Height, self).__init__()
self.type_id = '40750a6a-89b2-455c-bd8d-b420a4cb500b'... | r(Height, self).write_xml()
data_xml = etree.Element('data-xml')
height = etree.Element('height')
| height.append(self.get_when_node('when', self.when))
value = etree.Element('value')
m = etree.Element('m')
m.text = str(self.value_m)
value.append(m)
if self.display_value is not None and self.display_units is not None:
display = etree.Element('display')
... |
pvtodorov/indra | indra/benchmarks/assembly_eval/combine4/run_combined.py | Python | bsd-2-clause | 1,490 | 0 | import os
import csv
import pickle
from indra.literature import id_lookup
from indra.sources import trips, reach, index_cards
from assembly_eval import have_file, run_assembly
if __name__ == '__main__':
pmc_ids = [s.strip() for s in open('pmcids.txt', 'rt').readlines()]
# Load the REACH reading output
wit... | tp = trips.process_xml(open(trips_fname).read())
# Get REACH statements
reach_stmts_for_pmcid = reach_stmts.get(pmcid_to_pmid[pmcid], [])
if not re | ach_stmts_for_pmcid:
print "No REACH statements for %s" % pmcid
# Get NACTEM/ISI statements
fname = 'nactem/' + pmcid + '.cards'
if not os.path.exists(fname):
nactem_stmts = []
else:
icp = index_cards.process_json_file(fname, 'nactem')
nact... |
chromium/chromium | third_party/blink/renderer/bindings/scripts/web_idl/typedef.py | Python | bsd-3-clause | 1,678 | 0 | # Copyright 2017 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.
from .code_generator_info import CodeGeneratorInfo
from .composition_parts import WithCodeGeneratorInfo
from .composition_parts import WithComponent
from .co... | ype
@property
def idl_type(self):
"""Returns the typedef'ed type."""
return self._idl_typ | e
|
mscuthbert/abjad | abjad/tools/labeltools/label_leaves_in_expr_with_numbered_intervals.py | Python | gpl-3.0 | 1,783 | 0 | # -*- encoding: utf-8 -*-
from abjad.tools import scoretools
from abjad.tools import scoretools
from abjad.tools import markuptools
from abjad.tools import scoretools
from abjad.tools import pitchtools
from abjad.tools.topleveltools import attach
from abjad.tools.topleveltools import iterate
def label_leaves_in_expr_... | 25, 11, -4, -14, -13, 9, 10, 6, 5],
... [Duration(1, 8)],
... )
>>> staff = Staff(notes)
>>> labeltools.la | bel_leaves_in_expr_with_numbered_intervals(staff)
.. doctest::
>>> print(format(staff))
\new Staff {
c'8 ^ \markup { +25 }
cs'''8 ^ \markup { -14 }
b'8 ^ \markup { -15 }
af8 ^ \markup { -10 }
bf,8 ^ \markup { +1 }
b,8 ^ \mark... |
luckylavish/zamboni | mkt/developers/views_payments.py | Python | bsd-3-clause | 20,258 | 0 | import functools
import json
import urllib
from django import http
from django.conf import settings
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.http import require_POST
import commonware
... | log.error('Error saving payment information (%s)' % err)
messages.error(
request, _(u'We en | countered a problem connecting to '
u'the payment server.'))
success = False
raise # We want to see all the solitude errors now.
# If everything happened successfully, give the user a pat on the back.
if success:
me... |
jkyeung/XlsxWriter | xlsxwriter/test/comparison/test_chart_title01.py | Python | bsd-2-clause | 1,535 | 0 | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... | xlsx_files/' + filename
self.ignore_files = []
self.ignore_elements = {}
def test_create_file(self):
"""Test the creation of an XlsxWriter file with default title."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_workshe | et()
chart = workbook.add_chart({'type': 'column'})
chart.axis_ids = [46165376, 54462720]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column('A1', data[0])
worksheet.write_column('B1', data[1])
... |
google/tf-quant-finance | tf_quant_finance/__init__.py | Python | apache-2.0 | 3,356 | 0.006853 | # Lint as: python3
# Copyright 2019 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | # pylint: disable=g-statement-before-imports
"""Attempt to import tensorflow, and ensure its version is sufficient.
Raises:
ImportError: if either tensorflow is not importable or its version is
inadequate.
"""
try:
import tensorflow.compat.v2 as tf
except ImportError:
# Print | more informative error message, then reraise.
print("\n\nFailed to import TensorFlow. Please note that TensorFlow is not "
"installed by default when you install TF Quant Finance library. "
"This is so that users can decide whether to install the GPU-enabled "
"TensorFlow package. To u... |
ferriman/SSandSP | processing/spiritOfBCN/getdata.py | Python | gpl-3.0 | 4,690 | 0.042857 | import random
perc2015 = []
perc2016 = []
perc2017 = []
perc2018 = []
perc2019 = []
def getColor(pais):
foundColor = 0
theColor = 0x000000
for elem in perc2015:
if elem[0]==pais:
theColor = elem[2]
foundColor = 1
for elem in perc2016:
if elem[0]==pais:
theColor = elem[2]
foundColor = 1
for elem i... | pais:
theColor = elem[2]
foundColor = 1
if foundColor == 0:
theColor = "%06x" % random.randint(0, 0xFFFFFF)
return theColor
total = 0
with open('2015_naixements_lloc-de-naixement.c | sv') as data:
for line in data:
fields = line.split(",")
#print(line)
#print(fields[len(fields)-1],fields[len(fields)-2])
found = 0
total = total + int(fields[len(fields)-1])
for elem in perc2015:
if elem[0] == fields[len(fields)-2].replace('"',''):
elem[1] = elem[1] + int(fields[len(fields)-1])
... |
turbidsoul/isort | sort.py | Python | mit | 556 | 0.003597 | import sublime
import sublime_plugin
from isort.isort import SortImports
class PysortCommand(sublime | _plugin.TextCommand):
def run(self, edit):
old_content = self.view.substr(sublime.Region(0, self.view.size()))
| new_content = SortImports(file_contents=old_content).output
self.view.replace(edit, sublime.Region(0, self.view.size()), new_content)
sublime.status_message("Python sort import complete.")
sublime.run_command('sub_notify', {'title': 'ISort', 'msg': 'Python sort import complete.', 'sound': ... |
AMOboxTV/AMOBox.LegoBuild | script.extendedinfo/resources/lib/WindowManager.py | Python | gpl-2.0 | 12,611 | 0.000793 | # -*- coding: utf8 -*-
# Copyright (C) 2015 - Philipp Temminghoff <phil65@kodi.tv>
# This program is Free Software see LICENSE file for details
from Utils import *
import xbmc
import xbmcaddon
import xbmcgui
import xbmcvfs
import os
from dialogs import BaseClasses
from LocalDB import local_db
import TheMovieDB
ADD... | os.path.join(path, LIST_DIALOG_FILE))
if not xbmcvfs.exists(os.path.join(path, ACTOR_DIAL | OG_FILE)):
xbmcvfs.copy(strSource=os.path.join(path, ACTOR_DIALOG_FILE_CLASSIC),
strDestnation=os.path.join(path, ACTOR_DIALOG_FILE))
else:
INFO_DIALOG_FILE = INFO_DIALOG_FILE_CLASSIC
LIST_DIALOG_FILE = LIST_DIALOG_FILE_CLASSIC
ACTOR_DIALOG_FILE = ACTOR_DIALOG_FILE_CLASSIC
cla... |
WIStCart/V3ValidationTool | V6ValidationTool_dist/script/LegacyCountyStats.py | Python | mit | 53,028 | 0.114053 | ADAMSLegacyDict = {'STATEID':38629,'PARCELID':38382,'TAXPARCELID':0,'PARCELDATE':38629,'TAXROLLYEAR':38629,'OWNERNME1':38198,'OWNERNME2':12641,'PSTLADRESS':38177,'SITEADRESS':22625,'ADDNUMPREFIX':28,'ADDNUM':22625,'ADDNUMSUFFIX':750,'PREFIX':6195,'STREETNAME':22625,'STREETTYPE':19749,'SUFFIX':1,'LANDMARKNAME':33,'UNITT... | RRONLegacyDict = {'STATEID':44181,'PARCELID':44181,'TAXPARCELID':0,'PARCELDATE':44181,'TAXROLLYEAR':44181,'OWNERNME1':41996,'OWNERNME2':4424,'PSTLADRESS':41996,'SITEADRESS':23451,'ADDNUMPREFIX':0,'ADDNUM':23451,'ADDNUMSUFFIX':526,'PREFIX':3546,'STREETNAME':23451,'STREETTYPE':23170,'SUFFIX':898,'LANDMARKNAME':0,'UNITTYP... | IP4':0,'STATE':44181,'SCHOOLDIST':41996,'SCHOOLDISTNO':41996,'CNTASSDVALUE':37592,'LNDVALUE':37592,'IMPVALUE':37590,'ESTFMKVALUE':23332,'NETPRPTA':37592,'GRSPRPTA':0,'PROPCLASS':37592,'AUXCLASS':4704,'ASSDACRES':38644,'DEEDACRES':41996,'GISACRES':0,'CONAME':44181,'LOADDATE':44181,'PARCELFIPS':44181,'PARCELSRC':44181,'L... |
cybert79/HaXor | boot2root-scripts/dvwa-login-bruteforce-http-post-csrf.py | Python | unlicense | 3,803 | 0.004207 | #!/usr/bin/python
# Quick PoC template for HTTP POST form brute force, with anti-CRSF token
# Target: DVWA v1.10
# Date: 2015-10-19
# Author: g0tmi1k ~ https://blog.g0tmi1k.com/
# Source: https://blog.g0tmi1k.com/2015/10/dvwa-login/
import requests
import sys
import re
from BeautifulSoup import BeautifulSoup
# Var... | % target
#print "[i] Data: %s" % data
#print "[i] Cookie: %s" % cookie
r = requests.post("{0}/login.php".format(ta | rget), data=data, cookies=cookie, allow_redirects=False)
except:
# Feedback for the user (there was an error) & Stop execution of our request
print "\n\n[!] url_request: Failed to connect (URL: %s/vulnerabilities/brute/).\n[i] Quitting." % (target)
sys.exit(-1)
# Wasn't it a redirect?
... |
Jonothompson/my-django-blog | mysite/settings.py | Python | mit | 2,696 | 0.000371 | """
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.8.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths... | tionMiddleware',
| 'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
... |
sbailey/redrock | py/redrock/test/test_io.py | Python | bsd-3-clause | 3,397 | 0.003827 | from __future__ import division, print_function
import os
import unittest
from uuid import uuid1
import numpy as np
from .. import utils as rrutils
from ..results import read_zscan, write_zscan
from ..templates import DistTemplate, find_templates, load_dist_templates
from ..zfind import zfind
from . import util
cl... | dtarg = util.fake_targets()
# Get the dictionary of wavelength grids
dwave = dtarg.wavegrids()
# Construct the distributed template.
template = util.get_template(subtype='BLAT')
dtemp = DistTemplate(template, dwave)
zscan1, zfit1 = zfind(dtarg, [ dtemp ])
... | olnames, zfit2.colnames)
for cn in zfit1.colnames:
np.testing.assert_equal(zfit1[cn], zfit2[cn])
for targetid in zscan1:
for spectype in zscan1[targetid]:
for key in zscan1[targetid][spectype]:
d1 = zscan1[targetid][spectype][key]
... |
kevin8909/xjerp | openerp/addons/Rainsoft_Xiangjie/rainsoft_account_invoice.py | Python | agpl-3.0 | 2,540 | 0.062205 | # -*- coding: utf-8 -*-
from openerp.osv import fields, osv
import openerp.addons.decimal_precision as dp
class rainsoft_account_invoice(osv.osv):
_name='account.invoice'
_inherit = 'account.invoice'
_columns={
'p_comment':fields.related('partner_id','comment',type='text',relation='r... | count.invoice.line"
def _get_average_price(self,cr,uid,ids,fields,args,context=None):
res={}
if not context.has_key('period'):
for i_id in ids:
res[i_id]={
'average_price':0.0,
'cost_amount':0. | 0,
}
return res
period = context['period']
for i_id in ids:
invoice = self.browse(cr,uid,i_id)
#check if the product is phantom type
boms_id = self.pool.get('mrp.bom').search(cr,uid,[('product_id','=',invoice.product_id.id),('type','=','phantom')],context=context)
if ... |
LordGaav/notification-scripts | slack.py | Python | mit | 3,578 | 0 | #!/usr/bin/env python3
#
# Copyright (c) 2017 Nick Douma
#
# 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, copy, modify,... | ED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from argparse import ArgumentParser, ArgumentTypeError
import datetime
import json
import re
import urllib.error
import urllib.parse
import urllib... |
jmcnamara/XlsxWriter | xlsxwriter/test/comparison/test_hyperlink31.py | Python | bsd-2-clause | 929 | 0 | ###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompar... | hyperlink31.xlsx')
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with hyperlinks."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
format1 = workbook.add_format({'bold': True})
worksheet.write('A1', 'Test', form... | worksheet.write('A3', 'http://www.python.org/')
workbook.close()
self.assertExcelEqual()
|
stopstalk/stopstalk-deployment | private/scripts/populate-atcoder-problems.py | Python | mit | 1,810 | 0.003867 | """
Copyright (c) 2015-2020 Raj Patel(raj454raj@gmail.com), StopStalk
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and assoc | iated documentation files (the "Software"), to deal
in | the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice a... |
mgood/flask-failsafe | setup.py | Python | bsd-2-clause | 1,085 | 0.000922 | import os
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.rst') | ).read()
except:
README = ''
CHANGES = ''
setup(
name='Flask-Failsafe',
version='0.2',
url='http://github.com/mgood/flask-failsafe',
license='BSD',
author='Matt Good',
author_email='matt@matt-good.net',
description='A failsafe for the Flask reloader',
long_description=README + ... | onment :: Web Environment',
'Framework :: Flask',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Sof... |
vmanoria/bluemix-hue-filebrowser | hue-3.8.1-bluemix/apps/sqoop/src/sqoop/settings.py | Python | gpl-2.0 | 916 | 0 | # Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use thi | s file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licens | es/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 permissions and
# limitations under ... |
maddiestone/IDAPythonEmbeddedToolkit | make_strings.py | Python | mit | 3,874 | 0.019102 | ##############################################################################################
# Copyright 2017 The Johns Hopkins University Applied Physics Laboratory LLC
# All rights reserved.
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documen... | acters", does not meet the minimum string length, or is not an ASCII character
break
string_start += 1
print "[make_strings.py] FINISHED. Created %d strings in range 0x%x to 0x%x" % (num_strings, | start_addr, end_addr)
else:
print "[make_strings.py] QUITTING. Entered address values not valid." |
dnjohnstone/hyperspy | hyperspy/tests/model/test_set_parameter_state.py | Python | gpl-3.0 | 4,051 | 0 | # -*- coding: utf-8 -*-
# Copyright 2007-2020 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy 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... | _set_parameter_in_model_not_free(self):
m = self.model
g | 1 = self.g1
g2 = self.g2
g3 = self.g3
m.set_parameters_not_free()
assert len(g1.free_parameters) == 0
assert len(g2.free_parameters) == 0
assert len(g3.free_parameters) == 0
def test_set_parameter_in_model_free(self):
m = self.model
g1 = self.g1
... |
samini/gort-public | Source/Squiddy/src/tema-android-adapter-3.2-sma/AndroidAdapter/adbcommands.py | Python | apache-2.0 | 11,424 | 0.037728 | #
# Copyright 2014 Shahriyar Amini
#
# 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 wri... | urn None
commandArray = ["adb", "-s", serial_id, "shell", "date", '+"%s"']
output = None
try:
output = | subprocess.check_output(commandArray, stderr = subprocess.PIPE)
except AttributeError:
output = subprocess.Popen(commandArray, stdout = subprocess.PIPE).communicate()[0]
except subprocess.CalledProcessError:
pass
if output is None:
return None
return float(output)
def focusedActivity(serial_id):
tmp = r... |
sinnwerkstatt/landmatrix | config/settings/base.py | Python | agpl-3.0 | 7,018 | 0.000428 | import sys
import environ
from django.utils.translation import ugettext_lazy as _
BASE_DIR = environ.Path(__file__) - 3 # type: environ.Path
env = environ.Env()
env.read_env(BASE_DIR(".env"))
LANGUAGE_CODE = "en"
LANGUAGES = [("en", _("English")), ("es", _("Español")), ("fr", _("Français"))]
TIME_ZONE = "Europe/Be... | context_processors.messages",
"django.template.context_processors.i18n",
| "django.template.context_processors.media",
"apps.wagtailcms.context_processors.add_data_source_dir",
]
},
}
]
LOGIN_REDIRECT_URL = "/editor/"
# Limit all uploads to 20MB, and data sources to 1MB
MAX_UPLOAD_SIZE = 20971520
DATA_SOURCE_MAX_UPLOAD_SIZE = 10485760
DATA_SOURCE_D... |
hzj123/56th | pombola/info/models.py | Python | agpl-3.0 | 6,304 | 0.005235 | import datetime
import lxml
from lxml.html.clean import Cleaner
import re
from django.conf import settings
from django.db import models
from django.core.urlresolvers import reverse
from django.utils.text import slugify
from markitup.fields import MarkupField
class ModelBase(models.Model):
created = models.DateTi... | cleaner = Cleaner(style=True, scripts=True)
return cleaner.clean_html(html)
@property
def content_as_html(self):
if settings.INFO_PAGES_ALLOW_RAW_HTML and self.use_raw:
# Parsing the HTML with lxml and outputting it again
# should ensure that we have only well-formed HTM... | arsed, method='html')
else:
# Since there seems to be some doubt about whether
# markdown's safe_mode is really safe, clean the rendered
# HTML to remove any potentially dangerous tags first
return self._clean_html(self.markdown_content.rendered or '')
@prope... |
fearedbliss/bliss-initramfs | pkg/hooks/Hook.py | Python | apache-2.0 | 2,523 | 0 | # Copyright (C) 2012-2020 Jonathan Vasquez <jon@xyinn.org>
#
# 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 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 permissions an... | 0
_use_man = 0
_files = []
_optional_files = []
_directories = []
_man = []
@classmethod
def Enable(cls):
"""Enables this hook."""
cls._use = 1
@classmethod
def Disable(cls):
"""Disables this hook."""
cls._use = 0
@classmethod
def EnableMan(... |
AdamDynamic/TwitterMetrics | KeywordSearch.py | Python | gpl-2.0 | 7,402 | 0.010267 | #!/usr/bin/env python
import MySQLdb
import string
import logging
import Reference as r
def CalculateWordCount(InputList,MatchList):
'''Counts the instance of MatchList values in the InputList'''
NumberOfMatches = 0
for w in InputList:
NumberOfMatches += MatchList.count(w)
retur... | ultsDict['positive'] = ResultsDict['positive'] + CalculateWordCount(ResultAsList, WordListPositive)
ResultsDict['strong'] = ResultsDict['strong'] + Calculate | WordCount(ResultAsList, WordListStrong)
ResultsDict['hostile'] = ResultsDict['hostile'] + CalculateWordCount(ResultAsList, WordListHostile)
ResultsDict['power'] = ResultsDict['power'] + CalculateWordCount(ResultAsList, WordListPower)
ResultsDict['weak'] = ResultsDict['weak'] + CalculateWordCount... |
akshbn/pygron | setup.py | Python | mit | 330 | 0.087879 | from setuptools import setup,find_pack | ages
setup(
name = 'pygron',
version = '0.3.1',
license = 'MIT',
author = 'Akshay B N',
description = 'Helps JSON become greppable',
zip_safe = False,
url = 'https://github.com/akshbn/pygron',
packages = find_packages(),
entry_points = {"console_scripts":["py | gron=pygron.cli_entry:main"]}
)
|
xhan-shannon/SystemControlView | utils/ReportGenerator.py | Python | gpl-2.0 | 460,449 | 0.012301 | #!/usr/bin/python
""" The report generator handles commands from the user to configure reports,
then obtains the data from the requested file,
then writes the report file.
"""
import rxt
import os
import sys
import locale
import traceback
import simpl
import simplejson
import time
import datetime
import csv
im... | port=%s' % (self.temp_report_path, self.report_path))
# Create /home/Sunrise/report_temp if it doesn not exists
if not os.path.isdir(self.temp_report_path):
try:
os.mkdir(self.temp_report_path)
except:
self.write_log('Test Cannot Create %s' % sel... | t doesn not exists
if not os.path.isdir(self.report_path):
try:
os.mkdir(self.report_path)
except:
self.write_log('Test Cannot Create %s' % self.report_path, 'Error', sys.exc_info())
# saved data entry
data = None
try:
... |
koreiklein/fantasia | calculus/basic/bifunctor.py | Python | gpl-2.0 | 13,217 | 0.019747 | # Copyright (C) 2013 Korei Klein <korei.klein1@gmail.com>
from misc import *
from calculus import variable
from lib import common_vars
from lib.common_symbols import domainSymbol, relationSymbol, leftSymbol, rightSymbol
from calculus.basic import endofunctor
from calculus.basic import formula
class UntransportableExc... | portLeft(self, B):
return (lambda x, y:
self.bifunctor._importRight(B)(y, x))
def | _importRight(self, B):
return (lambda x, y:
self.bifunctor._importLeft(B)(y, x))
def _liftLeft(self, B):
# May throw an exception.
lift = self.bifunctor._liftRight(B)
return (lambda x, y:
lift(y, x))
def _liftRight(self, B):
# May throw an exception.
lift = self.bifunctor._li... |
dlundquist/ansible | lib/ansible/runner/__init__.py | Python | gpl-3.0 | 55,816 | 0.005518 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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) an... | vars_cache=None, # used to store variables about hosts
tr | ansport=C.DEFAULT_TRANSPORT, # 'ssh', 'paramiko', 'local'
conditional='True', # run only if this fact expression evals to true
callbacks=None, # used for output
sudo=False, # whether to run sudo or not
sudo_user=C.DEFAULT_S... |
dyf/primopt | spline.py | Python | bsd-2-clause | 1,314 | 0.019787 | import numpy as np
# f(x) = a*x*x*x + b*x*x + c*x + d
# f'(x) = 3*a*x*x + 2*b*x + c
#
# d = x0
# c = dx0
# a + b + c + d = x1
# 3*a + 2*b + c = dx1
#
# a + b + dx0 + x0 = x1
# a + b = x1 - x0 - dx0
# a = x1 - x0 - dx0 - b
#
# 3*a + 2*b + dx0 = dx1
# 3*a + 2*b = dx1 - dx0
# 3*(x1 - x0 - dx0 - b) + 2*b = dx1 - dx0
# -3... | bic_spline_coeffs(p0, v0, p1, v1):
d = p0
c = v0
b = -v1 + v0 + 3*(p1 - p0 - v0)
a = p1 - p0 - v0 - b
return [a,b,c,d]
def cubic_spline_coeffs_list(ps, vs):
return [ cubic_spline_coeffs(ps[i], vs[i], ps[i+1], vs[i+1]) for i in range(len(ps)-1) ]
def cubic_spline(N, ps=None, vs=None, coeffs_lis... |
vs = []
for a,b,c,d in coeffs_list:
v = a*t**3 + b*t**2 + c*t + d
vs.append(v)
return np.concatenate(vs).T
if __name__ == "__main__":
import matplotlib.pyplot as plt
Np=4
Nt=100
p = np.random.random((Np,2))*2-1
v = np.random.random((Np,2))*2-1
xy = cu... |
JudoWill/glue | glue/core/tests/test_roi.py | Python | bsd-3-clause | 29,076 | 0.000378 | #pylint: disable=I0011,W0613,W0201,W0212,E1101,E1103
from __future__ import absolute_import, division, print_function
import pytest
import numpy as np
from numpy.testing import assert_almost_equal
from matplotlib.figure import Figure
from glue.core.data import CategoricalComponent
from mock import MagicMock
from ..... | self):
self.roi.update_limits(2, 2, 10, 12)
assert self.roi.height() == 10
def test_multidim_ndarray(self):
sel | f.roi.update_limits(0, 0, 10, 10)
x = np.array([1, 2, 3, 4]).reshape(2, 2)
y = np.array([1, 2, 3, 4]).reshape(2, 2)
assert self.roi.contains(x, y).all()
assert not self.roi.contains(x + 10, y).any()
assert self.roi.contains(x, y).shape == x.shape
def test_str_undefined(self)... |
huntie/sublime-tmux | tmux.py | Python | mit | 4,727 | 0.004019 | import sublime
import sublime_plugin
from datetime import datetime
import io
import os
import re
import subprocess
import sys
def get_setting(key, default=None):
settings = sublime.load_settings('tmux.sublime-settings')
os_specific_settings = {}
if sys.platform == 'darwin':
os_specific_settings = ... | n: [
'{}: {} window{}'.format(session['name'], session['windows'], 's'[int(session['windows']) == 1:]),
'{:%c}'.format(datetime.fromtimestamp(int(session['created']))),
'{}x{}{}'.format(session['width'], session['height'], ' (attached)' if int(ses | sion['attached']) else '')
],
sessions
))
def on_session_selected(self, index):
if index == -1:
return
self.command_args.extend(['-t', self.attached_sessions[index]['name'] + ':'])
self.execute()
def run_tmux(self, parameters, split):
... |
endthestart/photocontest | photocontest/photocontest/migrations/0009_auto__del_field_event_date.py | Python | mit | 2,554 | 0.007439 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Event.date'
db.delete_column(u'photocontest_event', 'da... | not deal with backwards NULL issues for 'Event.date'
raise RuntimeError("Cannot reverse this migration. 'Event.date' and its values cannot be restored.")
# The following code is provided here to aid in writing a correct migration # Adding field 'Event.date'
db.add_column(u'photo... | ields.DateField')(),
keep_default=False)
models = {
u'photocontest.event': {
'Meta': {'object_name': 'Event'},
'event_date': ('django.db.models.fields.DateField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
u'id': ('django.db.mo... |
vivianbuan/cs3240-s15-team20 | SecureWitness/accounts/migrations/0006_auto_20150423_1615.py | Python | mit | 454 | 0 | # -*- coding: utf-8 - | *-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('accounts', '0005_auto_20150422_0105'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
... | 15, 4, 23)),
),
]
|
Genomon-Project/GenomonMutationAnnotator | lib/mutanno/annotator.py | Python | lgpl-3.0 | 2,295 | 0.009586 | import sys
import os
import re
import logging
import pysam
#
# Class definitions
#
class annotator:
def __init__(self, tabix_db, header, num | _output_column):
self.tabix_db = tabix_db
self.header = header
self.num_output_column = int(num_output_column)
def annotate(self, in_mutation_file, output):
tb = pysam.TabixFile(self.tabix_db)
# tabix open
srcfile = open(in_mutation_file,'r')
hResult =... | t".join(map(str,header_array))
print >> hResult, (header +"\t"+ newheader)
ori_result = ""
for num in range(self.num_output_column):
ori_result = ori_result + "---\t"
ori_result = ori_result[:-1]
for line in srcfile:
line = line.rstrip()
... |
haikentcode/haios | haios/setup.py | Python | mit | 356 | 0.008427 | from setuptools import setup
setup(name='haios',
version='0.1',
description='Image Se | arch Engine',
url='https://github.com/haikentcode/haios',
author='HITESH KUMAR REGAR (haikent)',
author_email='hiteshnitj16@gmail.com',
license='MIT',
packages=['descriptor','distance','spider','objects'],
z | ip_safe=False)
|
dchaplinsky/LT2OpenCorpora | lt2opencorpora/__init__.py | Python | mit | 121 | 0 | __version | __ = '2.0.3'
try:
from .convert import Dictionary
except ImportError:
# | To make setup.py work
pass
|
endlessm/chromium-browser | third_party/llvm/lldb/test/API/lang/objc/forward-decl/TestForwardDecl.py | Python | bsd-3-clause | 2,454 | 0.000815 | """Test that a forward-declared class works when its complete definition is in a library"""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class ForwardDeclTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def setUp... | debug_info_test
@skipUnlessDarwin
@skipIf(compiler=no_match("clang"))
@skipIf(compiler_version=["<", "7.0"])
def test_debug_names(self):
"""Test that we are able to find complete types when using DWARF v5
accelerator tables"""
self.do_test(
dict(CFLAGS_EXTRAS="-dwarf-... | s=Dwarf"))
|
prospwro/odoo | addons/irsid_base/models/__init__.py | Python | agpl-3.0 | 1,032 | 0.000969 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 OpenERP SA (<http://openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# i | t under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warran... | Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import doc
import doc_signature
#i... |
pyspace/test | pySPACE/resources/dataset_defs/dummy.py | Python | gpl-3.0 | 1,581 | 0.011385 | """ Store only meta data but no real data (except from store state of nodes) """
import logging
import os
import pwd
import yaml
from pySPACE.resources.dataset_defs.base import BaseDataset
class DummyDataset(BaseDataset):
""" Class to store only meta data of collection
This class overrides the 'store' method... | .
This type is intended to be passed to pySPACE as a result
by the NilSinkNode.
**Parameters**
:dataset_md:
The meta data of | the current dataset.
(*optional, default: None*)
:Author: David Feess (david.feess@dfki.de)
:Created: 2010/03/30
"""
def __init__(self, dataset_md = None):
super(DummyDataset, self).__init__(dataset_md = dataset_md)
def store(self, result_dir, s_format = "None"):
if n... |
StarbotDiscord/Starbot | libs/displayname.py | Python | apache-2.0 | 6,488 | 0.013255 | # Copyright (c) 2017 CorpNewt
#
# This software is released under the MIT License.
# https://opensource.org/licenses/MIT
import discord
def name(member : discord.Member):
# A helper function to return the member's display name
nick = name = None
try:
nick = member.nick
except AttributeError:
... | if newMem:
# We FOUND it!
return { "Role" : newMem, "Int" : theInt }
else:
# Nothing was right about this...
return { "Role" : None, "Int" : None }
except ValueError:
# Last section wasn't an int
amember = roleForName(nam... | eck if we got an ID instead
# Get just the numbers
memID = ''.join(list(filter(str.isdigit, name)))
newMem = roleForID(memID, server)
if newMem:
# We FOUND it!
return { "Role" : newMem, "Int" : None }
else:
# Not... |
mbohlool/client-python | kubernetes/client/models/v1_group_version_for_discovery.py | Python | apache-2.0 | 4,487 | 0.002006 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.8.2
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
... |
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'group_version': 'str',
'version': ... | }
def __init__(self, group_version=None, version=None):
"""
V1GroupVersionForDiscovery - a model defined in Swagger
"""
self._group_version = None
self._version = None
self.discriminator = None
self.group_version = group_version
self.version = vers... |
ludobox/ludobox | server/tests/test_routes_api.py | Python | agpl-3.0 | 9,003 | 0.00411 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
from ludobox.content import read_content
from ludobox.routes.api import rest_api
# test helpers
from LudoboxTestCase import LudoboxTestCase
from helpers import delete_data_path, create_empty_data_path, add_samples_to_data_dir
class TestLudoboxWebSe... | A_DIR"])
create_empty_data_path(self.app.config["DATA_DIR"])
data = {
'files': self.files,
'info': json.dumps(valid_info)
}
with self.app.test_client() as c:
result = c.post('/api/create',
data=data,
... | form-data'
)
print result.data
self.assertEqual(result.status_code, 403)
def test_api_create_content(self):
# create empy path for data
delete_data_path(self.tmp_path)
create_empty_data_path(self.tmp_path)
# load info wi... |
CMPUT404W17T06/CMPUT404-project | dash/migrations/0003_auto_20170313_0117.py | Python | apache-2.0 | 497 | 0.002012 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-13 01:17
from __future__ import unicode_literals
from django.db import migrations, models
import uuid
|
class Migration(migrations.Migration):
dependencies = [
('dash', '0002_remove_post_origin'),
]
operations = [
migrations.AlterField(
model_name='comment',
name | ='id',
field=models.UUIDField(default=uuid.uuid4, primary_key=True, serialize=False),
),
]
|
ATRAN2/Futami | futami/ami.py | Python | gpl-2.0 | 7,977 | 0.001128 | # -*- coding: utf-8 -*-
from collections import defaultdict
from itertools import chain
from functools import wraps
from operator import itemgetter
from multiprocessing import (
current_process,
SimpleQueue,
Process,
)
from time import sleep
import logging
import sys
import traceback
from retrying import ... | en_threads = defaultdict(lambda: defaultdict(list))
while True:
# Process pending update requests
| while not update_request_queue.empty():
request = update_request_queue.get()
if request.action is Action.InternalQueueUpdate:
if isinstance(request.target, BoardTarget):
watched_boards.add(request.target.board)
see... |
Connexions/nebuchadnezzar | nebu/models/utils.py | Python | agpl-3.0 | 5,088 | 0 | from copy import copy
import json
from cnxepub.utils import squash_xml_to_text
from cnxml.parse import parse_metadata as parse_cnxml_metadata
from cnxtransforms import cnxml_abstract_to_html
from lxml import etree
__all__ = (
'convert_to_model_compat_metadata',
'scan_for_id_mapping',
'scan_for_uuid_mappi... | _metadata(parse_cnxml_metadata(xml))
id = id_from_metadata(md)
id = id.split('@')[0]
mapping[id] = filepath
return mapping
def scan_for_uuid_mapping(start_dir):
"""Collect a mapping of content UUIDs to filepaths relative to the given
directory (as ``start_dir``).
This is simil... | found in CNXML as the key, we want the same mapping keyed by the
UUID in the corresponding metadata.json file if it's available.
:param start_dir: a directory to start the scan from
:type start_dir: :class:`pathlib.Path`
:return: mapping of content uuids to the content filepath
:rtype: {str: pathli... |
jaduff/goodstanding | goodstanding/models.py | Python | bsd-3-clause | 2,768 | 0.004335 | from sqlalchemy import (
Column,
Index,
Integer,
Text,
Table,
ForeignKey,
String,
Boolean,
DateTime,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
relationship,
)
from zope.sqlalchemy import... | Student.id),
lazy='dynamic')
|
class gsClassNote(Base):
__tablename__ = 'gsClassNote'
Noteid = Column(Integer, primary_key=True)
classStudentid = Column(Integer, ForeignKey('gsClassStudent.id'))
note = Column(Text, index=False, unique=False)
value = Column(Integer, index=False)
date = Column(D... |
NickMolloy/rt_api | tests/mock_api.py | Python | gpl-3.0 | 935 | 0.002139 | from httmock import all_requests
@all_requests
def non_json_episode_response(url, request):
return {'status_code': 200, 'content': None}
@all_requests
def unauthorized_episode_response(url, request):
return {'status_code': 401, 'content': '{"error": "access_denied", "error_message": "The resource owner or a... | _repsonse_for_authentication(url, request):
return {'status_code': 500, 'content': 'Something went wrong.'}
@all_requests
def test_forbidden_repsonse_for_authentication(url, request):
return {'stat | us_code': 403, 'content': '{"error": "access_denied"}'}
|
Southpaw-TACTIC/TACTIC | src/test/pipeline_test.py | Python | epl-1.0 | 143 | 0.013986 |
import tacticenv
import unittest
from pyasm.security import B | atch
Batch()
from pyasm.biz.pipeline_test impor | t ProcessTest
unittest.main()
|
cosmos342/VisionClassifier | vgg16.py | Python | mit | 8,410 | 0.005589 | # -*- coding: utf-8 -*-
"""VGG16 model for Keras.
# Reference
- [Very Deep Convolutional Networks for Large-Scale Image Recognition](https://arxiv.org/abs/1409.1556)
"""
from __future__ import print_function
from __future__ import absolute_import
import warnings
from keras.models import Model
from keras.layers imp... | onal shape tuple, only to be specified
if `include_top` is False (otherwise the input shape
has to be `(224, 224, 3)` (with `tf` dim ordering)
or `(3, 224, 244)` (with `th` dim ordering).
It should have exactly 3 inputs channels,
and width and height should be... | pecified if `include_top` is True, and
if no `weights` argument is specified.
# Returns
A Keras model instance.
"""
if weights not in {'imagenet', None}:
raise ValueError('The `weights` argument should be either '
'`None` (random initialization) or `imag... |
hamasho/endojo | apps/games/listening/models.py | Python | gpl-3.0 | 4,489 | 0 | import os
import datetime
from datetime import timedelta
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from core.utils import date_range
class Package(models.Model):
title = models.CharField(max_length=200, unique=True)
level = models.SmallIntegerF... | ing_packagestate_user')
package = models.ForeignKey(Package)
complete = models.BooleanField(default=True)
class Meta:
unique_together = ('user', 'package')
class ProblemScore(models.Model):
user = models.ForeignKey(User, related_name='listening_problemscore_user')
problem = models.Foreign... | )
complete = models.BooleanField(default=True)
update_date = models.DateTimeField(default=timezone.now)
class Meta:
unique_together = ('user', 'problem')
def save(self, *args, **kwargs):
"""
When saving scores, also have to update History model.
"""
if self.comp... |
nanounanue/rita-pipeline | rita/pipelines/rita.py | Python | gpl-3.0 | 6,982 | 0.006307 | # coding: utf-8
"""
rita Pipeline
.. module:: rita
:synopsis: rita pipeline
.. moduleauthor:: Adolfo De Unánue <nanounanue@gmail.com>
"""
import os
import subprocess
from pathlib import Path
import boto3
import zipfile
import io
import csv
import datetime
import luigi
import luigi.s3
import pandas as pd
... | rite(df.loc[:, 'YEAR':'DIV_AIRPORT_LANDINGS'].to_csv(None,
sep="|",
header=True,
| index=False,
encoding="utf-8",
quoting=csv.QUOTE_ALL))
def output(self):
return luigi.s3.S3Target('{}/{}/{}/YEAR={}/{}.psv'... |
ovaistariq/mha-helper | mha_helper/config_helper.py | Python | gpl-3.0 | 8,633 | 0.00278 | # (c) 2015, Ovais Tariq <me@ovaistariq.net>
#
# This file is part of mha_helper
#
# 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... | hostname = hostname[:-1] # strip exactly one dot from the right, if present
allowed = re.compile("(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)
if not all(allowed.match(x) for x in hostname.split(".")):
return False
# Now we try to resolve the hostname and error out if we cannot
... | ))
return False
return True
def __init__(self, host):
self._host = host
if host not in self.__class__.host_config:
raise ValueError
self._host_config = self.__class__.host_config[host]
def get_writer_vip(self):
return self.get_writer_vip_cidr()... |
taulk/oj | LeetCode/[11]container-with-most-water/Solution.py | Python | unlicense | 395 | 0.002532 | class Solution(object):
def maxArea(self, height):
"""
:ty | pe height: List[int]
:rtype: int
"""
i = 0
j = len(height)-1
| res = 0
while i<j:
res = max(res, min(height[i], height[j]) * (j-i))
if height[i] > height[j]:
j = j - 1
else:
i = i + 1
return res
|
opennetworkinglab/spring-open-cli | cli/storeclient.py | Python | epl-1.0 | 15,736 | 0.005719 | #
# Copyright (c) 2010,2011,2012,2013 Big Switch Networks, Inc.
#
# Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html
#
# Unless required ... | ata/"
sdn_platform_data_url | = "http://%s/rest/v1/system/"
def set_controller(self,controller):
self.controller = controller
def display_mode(self, mode):
self.display_rest = mode
def display_reply_mode(self, mode):
self.display_rest_reply = mode
def set_sdn_controller_platform_rest_if(self, sdn_... |
seckcoder/lang-learn | python/sklearn/sklearn/tree/tests/test_tree.py | Python | unlicense | 15,491 | 0.001291 | """
Testing for the tree module (sklearn.tree).
"""
import numpy as np
from numpy.testing import assert_array_equal
from numpy.testing import assert_array_almost_equal
from numpy.testing import assert_almost_equal
from numpy.testing import assert_equal
from nose.tools import assert_raises
from nose.tools import assert... | it
iris = datasets.load_iris()
rng = np.random.RandomState(1)
perm = rng.permutation(iris.target.size)
iris.data = iris.data[perm]
iris.target = iris.target[perm]
# also load the boston dataset
# and randomly permute it
boston = datasets.load_boston()
perm = rng.permutation(boston.target.size)
boston.data = boston.dat... | cisionTreeClassifier()
clf.fit(X, y)
assert_array_equal(clf.predict(T), true_result)
# With subsampling
clf = tree.DecisionTreeClassifier(max_features=1, random_state=1)
clf.fit(X, y)
assert_array_equal(clf.predict(T), true_result)
def test_regression_toy():
"""Check regression on a toy... |
lsst-sqre/sphinxkit | tests/test_sphinxext_mockcoderefs.py | Python | mit | 1,652 | 0 | """Tests for documenteer.sphinext.mockcoderefs."""
from shutil import rmtree
from tempfile import mkdtemp
import pytest
from sphinx.application import Sphinx
import documenteer.sphinxext.mockcoderefs as mockcoderefs
try:
from unittest.mock import Mock
except ImportError:
from mock import Mock
@pytest.fix... | ldername="html",
)
mockcoderefs.setup(app)
# Stitch together as the sphinx app init() usually does w/ real conf files
tr | y:
app.config.init_values()
except TypeError:
# Sphinx < 1.6.0
app.config.init_values(Sphinx._log)
def fin():
for dirname in (src, doctree, confdir, outdir):
rmtree(dirname)
request.addfinalizer(fin)
return app
@pytest.fixture()
def inliner(app):
retu... |
ogbash/doug | scripts/doug/execution.py | Python | lgpl-2.1 | 8,926 | 0.004593 | import subprocess
import re
import copy
from StringIO import StringIO
import os
import doug
from doug.config import DOUGConfigParser, ControlFile
from scripts import ScriptException
import logging
LOG = logging.getLogger('doug')
_defaultConfig = None
def getDefaultConfig():
global _defaultConfig
if _default... | xt'):
result.setpath('doug-result', 'fineaggrsfile', 'aggr1.txt')
#self.files | .append(("aggr1.txt", "Fine aggregates"))
if solutionfname and os.path.isfile('aggr2.txt'):
result.setpath('doug-result', 'coarseaggrsfile', 'aggr2.txt')
#self.files.append(("aggr2.txt", "Coarse aggregates"))
files = os.listdir... |
huijunwu/heron | heron/tools/ui/src/python/handlers/api/__init__.py | Python | apache-2.0 | 1,275 | 0 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | ologyLogicalPlanJsonHandler,
TopologyPackingPlanJsonHandler,
TopologyPhysicalPlanJsonHandler,
TopologySchedulerLocationJsonHandler,
TopologyExecutionStateJsonHandler,
TopologyExceptionsJsonHandler,
PidHan | dler,
JstackHandler,
MemoryHistogramHandler,
JmapHandler
)
|
subodhchhabra/glances | glances/plugins/glances_fs.py | Python | lgpl-3.0 | 10,262 | 0.001169 | # -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# Copyright (C) 2015 Nicolargo <nicolas@nicolargo.com>
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the Lic... | continue
fs_current = {
'device_name': fs.device,
'fs_type': fs.fstype,
'mnt_point': fs.mountpoint,
| 'size': fs_usage.total,
'used': fs_usage.used,
'free': fs_usage.free,
'percent': fs_usage.percent,
'key': self.get_key()}
self.stats.append(fs_current)
elif self.input_method == 'snmp':
#... |
TakeshiTseng/HyperRyu | hyper_ryu/vtopo/vtopo.py | Python | mit | 884 | 0 | '''
Virtual topology
'''
class VTopo(object):
'''
Attributes:
- switches : virtual switch list
- links : virtual links
'''
def __init__(self):
super(VTopo, self).__init__()
self.isStart = False
self.switches = []
self.links = []
def addSwitch(self, vswitc... | cal and virtual automatically
'''
pass
def addLink(self, vlink):
'''
Add new virtual link
Mapping between physical and virtual automatically
'''
pass
def getVPSwitchMapping(self, vswitch):
'''
get virtual to physical mapping
'''
... | ss
def start(self):
pass
|
Coelhon/MasterRepo.repository | plugin.video.zen/resources/lib/modules/trailer.py | Python | gpl-2.0 | 3,897 | 0.010521 | # -*- coding: utf-8 -*-
'''
zen Add-on
Copyright (C) 2016 zen
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 v... | n)
try: item.setArt({'icon': icon})
except: pass
item.setInfo(type='Video', infoLabels = {'title': title})
control.player.play(url, item)
except:
pass
def worker(self, name, url):
try:
if url.startswith(self.base_link):
... | url = self.youtube_watch % url
url = self.resolve(url)
if url == None: raise Exception()
return url
else:
raise Exception()
except:
query = name + ' trailer'
query = self.youtube_search + query
url ... |
osigaud/ArmModelPython | Control/Experiments/Experiments.py | Python | gpl-2.0 | 14,422 | 0.014284 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Author: Thomas Beucher
Module: Experiments
Description: Class used to generate all the trajectories of the experimental setup and also used for CMAES optimization
'''
import numpy as np
import time
#from Utils.ThetaNormalization import normalization, unNormalization... | import partial
#------------------------------------------------------------------------------
class Experiments:
def __init__(self, rs, sizeOfTarget, saveTraj, foldername, thetafile, popSize, period, estim="Inv"):
'''
Initializes parameters used to run functions below
Inputs:
'''
... | self.name = "Experiments"
self.call = 0
self.dimState = rs.inputDim
self.dimOutput = rs.outputDim
self.numberOfRepeat = rs.numberOfRepeatEachTraj
self.foldername = foldername
self.tm = TrajMaker(rs, sizeOfTarget, saveTraj, thetafile, estim)
self.posIni = np.loadt... |
FederatedAI/FATE | python/federatedml/feature/homo_feature_binning/homo_binning_base.py | Python | apache-2.0 | 9,934 | 0.003221 | #
# Copyright 2019 The FATE 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 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 permissions and
# limitations under the License.
import functools
import numpy as np
from federatedml.util import LOGGER
from federatedml.feature.binning.base_binning import BaseBinning
from federatedml.framework import weights
from fate_arch.sessio... |
mfalesni/pytest-fauxfactory | tests/test_faux_string.py | Python | gpl-3.0 | 5,253 | 0 | # -*- coding: utf-8 -*-
"""Test the `faux_string` mark."""
import pytest
def is_numeric(value):
"""Check if value is numeric."""
return value.isnumeric()
def contains_number(value):
"""Check to see if the string contains a number."""
return any(char.isnumeric() for char in value)
def test_mark_pla... | assert value
""")
result = testdir.runpytest()
result.assert_outcomes(passed=10)
assert result.ret == 0
def test_mark_incorrect_value(testdir):
"""Check that argument `value` is not being used."""
testdir.makepyfile("""
im | port pytest
@pytest.mark.faux_string(10)
def test_something(foo):
assert foo
""")
result = testdir.runpytest()
result.assert_outcomes(error=1)
assert 'uses no argument \'value\'' in result.stdout.str()
assert result.ret == 2
def test_mark_str_type_argument(testdir):
... |
chhe/streamlink | src/streamlink/plugins/raiplay.py | Python | bsd-2-clause | 1,786 | 0.00168 | """
$url raiplay.it
$type live
$region Italy
"""
import logging
import re
f | rom urllib.parse import urlparse, urlunparse
from streamlink.plugin import Plugin, pluginmatcher
from streamlink.plugin.api import validate
from streamlink.stream.hls import HLSStream
log = logging.getLogger(__name__)
class RaiPlayHLSStream(HLSStream):
@classmethod
def _get_variant_playlist(cls, res):
... | ()._get_variant_playlist(res)
@pluginmatcher(re.compile(
r"https?://(?:www\.)?raiplay\.it/dirette/(\w+)/?"
))
class RaiPlay(Plugin):
_re_data = re.compile(r"data-video-json\s*=\s*\"([^\"]+)\"")
_schema_data = validate.Schema(
validate.transform(_re_data.search),
validate.any(None, validate... |
frappe/erpnext | erpnext/education/doctype/course_topic/test_course_topic.py | Python | gpl-3.0 | 154 | 0.006494 | # Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and | Contributors
# See license.txt
import unittest
class Tes | tCourseTopic(unittest.TestCase):
pass
|
afourmy/pyNMS | pyNMS/right_click_menus/network_general_menu.py | Python | gpl-3.0 | 1,562 | 0.007042 | # Copyright (C) 2017 Antoine Fourmy <antoine dot fourmy at gmail dot com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# ... | mplied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Ge | neral Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from .general_menu import GeneralMenu
from .geographical_menu import GeographicalMenu
from miscellaneous.decorators import overrider
from ... |
tencent-wechat/phxsql | phxrpc_package_config/tools/phxsql_utils.py | Python | gpl-2.0 | 103 | 0.106796 | d | ef format_path( str ):
while( str.find( '//' ) != -1 ):
str = str.replace( '//', '/' )
ret | urn str
|
ict-felix/stack | vt_manager_kvm/src/python/vt_manager_kvm/communication/sfa/setUp/setup_config.py | Python | apache-2.0 | 416 | 0.036058 | AUTHORITY_XRN = 'ocf.ofam'
SUBJ | ECT = {'CN':'OfeliaSDKR1',
'C':'SP',
'ST':'Catalunya',
'L':'Barcelona',
'O':'i2CAT',
'OU':'DANA',
}
PARENT_SUBJECT = {'CN':'OfeliaSDKR1',
'C':'SP',
'ST':'Catalunya',
'L':'Barcelona',
... | |
stonekyx/binary | vendor/scons-local-2.3.4/SCons/Taskmaster.py | Python | gpl-3.0 | 40,520 | 0.002098 | #
# Copyright (c) 2001 - 2014 The SCons Foundation
#
# 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, copy, modify, merge... | = tm
self.targets = targets
self.top = top
self.node = node
self.exc_clear()
def trace_message(self, method, node, description='node'):
fmt = '%-20s %s % | s\n'
return fmt % (method + ':', description, self.tm.trace_node(node))
def display(self, message):
"""
Hook to allow the calling interface to display a message.
This hook gets called as part of preparing a task for execution
(that is, a Node to be built). As part of figur... |
Bolton-and-Menk-GIS/restapi | restapi/decorator/__init__.py | Python | gpl-2.0 | 16,306 | 0.000736 | # ######################### LICENSE ############################ #
# Copyright (c) 2005-2015, Michele Simionato
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# Redistributi... | LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREME | NT OF SUBSTITUTE GOODS OR SERVICES; LOSS
# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILIT... |
brianr/uuss | proto.py | Python | mit | 17,229 | 0.003541 | import contextlib
from uuss.server import model
from lolapps.common import uums
from lolapps.util import json
import os
import simplejson
import struct
import time
try:
# Try importing the C++ extension version
import uuss_pb
except:
# The dynamic python version will automatically be used
pass
from uus... | __(self):
self.Request = None
self.Response = No | ne
@contextlib.contextmanager
def get_response(self, protocol, req, config):
log.debug("UUSSAction.get_response start (%r, %r)", req.user_id, req.game)
userstate = getattr(model, req.game).userstate
log.debug("UUSSAction.get_response userstate: %r", userstate)
with self._call(pr... |
azon1272/War-for-cookies-v2 | game_window.py | Python | bsd-3-clause | 114 | 0.017544 | from lib.lib_game import Window
if __name_ | _ == '__main__':
a = Window('first | _map_for_test')
a.Run()
|
audiencepi/SimilarWeb-Python | setup.py | Python | mit | 1,247 | 0 | from setuptools import find_packages
from setuptools import setup
import io
import os
VERSION = '0.0.3'
def fpath(name):
return os.path.join(os.path.dirname(__file__), name)
def read(*filenames, **kwargs):
encoding = kwargs.get('encoding', 'utf-8')
sep = kwargs.get('sep', '\n')
buf = []
for fil... | il.com',
classifiers=[
| 'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
)
if __name__ == '__main__':
setup(**setup_args)
|
CoderBotOrg/coderbot | stub/picamera/camera.py | Python | gpl-2.0 | 113 | 0.00885 | from test.picamera_mock impor | t PiCameraMock as PiCamera
class array(object):
def __init(s | elf):
pass
|
mgraffg/RGP | EvoDAG/population.py | Python | apache-2.0 | 18,497 | 0.000378 | # Copyright 2015 Mario Graff Guerrero
# 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 wri... | ytr=base._ytr, nai | ve_bayes=base.naive_bayes,
finite=base._finite, mask=base._mask)
sig = v.signature()
unique_individuals.add(sig)
v.height = 0
if not v.eval(base.X):
return None
if not v.isfinite():
return None
if not base._bagging_fitness.set_fitness... |
wrobell/geocoon | geocoon/tests/test_sql.py | Python | gpl-3.0 | 1,771 | 0.000565 | #
# GeoCoon - GIS data analysis library based on Pandas and Shapely
#
# Copyright (C) 2014 by Artur | Wroblewski <wrobell@pld-linux.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either versio | n 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 ... |
ai-ku/langvis | jython-2.1/Lib/unittest.py | Python | mit | 25,555 | 0.002465 | #!/usr/bin/env python
'''
Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's
Smalltalk testing framework.
This module contains the core framework classes that form the basis of
specific test cases and suites (TestCase, TestSuite etc.), and also a
text-based utility class for running the... | st, err))
def addFailure(self, test, err):
"Called when a failure has occurred"
self.failures.append((test, err))
def addSuccess(self, test):
"Called when a test has completed successfully"
pass
def wasSuccessful(self):
"Tells whether or not this result | was a success"
return len(self.failures) == len(self.errors) == 0
def stop(self):
"Indicates that the tests should be aborted"
self.shouldStop = 1
def __repr__(self):
return "<%s run=%i errors=%i failures=%i>" % \
(self.__class__, self.testsRun, len(self... |
OpenTouch/python-facette | src/facette/v1/plot.py | Python | apache-2.0 | 2,559 | 0.008988 | # Copyright (c) 2014 Alcatel-Lucent Enterprise
# 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
#
# Un... | js, | self.plot)
self.description = facette_to_json(PLOT_DESCRIPTION, js, self.plot)
self.type = facette_to_json(PLOT_TYPE, js, self.plot)
self.stack_mode = facette_to_json(PLOT_STACK_MODE, js, self.plot)
self.start = facette_to_json(PLOT_START, js, self.plot)
... |
cloudbase/maas | src/maasserver/migrations/0033_component_error.py | Python | agpl-3.0 | 15,078 | 0.007494 | # -*- coding: utf-8 -*-
import datetime
from django.db import models
from south.db import db
from south.v2 import SchemaMigration
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'ComponentError'
db.create_table(u'maasserver_componenterror', (
('id', self.gf(... | 'null': 'True'})
},
u'maasserver.dhcplease': {
'Meta': {'object_name': 'DHCPLease'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': | 'True'}),
'ip': ('django.db.models.fields.IPAddressField', [], {'unique': 'True', 'max_length': '15'}),
'mac': ('maasserver.fields.MACAddressField', [], {}),
'nodegroup': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['maasserver.NodeGroup']"})
},
u'm... |
bazelbuild/bazel-bench | utils/bigquery_upload.py | Python | apache-2.0 | 2,925 | 0.009573 | # Copyright 2019 The Bazel 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 applicable law... | ect_id, dataset_id, table_id,
location):
"""Uploads the csv file to BigQuery.
Takes the configuration from GOOGLE_APP | LICATION_CREDENTIALS.
Args:
csv_file_path: the path to the csv to be uploaded.
project_id: the BigQuery project id.
dataset_id: the BigQuery dataset id.
table_id: the BigQuery table id.
location: the BigQuery table's location.
"""
logger.log('Uploading the data to bigquery.')
client = bigq... |
doofmars/systems_nominal_bot | code.py | Python | mit | 6,584 | 0.092193 | import ImageGrab
import os
import time
import win32api, win32con
import quickGrab
import ImageOps
from numpy import *
"""
All coordinates assume a screen resolution of 1920x1080
And window size of 1280x720
"""
## Globals
#Top left corner of game window
pad_x = 320
pad_y = 171
#Size of window
window_x = 1280
window... | search | ':0xAA,
'browser_favorites':0xAB,
'browser_start_and_home':0xAC,
'volume_mute':0xAD,
'volume_Down':0xAE,
'volume_up':0xAF,
'next_track':0xB0,
'previous_track':0xB1,
'stop_media':0xB2,
'play/pause_media':0xB3,
'start_mail':0xB4,
'select_media':0xB5,
'start_application_1':0xB6,
'sta... |
LorenzoBi/computational_physics | assignments/1/report/code/math_functions.py | Python | mit | 3,299 | 0.001516 | '''
This is the code containing the the mathematical functions used for the
assignment
'''
import numpy as np
# cotangent
def cot(x):
return np.cos(x) / np.sin(x)
#The rooted equation in the finite well calculation
def rooted_equation(x, Rsquared=36):
return np.sqrt(Rsquared - x ** 2)
# x*tan(x)
def simm... | (x) / np.sin(x))
# sqrt(r**2 - x**2) - x*tan(x)
def simmetric_constraint(x, Rsquared=36):
return rooted_equation(x, Rsquared) - simmetric_state(x)
# sqrt(r**2 - x**2) + x*cot(x)
def antisimmetric_constraint(x, Rsquared=36):
return rooted_equation(x, Rsquared) - ant | isimmetric_state(x)
# derivative of sqrt(r**2 - x**2) - x*tan(x)
def d_simmetric_costraint(x, Rsquared=36):
return - x / np.sqrt(36 - x ** 2) - np.tan(x) - x / (np.cos(x) ** 2)
# derivative of sqrt(r**2 - x**2) + x*cot(x)
def d_antisimmetric_constraint(x, Rsquared=36):
return - x / np.sqrt(36 - x ** 2) + co... |
antoinecarme/pyaf | tests/model_control/detailed/transf_Integration/model_control_one_enabled_Integration_MovingAverage_Seasonal_WeekOfYear_AR.py | Python | bsd-3-clause | 167 | 0.047904 | import tests.mod | el_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Integration'] , ['MovingAver | age'] , ['Seasonal_WeekOfYear'] , ['AR'] ); |
nmercier/linux-cross-gcc | linux/lib/python2.7/dist-packages/blueman/plugins/applet/KillSwitch.py | Python | bsd-3-clause | 4,342 | 0.004606 | from gi.repository import GObject
import dbus
from blueman.Functions import *
from blueman.main.SignalTracker import SignalTracker
from blueman.plugins.AppletPlugin import AppletPlugin
from blueman.main.KillSwitchNG import KillSwitchNG, RFKillType, RFKillState
try:
import blueman.main.KillSwitch as _KillSwitch
ex... | ETOOTH:
dprint("killswitch registered", switch.idx)
# if manager.HardBlocked:
# self.Applet.Plugins.PowerManager.SetPowerChangeable(False)
#
# if not self.Manager.GetGlobalState():
# self.Applet.Plugins.PowerManager.SetBluetoothSta | tus(False)
#
# pm_state = self.Applet.Plugins.PowerManager.GetBluetoothStatus()
# if self.Manager.GetGlobalState() != pm_state:
# self.Manager.SetGlobalState(pm_state)
def on_switch_changed(self, manager, switch):
if switch.type == RFKillType.BLUETOOTH:
s ... |
TheBlackDude/ehealth_academy | server/manage.py | Python | mit | 246 | 0 | #!/usr/bin | /env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "eHA.settings")
from django.core.management import execute_from_command_line
execute_from_com | mand_line(sys.argv)
|
F483/bikesurf.org | apps/gallery/control.py | Python | mit | 2,303 | 0.002605 | # -*- coding: utf-8 -*-
# Copyright (c) 2012 Fabian Barkhau <fabian.barkhau@gmail.com> |
# License: MIT (see LICENSE.TXT file)
import os
from django.core.exceptions import PermissionDenied
from apps.gallery.models import Gallery
from apps.gallery.models import Picture
from apps.team.utils import assert_member
from apps.team import control as team_control
def can_edit(account, gallery):
... | .team)) or
(not gallery.team and gallery.created_by != account))
def _assert_can_edit(account, gallery):
if not can_edit(account, gallery):
raise PermissionDenied
def delete(account, gallery):
""" Delete gallery and all pictures belonging to it. """
_assert_can_edit(account, gal... |
uclouvain/osis_louvain | base/signals/publisher.py | Python | agpl-3.0 | 1,579 | 0.002535 | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | - is available
# at the root of the source code of this program. If not,
# see http://www.gnu.org/licenses/.
#
##############################################################################
from django.dispatch import Signal
compute_scores_encodings_deadlines = Signal(providing_args=[ | "offer_year_calendar"])
compute_student_score_encoding_deadline = Signal(providing_args=["session_exam_deadline"])
compute_all_scores_encodings_deadlines = Signal(providing_args=["academic_calendar"])
|
rectory-school/rectory-apps | enrichmentmanager/admin.py | Python | mit | 4,641 | 0.011635 | from datetime import date, datetime, time, timedelta
from django.contrib import admin
from django.utils import timezone
from enrichmentmanager.models import Teacher, Student, EnrichmentOption, EnrichmentSlot, EnrichmentSignup, EmailSuppression
from simple_history.admin import SimpleHistoryAdmin
class EditableUntilLi... | return queryset. | filter(date = date.today())
class EnrichmentOptionInline(admin.TabularInline):
model = EnrichmentOption
class EnrichmentSlotAdmin(admin.ModelAdmin):
inlines = [EnrichmentOptionInline]
list_display = ['date', 'editable_until']
actions = ['allow_edit_until_1_10_0', 'allow_edit_unti... |
gabisurita/kinto-codegen-tutorial | python-client/test/test_group.py | Python | mit | 2,149 | 0.000931 | # coding: utf-8
"""
kinto
Kinto is a minimalist JSON storage service with synchronisation and sharing abilities. It is meant to be easy to use and easy to self-host. **Limitations of this OpenAPI specification:** 1. Validation on OR clauses is not supported (e.g. provide `data` or `permissions` in patch ... | piException
from swagger_client.models.group import Group
class TestGroup(unittest.TestCase):
""" Group unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testGroup(self):
"""
Test Group
"""
model = swagger_client.models.group.Grou... | __':
unittest.main()
|
michellemorales/OpenMM | kaldi/egs/wsj/s5/steps/nnet3/components.py | Python | gpl-2.0 | 29,765 | 0.013069 | #!/usr/bin/env python
# Note: this file is part of some nnet3 config-creation tools that are now deprecated.
from __future__ import print_function
import os
import argparse
import sys
import warnings
import copy
from operator import itemgetter
def GetSumDescriptor(inputs):
sum_descriptors = inputs
while len(s... | name={0}_affine type=NaturalGradientAffin | eComponent input-dim={1} output-dim={2} {3} {4}".format(name, input['dimension'], output_dim, ng_affine_options, max_change_options))
component_nodes.append("component-node name={0}_affine component={0}_affine input={1}".format(name, input['descriptor']))
return {'descriptor': '{0}_affine'.format(name),
... |
pgaref/HTTP_Request_Randomizer | tests/mocks.py | Python | mit | 9,201 | 0.003695 | from httmock import urlmatch
free_proxy_expected = ['138.197.136.46:3128', '177.207.75.227:8080']
proxy_for_eu_expected = ['107.151.136.222:80', '37.187.253.39:8115']
rebro_weebly_expected = ['213.149.105.12:8080', '119.188.46.42:8080']
prem_expected = ['191.252.61.28:80', '167.114.203.141:8080', '152.251.141.93:8080... | <td>Yes/Yes</td>
</tr>
</table>"""
@urlmat | ch(netloc=r'(.*\.)?rebro\.weebly\.com$')
def rebro_weebly_mock(url, request):
return """<div class="paragraph" style="text-align:left;"><strong><font color="#3ab890" size="3"><font
color="#d5d5d5">IP:Port</font></font></strong><br/><font
size="2"><strong><font color="#33a27f">213.149.105.12:8080<br/... |
AutorestCI/azure-sdk-for-python | azure-mgmt-datafactory/azure/mgmt/datafactory/models/self_hosted_integration_runtime_node.py | Python | mit | 6,083 | 0.000329 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | str
:ivar status: Status of the integration runtime node. Possible values
include: 'NeedRegistration', 'Online', 'Limited', 'Offline', 'Upgrading',
'Initializing', 'InitializeFailed'
:vartype status: | str or
~azure.mgmt.datafactory.models.SelfHostedIntegrationRuntimeNodeStatus
:ivar capabilities: The integration runtime capabilities dictionary
:vartype capabilities: dict[str, str]
:ivar version_status: Status of the integration runtime node version.
:vartype version_status: str
:ivar version... |
graik/biskit | archive_biskit2/scripts/Dock/pdb2complex.py | Python | gpl-3.0 | 2,397 | 0.0267 | #!/usr/bin/env python
##
## Biskit, a toolkit for the manipulation of macromolecular structures
## Copyright (C) 2004-2018 Raik Gruenberg & Johan Leckner
##
## 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 Softwar... | Complex as ProteinComplex
def _use( options ):
print """
pdb2complex.py - create a reference Complex (without waters)
Syntax: pdb2complex.py -c |complex pdb|
| -r |chain index| -l |chain index|
-o |output name|
Options: -c complex pdb file or pickled PDBModel object
-r receptor chain list (e.g. 0 1 )
-l ligand ~ (e.g. 2 )
-o output file
-lo,l... |
icomfort/anaconda | livecd.py | Python | gpl-2.0 | 17,872 | 0.003637 | #
# livecd.py: An anaconda backend to do an install from a live CD image
#
# The basic idea is that with a live CD, we already have an install
# and should be able to just copy those bits over to the disk. So we dd
# the image, move things to the "right" filesystem as needed, and then
# resize the rootfs to the size o... | os.makedirs(dst)
errors = []
for name in name | s:
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
if preserveSelinux:
trySetfilecon(srcname... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.