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 |
|---|---|---|---|---|---|---|---|---|
pattisdr/osf.io | framework/auth/oauth_scopes.py | Python | apache-2.0 | 18,447 | 0.005746 | """
Define a set of scopes to be used by COS Internal OAuth implementation, specifically tailored to work with APIv2.
List of scopes, nomenclature, and rationale can be found in the relevant "Login as OSF- phase 2" proposal document
"""
from collections import namedtuple
from website import settings
# Public scopes... | eScopes.NODE_COMMENTS_WRITE, CoreScopes.NODE_FORKS_WRITE,
CoreScopes.NODE_PREPRINTS_WRITE, CoreScopes.PREPRINT_REQUESTS_WRITE, CoreScopes.WIKI_BASE_WRITE)
# Preprints collection
# TODO: Move Met | rics scopes to their own restricted compose |
Bestoa/py-brainfuck | nbfi/__init__.py | Python | mit | 2,726 | 0.002935 | '''Brainfuck interpreter'''
VERSION = '0.1.2.1103'
def __static_vars():
'''Decorate, add static attr'''
def decorate(func):
'''The decorate'''
setattr(func, 'stdin_buffer', [])
return func
return decorate
@__static_vars()
def __getchar() -> int:
'''Return one char from stdin''... | place the [] with paired code pointer'''
iptr = 0
bracket = list()
code = list(raw_code)
code_len = len(code)
while iptr < code_len:
code[iptr] = [code[iptr], '']
if code[iptr][0] == '[':
bracket.append(iptr)
elif code[iptr][0] == ']':
piptr = bracket.... | code = []
return code
def __execute(code: list, stack_size: int) -> list:
'''Run bf code'''
iptr = 0
sptr = 0
stack = list(0 for _ in range(stack_size))
code_len = len(code)
while iptr < code_len:
instruction = code[iptr][0]
if instruction == '>':
sptr += 1
... |
maxsocl/django-tvdb | setup.py | Python | mit | 1,193 | 0.000838 | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-tvdb',
version='0.1',
packages=['tvdb'],
include_package_data=True,
... |
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Py... | 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
CG-F16-16-Rutgers/steersuite-rutgers | steerstats/steersuitedb/Scenario.py | Python | gpl-3.0 | 2,417 | 0.009516 | import psycopg2
from Sequence import ScenarioSequence
class Scenario(object):
"""A simple example class"""
_id_name = "scenario_id"
_table_name = "scenario"
_insert_order = """
(scenario_id ,
algorithm_type ,
benchmark_type ,
config_id,
scenario_description )"""
#scenario ... | lf, cur, n):
cur.execute("SELECT * FR | OM " + self._table_name + " where " + self._id_name + " = "+ str(n))
row = cur.fetchone()
return row
def insertScenario(self, cur, algorithm_type, benchmark_type, config_id, scenario_description):
try:
alDataSeq = ScenarioSequence()
next_id = alDataSeq.g... |
odoousers2014/odoo | addons/website_version/__openerp__.py | Python | agpl-3.0 | 724 | 0.005525 | {
'name': 'Website Versioning',
'category': 'Website',
'summary': 'Allow to save all the versions of your website and allow to perform AB testing.',
'version': | '1.0',
'description': """
OpenERP Website CMS
===================
""",
'author': 'OpenERP SA',
'depends': ['website','marketing','google_a | ccount'],
'installable': True,
'data': [
'security/ir.model.access.csv',
'views/website_version_templates.xml',
'views/marketing_view.xml',
'views/website_version_views.xml',
'views/res_config.xml',
'data/data.xml',
],
'demo': [
'data/demo.xml',
... |
ddico/odoo | addons/survey/tests/test_survey.py | Python | agpl-3.0 | 3,979 | 0.002011 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _
from odoo.addons.survey.tests import common
from odoo.tests.common import users
class TestSurveyInternals(common.TestSurveyCommon):
@users('survey_manager')
def test_answer_validation_mandat... | e': 'Row0'}, {'value': 'Row1'}]
question = self._add_question(self.page_0, 'Q0', question_type, **kwargs)
| self.assertDictEqual(
question.validate_question(''),
{question.id: 'TestError'}
)
@users('survey_manager')
def test_answer_validation_date(self):
question = self._add_question(
self.page_0, 'Q0', 'date', validation_required=True,
... |
srio/shadow3-scripts | METROLOGY/surface2d_to_hdf5.py | Python | mit | 6,588 | 0.007286 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
from srxraylib.plot.gol import plot
from oasys.util.oasys_util import write_surface_file
from srxraylib.metrology.profiles_simulation import slopes
# def transform_data(file_name):
#
# """... | + np.sqrt(radius ** 2 - xm ** 2)
# if plotting:
# plot(xm, zfit, legend=["fit"])
# #plot(xcut, zmcut, xm, zfit, legend=["cut","fit"])
#
# #print(len(zfit))
#
# plot(xm, zm-zfit, legend=["detrended"])
#
# for i in range(z.shape[0]):
# z[i,:] -= zfit
#
#
# nx, ny =... | .shape
# z = z - (z[nx//2,ny//2])
#
# # print(f" Slope error is {round(z[:, 0].std(), 6)}")
#
# return xm, z
def plot2d(x,y,data):
plt.pcolormesh(x,y,data, cmap=plt.cm.viridis)
plt.colorbar().ax.tick_params(axis='y',labelsize=12)
plt.ylabel("Vertical [mm]",fontsize=12)
... |
scalable-networks/ext | uhd/host/apps/omap_debug/set_debug_pins.py | Python | gpl-2.0 | 712 | 0.008427 | #!/usr/bin/python
import os
# Memory Map
misc_base = 0
uart_base = 1
| spi_base = 2
i2c_base = 3
gpio_base = 4 * 128
settings_base = 5
# GPIO offset
gpio_pins = 0
gpio_ddr = 4
gpio_ctrl_lo = 8
gpio_ctrl_hi = 12
def set_reg(reg, val):
os.system("./usrp1-e-ctl w %d 1 %d" % (reg,val))
def get_reg(reg):
fin,fout = os.popen4("./usrp1-e-ctl r %d 1" % (reg,))
print fout.read()
# ... | r debug 0, F is for debug 1 )
set_reg(gpio_base+gpio_ctrl_lo, 0xAAAA)
set_reg(gpio_base+gpio_ctrl_lo+2, 0xAAAA)
set_reg(gpio_base+gpio_ctrl_hi, 0xAAAA)
set_reg(gpio_base+gpio_ctrl_hi+2, 0xAAAA)
|
jpn--/pines | pines/zipdir.py | Python | mit | 3,774 | 0.037096 | #!/usr/bin/env python
import os
import zipfile
import hashlib
def _rec_split(s):
rest, tail = os.path.split(s)
if rest in ('', os.path.sep):
return tail,
return _rec_split(rest) + (tail,)
def _any_dot(s):
for i in _rec_split(s):
if len(i)>0 and i[0]=='.':
return True
return False
def _zipdir(path, ziph,... | kip_dots=skip_dots)
def zipmod_temp(module, skip_dots=True):
import tempfile
tempdir = tempfile.TemporaryDirectory()
zip_file_name = os.path.join(tempdir.name, module.__name__+".zip")
zipmod(module, zip_file_name, skip_dots=skip_dots)
return zip_file_name, tempdir
def make_hash_file(fname):
hash256 = hashlib.... | hash256.update(chunk)
h = hash256.hexdigest()
with open(fname[:-3] + ".sha256.txt", "w") as fh:
fh.write(h)
else:
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash256.update(chunk)
h = hash256.hexdigest()
with open( fname+".sha256.txt" , "w") as fh:
fh.write(h)
... |
munikes/loteria_lgb | loteria/web/views.py | Python | agpl-3.0 | 891 | 0.001122 | from django.views import generic
from django.core.urlresolvers import reverse_lazy
from .models import LotteryUser
class LotteryUserList(generic.ListView):
template_name = 'index.html'
context_object_name = 'number_list'
def get_que | ryset(self):
"""Return all numbers"""
return LotteryUser.objects | .all().order_by('number')
class LotteryUserCreate(generic.edit.CreateView):
model = LotteryUser
fields = ['name', 'number']
template_name_suffix = '_create_form'
success_url = reverse_lazy('lotteryuser-list')
class LotteryUserUpdate(generic.edit.UpdateView):
model = LotteryUser
fields = ['na... |
NextHub/drf-expander | rest_framework_expander/optimizers.py | Python | isc | 5,150 | 0.001748 | from collections import OrderedDict
from copy import deepcopy
from django.utils import six
from rest_framework.utils.serializer_helpers import BindingDict
from rest_framework_expander import utils
from rest_framework_expander.exceptions import ExpanderContextMissing
class ExpanderOptimizer(object):
"""
Provi... | objects = optimizer.to_optimized_objects(objects)
return objects
class PrefetchExpanderOptimi | zerSet(ExpanderOptimizerSet):
"""
ExpanderOptimizerSet which defaults to calling prefetch related.
"""
def get_optimizers(self):
optimizers = deepcopy(self._declared_optimizers)
for name in self.expander.children.keys():
if name not in optimizers:
optimizers... |
le4ndro/homeinventory | homeinventory/dashboard/views.py | Python | mit | 1,435 | 0 | import logging
from django.shortcuts import render
from django.http import JsonResponse
from django.db.models import Count
from homeinventory.inventory.models import Item, Category, Location, ItemLoan
logger = logging.getLogger(__name__)
def dashboard(request):
# get loans
item_loan = ItemLoan.objects \
... | oan': item_loan, 'item_warranty': item_warranty})
def total_item_by_category(request):
q = Category.objects.filter(user=request.user) \
.annotate(da | ta=Count('item')) \
.values('name', 'data').filter(data__gt=0)
logger.debug(q)
q_list = list(q)
return JsonResponse(q_list, safe=False)
def total_item_by_location(request):
q = Location.objects.filter(user=request.user) \
.annotate(data=Count('item')) \
... |
philipn/localwiki-geocode-pagenames | geocode_pagenames/utils.py | Python | mit | 688 | 0 | MAX_RESULTS_PER_PAGE = 100
def all(listf, **kwargs):
"""
Simple generator to page through all results of function `listf`.
"""
if not kwargs.get('limit'):
kwargs['limit'] = MAX_RESULTS_PER_PAGE
resp = listf(**kwargs)
for obj in resp['objects']:
yield obj
while resp['meta... | s']:
yield obj
def clean_pagename(name):
# Pagenames can't contain a slash with spaces surrounding it.
name = '/' | .join([part.strip() for part in name.split('/')])
return name
|
PirateLearner/pi | PirateLearner/blogging/db_migrate.py | Python | gpl-2.0 | 2,332 | 0.009434 | from blogging.tag_lib import parse_content
from blogging.models import BlogContent, BlogParent, BlogContentType
import json
import os
def convert_tags(blog,tag_name,fd):
tag = {}
# tag['name'] = tag_name + '_tag'
tag['name'] = tag_name
content = parse_content(blog,tag)
if len(content) > 0:
... | tmp['content'] = content
| tag['name'] = 'pid_count_tag'
content = parse_content(blog,tag)
if len(content) > 0:
tmp['pid_count'] = content
else:
tmp['pid_count'] = '0'
fd.write(json.dumps(tmp) + "\n\n")
blog.data = json.dumps(tmp)
return True
else:
... |
silenius/amnesia | amnesia/modules/folder/views/__init__.py | Python | bsd-2-clause | 235 | 0 | # | -*- coding: utf-8 -*-
from .browser import FolderBrowserView
def includeme(config):
config.include('.order')
config.include('.admin')
config.include('.browser')
config.include('.crud') |
config.include('.paste')
|
voutilad/courtlistener | cl/corpus_importer/import_columbia/convert_columbia_html.py | Python | agpl-3.0 | 2,132 | 0.007036 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 15 16:32:17 2016
@author: elliott
"""
import re
def convert_columbia_html(text):
conversions = [('italic', 'em'),
('block_quote', 'blockquote'),
('bold', 'strong'),
('underline', 'u'),
('s... | up(1)
rep = '<sup id="ref-fn%s"><a href="#fn%s">%s</a></sup>' % (fnum, fnum, fnum)
text = text.replace(ref, | rep)
foot_numbers = re.findall('<footnote_number>.*?</footnote_number>',text)
for ref in foot_numbers:
try:
fnum = re.search('[\*\d]+', ref).group()
except:
fnum = re.search('\[fn(.+)\]', ref).group(1)
rep = r'<sup id="fn%s"><a href="#ref-fn%s">%s</a></sup>' % (... |
bwduncan/Suncalendar | Sun.py | Python | gpl-2.0 | 19,058 | 0.00105 | #!/usr/bin/env python
# -*- coding: utf8 -*-
"""
SUNRISET.C - computes Sun rise/set times, start/end of twilight, and
the length of the day at any date and latitude
Written as DAYLEN.C, 1989-08-16
Modified to SUNRISET.C, 1992-12-01
(c) Paul Schlyter, 1989, 1992
Released to the public domain by Paul Sch... | of the day, from sunrise to sunset.
Sunrise/set is considered to occur when the Sun's upper limb is
35 arc minutes below the horizon (this accounts for the refraction
of the Earth's atmosphere).
"""
return cls.__daylen(year, month, day, lon, lat, -35.0 / 60.0, 1)
@classmeth... | ding civil twilight.
Civil twilight starts/ends when the Sun's center is 6 degrees below
the horizon.
"""
return cls.__daylen(year, month, day, lon, lat, -6.0, 0)
@classmethod
def dayNauticalTwilightLength(cls, year, month, day, lon, lat):
"""
This macro computes... |
alexanderfefelov/nav | python/nav/metrics/errors.py | Python | gpl-2.0 | 926 | 0 | #
# Copyright (C) 2014 UNINETT
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public L | icense version 2 as published by
# the Free Software Foundation.
#
# 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 ... | long with NAV. If not, see <http://www.gnu.org/licenses/>.
#
"""Graphite related exception classes"""
class GraphiteUnreachableError(Exception):
"""The graphite-web API is unreachable"""
def __init__(self, msg, cause=None):
super(GraphiteUnreachableError, self).__init__(msg + " (%s)" % cause)
... |
Kortemme-Lab/klab | klab/fcm/fcm.py | Python | mit | 18,877 | 0.00731 | #!/usr/bin/python
blank_datafile = '/home/kyleb/Dropbox/UCSF/cas9/FCS/150916-3.1/kyleb/150916-rfp-cas9/96 Well - Flat bottom_002/Specimen_001_F1_F01_046.fcs'
script_output_dir = 'script_output'
sample_directory = '/home/kyleb/Dropbox/UCSF/cas9/FCS/150916-3.1/kyleb/150916-rfp-cas9/96 Well - Flat bottom_002'
rows_in_pl... | self.plate_position
def find_fcs_files(sample_directory):
fcs_files = []
for filename in os.listdir(sample_directory):
if filename.endswith('.fcs'):
full_filename = os.path.join(sample_directory, filename)
fcs_files.append( (PlatePos(filename.split('_')[2]), full_filena | me) )
fcs_files.sort()
return fcs_files
def ticks_format(value, index):
"""
get the value and returns the value as:
integer: [0,99]
1 digit float: [0.1, 0.99]
n*10^m: otherwise
To have all the number of the same size they are all returned as latex strings
http://stackoverf... |
zackproser/WealthEngine-Python-SDK | wealthengine_python_sdk/setup.py | Python | mit | 361 | 0.094183 | from setuptools import setup
setup(name='wealthengine_python_sdk',
version='0.1',
description='A Python SDK for WealthEngi | ne\'s Public API',
url='https://github.com/zackproser/wealthengine | -python-sdk',
author='Zack Proser',
author_email='zackproser@gmail.com',
license='MIT',
packages='wealthengine_python_sdk',
zip_safe=False) |
interDist/pasportaservo | core/templatetags/utils.py | Python | agpl-3.0 | 1,270 | 0.001575 | import random
from hashlib import sha256
| from django import template
register = tem | plate.Library()
@register.simple_tag
def random_identifier(length=None):
try:
length = int(length)
except Exception:
length = None
if length is None or length <= 0:
length = random.randint(16, 48)
return ''.join(random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxy... |
suvit/scrapy-megafon-phones | megafon_phones/megafon_phones/pipelines.py | Python | mit | 662 | 0.001511 | # Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class PhonePipeline(object):
def __init__(self):
self.file = None
def create_exporter(self, spider):
file = open('%s_data.txt' ... | e = file
def process_item(self, item, spider):
if self.file is None:
self.create_exporter(spider)
datafile = self.file
datafile.write(it | em['phone'])
datafile.write('\n')
return item
def close_spider(self, spider):
self.file.close()
|
5monkeys/django-enumfield | django_enumfield/contrib/drf.py | Python | mit | 1,336 | 0.000749 | import six
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class EnumField(serializers.ChoiceField):
default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')}
def __init__(self, enum, **kwargs):
self.enum = enum
choices =... | self.fail("invalid_choice", input=data)
return value
def to_representation(self, value):
enum_value = self.enum.get(value)
i | f enum_value is not None:
return self.get_choice_value(enum_value)
class NamedEnumField(EnumField):
def get_choice_value(self, enum_value):
return enum_value.name
class Meta:
swagger_schema_fields = {"type": "string"}
|
mjmvisser/adl3 | adl3/adl_defines.py | Python | mit | 39,284 | 0.005957 | # Copyright (C) 2011 by Mark Visser <mjmvisser@gmail.com>
#
# 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... | :311
ADL_DISPLAY_CONTYPE_ATICVDONGLE_NTSC = 4 # ADL_SDK_3.0/include/adl_defines.h:312
ADL_DISPLAY_CONTYPE_ATICVDONGLE_JPN = 5 # ADL_SDK_3.0/include/adl_defines.h:313
ADL_DISPLAY_CONTYPE_ATICVDONGLE_NONI2C_JPN = 6 # ADL_SDK_3.0/include/adl_defines.h:314
ADL_DISPLAY_CONTYPE_ATICVDONGLE_NONI2C_NTSC = 7 # A... | l_defines.h:316
ADL_DISPLAY_CONTYPE_HDMI_TYPE_B = 11 # ADL_SDK_3.0/include/adl_defines.h:317
ADL_DISPLAY_CONTYPE_SVIDEO = 12 # ADL_SDK_3.0/include/adl_defines.h:318
ADL_DISPLAY_CONTYPE_COMPOSITE = 13 # ADL_SDK_3.0/include/adl_defines.h:319
ADL_DISPLAY_CONTYPE_RCA_3COMPONENT = 14 # ADL_SDK_3.0/include/ad... |
videlec/sage-flatsurf | flatsurf/geometry/straight_line_trajectory.py | Python | gpl-2.0 | 31,149 | 0.003307 | from __future__ import absolute_import, print_function, division
from six.moves import range, map, filter, zip
from six import iteritems
from collections import deque, defaultdict
from .polygon import is_same_direction, line_intersection
from .surface_objects import SaddleConnection
# Vincent question:
# using deque... | self._start.polygon_label()
def invert(self):
return SegmentInPolygon(self._end, self._start)
def next(self):
r"""
Return the next segment obtained by continuing straight through the end point.
EXAMPLES::
sage: from flatsurf imp | ort *
sage: from flatsurf.geometry.straight_line_trajectory import SegmentInPolygon
sage: s = similarity_surfaces.example()
sage: s.polygon(0)
Polygon: (0, 0), (2, -2), (2, 0)
sage: s.polygon(1)
Polygon: (0, 0), (2, 0), (1, 3)
sage: v ... |
Jozhogg/iris | lib/iris/tests/unit/fileformats/grib/load_convert/test_time_range_unit.py | Python | lgpl-3.0 | 1,951 | 0 | # (C) British Crown Copyright 2014, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later ve... | : Unit('6 hours'),
12: Unit('12 hours'),
13: Unit('seconds')}
def test_units(self):
for indicator, unit | in self.unit_by_indicator.items():
result = time_range_unit(indicator)
self.assertEqual(result, unit)
def test_bad_indicator(self):
emsg = 'unsupported time range'
with self.assertRaisesRegexp(TranslationError, emsg):
time_range_unit(-1)
if __name__ == '__main_... |
dhcrzf/zulip | zerver/tests/test_create_video_call.py | Python | apache-2.0 | 1,733 | 0.001731 | import mock
from zerver.lib.test_classes import ZulipTestCase
from typing import Dict
class TestFeedbackBot(ZulipTestCase):
def setUp(self) -> None:
user_profile = self.example_user('hamlet')
self.login(user_profile.email, realm=user_profile.realm)
def test_create_video_call_success(self) -> N... | lt.status_code)
content = result.json()
self.assertEqual(content['zoom_url'], 'example.com')
def test_create_video_call_failure(self) -> None:
with mock.patch('zerver.lib.actions.request_zoom_video_call_url', return_value=None):
result = self.client_get("/json/calls/crea... | , '')
def test_create_video_request_success(self) -> None:
class MockResponse:
def __init__(self) -> None:
self.status_code = 200
def json(self) -> Dict[str, str]:
return {"join_url": "example.com"}
with mock.patch('requests.post', return_va... |
Roshan2017/spinnaker | dev/dev_runner.py | Python | apache-2.0 | 10,050 | 0.00796 | #!/usr/bin/python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | on)
def start_subsystem(self, subsystem, environ=None):
"""Starts the specified subsystem.
Args:
subsystem [string]: The repository name of the subsystem to run.
"""
print 'Starting {subs | ystem}'.format(subsystem=subsystem)
command = os.path.join(
self.installation.SUBSYSTEM_ROOT_DIR,
subsystem,
'start_dev.sh')
return self.run_daemon(command, [command], environ=environ)
def tail_error_logs(self):
"""Start a background tail job of all the component error logs."""
... |
zamattiac/ROSIEBot | tests_verifier.py | Python | mit | 895 | 0 | import os
from verifier import Verifier
import verifier
import unittest
# Verification tests
import json
import codecs
TASK_FILE = '201606231548.json'
with codecs.open(TASK_FILE, mode='r', encoding='utf-8') as file:
run_info = json.load(file)
v = Verifier()
class TestVerifer(unittest.TestCase):
def | test_handle_errors(self):
l1 = verifier.send_to_retry
verifier.handle_errors()
l2 = verifier.send_to_retry
self.assertGreater(len(l1), len(l2))
self.assertEqual(len(l2), len(l1) + len(run_info['error_list']))
def test_get_path_from_url(self):
path = v.get_path_from_u... | ue(os.path.exists(path))
def test_generate_page_dictionary(self):
d1 = v.generate_page_dictionary('wiki/')
self.assertGreater(len(d1), 0)
if __name__ == '__main__':
unittest.main()
|
brakhane/panda3d | direct/src/showbase/PythonUtil.py | Python | bsd-3-clause | 86,071 | 0.005763 | """Contains miscellaneous utility functions and classes."""
__all__ = ['indent',
'doc', 'adjust', 'difference', 'intersection', 'union',
'sameElements', 'makeList', 'makeTuple', 'list2dict', 'invertDict',
'invertDictLossless', 'uniqueElements', 'disjoint', 'contains',
'replace', 'reduceAngle', 'fitSrcAngle2Dest', 'fit... | op() == 10
assert len(q) == 1
assert not q.isEmpty()
assert q.pop() == 20
assert len(q) == 0
assert q.isEmpty()
def indent(stream, numIndents, str):
"""
Write str to stream with numIndents in front of it
"""
# To match emacs, instead of a tab character we will use 4 spaces
stre... | (self, label="", start=0, limit=None):
"""
label is a string (or anything that be be a string)
that is printed as part of the trace back.
This is just to make it easier to tell what the
stack trace is referring to.
start is an integer number of sta... |
rex-xxx/mt6572_x201 | sdk/monkeyrunner/jython/test/all_tests.py | Python | gpl-2.0 | 1,636 | 0.00978 | #!/usr/bin/python2.4
#
# Copyright 2010, The Android Open Source Project
#
# Licens | ed 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, s | oftware
# 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.
"""Test runner to run all the tests in this package."""
import o... |
Zlash65/erpnext | erpnext/patches/v8_9/update_billing_gstin_for_indian_account.py | Python | gpl-3.0 | 534 | 0.026217 | # Copyright (c) 2017, Frappe and Contributors
# License: GNU General Public Lic | ense v3. See license.txt
from __future__ import unicode_literals
import frappe
def execute():
company = frappe.get_all('Compan | y', filters = {'country': 'India'})
if company:
for doctype in ['Sales Invoice', 'Delivery Note']:
frappe.db.sql(""" update `tab{0}`
set billing_address_gstin = (select gstin from `tabAddress`
where name = customer_address)
where customer_address is not null and customer_address != ''""".format(doc... |
repotvsupertuga/tvsupertuga.repository | script.module.universalscrapers/lib/universalscrapers/scraperplugins/watchfree.py | Python | gpl-2.0 | 7,916 | 0.006822 | import base64
import re,time
import urllib
import urlparse
from BeautifulSoup import BeautifulSoup
from ..import proxy
from ..common import replaceHTMLCodes, clean_title
from ..scraper import Scraper
import xbmcaddon
import xbmc
class Watchfree(Scraper):
domains = ['watchfree.to']
name = "watchfree"
def ... | href = urlparse.parse_qs(urlparse.urlparse(href).query)[ | 'q'][0]
except:
pass
if cleaned_title == clean_title(link_title) and show_year in link_title:
url = re.findall('(?://.+?|)(/.+)', href)[0]
show_url = urlparse.urljoin(self.base_link, replaceHTMLCodes(url))
... |
webgeodatavore/pyqgis-samples | gui/qgis-sample-QgsColorWheel.py | Python | gpl-2.0 | 214 | 0.004673 | # coding: utf-8
from qgis.gui import QgsColorWheel
color_wheel = QgsColorWheel()
|
def on_color_ | wheel_changed(color):
print(color)
color_wheel.colorChanged.connect(on_color_wheel_changed)
color_wheel.show()
|
shengqh/ngsperl | lib/Annotation/annovarSplicing.py | Python | apache-2.0 | 5,184 | 0.016397 | import subprocess
import os.path
import re
import argparse
parser = argparse.ArgumentParser(description="annovate splicing with protein position by annovar.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-i', '--input', action='store', nargs='?', help='... | r,
"-protocol",
"refGene",
"-operation",
"g",
"--outfile",
outputfile,
"--remove",
"--otherinfo"]
subprocess.call(args)
annovar_outputfile = outpu | tfile + "." + annovar_buildver + "_multianno.txt"
if os.path.isfile(annovar_outputfile):
splicing_map = {}
prog = re.compile("p\.\w(\d+)[\w|\?]")
with open(annovar_outputfile, "r") as f:
splicingHeaders = f.readline().rstrip().split('\t')
splicingFuncRefGeneIndex=splicingHeaders.index("Func.refGene")
... |
mgeisler/satori | satori/sysinfo/ohai_solo.py | Python | apache-2.0 | 6,696 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distrib... | with_exit_code=True,
| escalate=True, allow_many=False)
LOG.debug("Ran ohai-solo install script. | %s.",
install_output['stdout'])
# Be a good citizen and clean up your tmp data
command = "rm install.sh"
client.execute(command, cwd='/tmp', escalate=True, allow_many=Fa... |
lizardsystem/flooding-lib | flooding_lib/util/flshinc.py | Python | gpl-3.0 | 10,414 | 0.000288 | """Tool to loop over fls_h.inc files. Based on nens/asc.py and NumPy
masked arrays. Stripped out all unnecessary flexibility.
Usage:
# Opens zipfile if path ends with zip; inside it opens the only file,
# or raises ValueError if there are several. Currently we need to no
# data value passed in because we don't get it... | plitline(self.f)
while line != ['ENDCLASSES']:
classes += [[float(fl) for fl in line]]
line = splitline(self.f)
# logger.debug("classes: {0}".format(classes))
self._header = {
'nrows': nrows,
'ncols': ncols,
'dx': dx,
'x0':... | opened = self._open_path()
maxcol = 0
maxrow = 0
for line in opened:
line = line.strip().decode('utf8').split()
if not line or '.' in line[0]:
continue
try:
row, col, value = [int(elem) for elem in line]
excep... |
dna2github/dna2oldmemory | PyLangParser/source/walker.py | Python | mit | 2,919 | 0.012676 | """
@author: Seven Lju
@date: 2016.04.27
"""
constStops = [
'\n', '\t', ' ', '~', '!', '#', '$', '%',
'@', '&', '*', '(', ')', '-', '=', '+', '[',
']', '{', '}', '\\', '|', '\'', '"', ';',
':', ',', '<', '.', '>', '/', '?', '^', '`'
]
class TextWalker(object):
def __init__(self, text, stops=constStops):
... | ursor = 0
self.n = len(text)
self.stops = stops
self.token = ""
self.stop = '\n'
def __iter__(self):
return self
def __next__(self):
if self.cursor > | = self.n:
raise StopIteration()
i = self.cursor
while True:
if i >= self.n:
self.stop = '\0'
break
self.stop = self.text[i]
if self.stop in self.stops:
break
i += 1
self.token = self.text[self.cursor:i]
self.cursor = i + 1
return (self.token, sel... |
elliotthill/django-oscar | oscar/apps/shipping/admin.py | Python | bsd-3-clause | 576 | 0 | from django.contrib import admin
from oscar.apps.shipping.models import (
OrderAndItemCharges, WeightBand, WeightBased)
class OrderChargesAdmin(admin.ModelAdmin):
exclude = ('code',)
list_display = ('name', 'description', 'price_per_order', 'price_per_item',
| 'free_shipping_threshold')
class WeightBandAdmin(admin.ModelAdmin):
list_display = ('method', 'weight_from', 'weight_to', 'charge')
admin.site.register(OrderAndItemCharges, OrderChargesAdmin)
admin.site.register(WeightBased)
admin.site.register(WeightBand, WeightBandAdmin)
| |
oleduc/ferrymang | ferrymang/modules/__init__.py | Python | bsd-3-clause | 22 | 0 | __author | __ = 'oleduc | '
|
tux-00/ansible | lib/ansible/module_utils/redhat.py | Python | gpl-3.0 | 10,236 | 0.001563 | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete wo... | if os.path.isfile(redhat_repo):
os.unlink(re | dhat_repo)
def register(self):
raise NotImplementedError("Must be implemented by a sub-class")
def unregister(self):
raise NotImplementedError("Must be implemented by a sub-class")
def unsubscribe(self):
raise NotImplementedError("Must be implemented by a sub-class")
def upda... |
masashi-y/depccg | depccg/printer/my_json.py | Python | mit | 1,555 | 0.001286 | from typing import Dict, Any
from depccg.tree import Tree
from depccg.cat import Category
def _json_of_category(category: Category) -> Dict[str, Any]:
def rec(node):
if node.is_functor:
return {
'slash': node.slash,
'left': rec(node.left),
'righ... | }
return rec(category)
def json_of(
tree: Tree,
full: bool = False
) -> Dict[str, Any]:
"""a tree in Python dict object.
Args:
tree (Tree): tree object
full (bool): whether to decomopose categories into its com | ponents, i.e.,
{
'slash': '/',
'left': {'base': 'S', 'feature': 'adj'},
'right': {'base': 'NP', 'feature': None},
},
or just as a string "S[adj]/NP".
Returns:
str: tree string in the CoNLL format
"""
def rec(node:... |
aitgon/wopmars | wopmars/tests/resource/wrapper/fooPackage/FooBase2P.py | Python | mit | 325 | 0.003077 | """
Example of module | documentation which can be
multiple-lined
"""
from sqlalchemy import Column, Integer, String
from wopmars.Base import | Base
class FooBase2P(Base):
"""
Documentation for the class
"""
__tablename__ = "FooBase2P"
id = Column(Integer, primary_key=True)
name = Column(String(255)) |
pupeno/bonvortaro | vortaro/views.py | Python | agpl-3.0 | 324 | 0.003086 | from django.shortcuts import render_to_response
from bonvortaro.vortaro import forms
def search(request):
if request.method == 'POST':
form = forms.SearchForm(request.POST)
else:
form = forms.SearchForm(request.GET)
return render_to_response("vortaro/search.html", {
"form": form
... | ||
tensorflow/tensorboard | tensorboard/plugins/scalar/scalars_plugin.py | Python | apache-2.0 | 6,802 | 0 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | e)`."""
all_scalars = self._data_provider.read_scalars(
ctx,
experiment_id=experiment,
plugin_name=metadata.PLUGIN_NAME,
downsample=self._downsample_to,
run_tag_filter=provider.RunTagFilter(runs=[run], tags=[tag]),
)
s | calars = all_scalars.get(run, {}).get(tag, None)
if scalars is None:
raise errors.NotFoundError(
"No scalar data for run=%r, tag=%r" % (run, tag)
)
values = [(x.wall_time, x.step, x.value) for x in scalars]
if output_format == OutputFormat.CSV:
... |
kg-bot/SupyBot | plugins/Python/config.py | Python | gpl-3.0 | 2,695 | 0.000742 | ###
# Copyright (c) 2003-2005, Jeremiah Fincher
# 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 co... | * Redistributions i | n binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to ... |
SymbiFlow/prjuray | fuzzers/002-tilegrid/clel_int/top.py | Python | isc | 2,848 | 0.001053 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020-2022 F4PGA Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | int_tile_name = grid.tilename_at_loc(int_tile_loc)
if not int_tile_name.startswith('INT_'):
continue
yield int_tile_name, site_name
def write_params(params):
pinstr = 'tile,val\n'
for tile, (site, val) in sorted(params.items()):
pinstr += '%s,%s,%s\n'... | params = {}
sites = sorted(list(gen_sites()))
for (tile_name, site_name), isone in zip(sites,
util.gen_fuzz_states(len(sites))):
params[tile_name] = (site_name, isone)
print('''
(* KEEP, DONT_TOUCH, LOC = "{loc}", LOCK_PINS="I0:A1 I1:A2 ... |
lulf/qpid-dispatch | python/qpid_dispatch_internal/tools/command.py | Python | apache-2.0 | 9,029 | 0.006534 | #
# 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... | ns import Sequence, Mapping
from qpid_dispatch_site import VERSION
from proton import SSLDomain, Url
from proton.utils import SyncRequestResponse, BlockingConnection
class UsageError(Exception):
"""
Raise this exception to indicate the usage message should be printed.
Handled by L{main}
"""
pass
d... | n OptionParser to use for usage related error messages.
@return: exit value for sys.exit
"""
try:
run(argv)
return 0
except KeyboardInterrupt:
print
except UsageError, e:
op.error(e)
except Exception, e:
if "_QPID_DISPATCH_TOOLS_DEBUG_" in os.environ:
... |
kyrelos/bauth | settings/production.py | Python | gpl-2.0 | 640 | 0.009375 | from .base import *
DEBUG = False
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',#'django.db.backends.postgresql_psycopg2',
'NAME': 'bauth',
'USER': 'postgres',
'ADMINUSER':'postgres',
'PASSWORD': 'C7TS*+dp~-9JHwb*7rzP',
... | .0.1',
'PORT': '',
}
}
# Add raven to the list of installed apps
INSTA | LLED_APPS = INSTALLED_APPS + (
# ...
'raven.contrib.django.raven_compat',
)
RAVEN_CONFIG = {
'dsn': 'https://5fa65a7464454dcbadff8a7587d1eaa0:205b12d200e24b39b4c586f7df3965ba@app.getsentry.com/29978',
} |
silly-wacky-3-town-toon/SOURCE-COD | toontown/parties/CalendarGuiDay.py | Python | apache-2.0 | 30,399 | 0.003388 | import datetime
import time
from pandac.PandaModules import TextNode, Vec3, Vec4, PlaneNode, Plane, Point3
from toontown.pgui.DirectGui import DirectFrame, DirectLabel, DirectButton, DirectScrolledList, DGG
from direct.directnotify import DirectNotifyGlobal
from toontown.pgui import DirectGuiGlobals
from toontown.toonb... | ne)
self.numberWidget = DirectLabel(parent=self.numberLocator, relief=None, text=str(self.myDate.day), text_scale=0.04, text_align=TextNode.ACenter, text_font=ToontownGlobals.getInterfaceFont(), text_fg=Vec4(110 / 255.0, 126 / 255.0, 255 / 255.0, 1))
self.attachMarker | (self.numberLocator)
self.listXorigin = 0
self.listFrameSizeX = self.scrollBottomRightLocator.getX() - self.scrollLocator.getX()
self.scrollHeight = self.scrollLocator.getZ() - self.scrollBottomRightLocator.getZ()
self.listZorigin = self.scrollBottomRightLocator.getZ()
self.listF... |
Pulgama/supriya | supriya/patterns/EventPattern.py | Python | mit | 1,545 | 0.003236 | import uuid
from uqbar.objects import new
from supriya.patterns.Pattern import Pattern
class EventPattern(Pattern):
### CLASS VARIABLES ###
__slots__ = ()
### SPECIAL METHODS ###
def _coerce_iterator_output(self, expr, state=None):
import supriya.patterns
if not isinstance(expr,... | ltimeEventPlayer(
self, clock=clock, server=server or supriya.realtime.Server.default()
)
event_player.start()
| return event_player
def with_bus(self, calculation_rate="audio", channel_count=None, release_time=0.25):
import supriya.patterns
return supriya.patterns.Pbus(
self,
calculation_rate=calculation_rate,
channel_count=channel_count,
release_time=r... |
zokis/mapa_do_cidadao | mapa_cidadao/mapa_cidadao/core/migrations/0003_auto_20150525_1937.py | Python | mit | 457 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration | ):
dependencies = [
('core', '0002_auto_20150525_1743'),
]
operations = [
migrations.AlterField(
model_name='categoria',
name='nome',
field=models.CharField(max_length=75, verbose_name=b'nome'),
preserve_default=True,
),
]
| |
jbaek7023/CustomEcommerce | src/products/mixins.py | Python | mit | 1,045 | 0.002871 | from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.http import Http404
class StaffRequiredMixin(object):
@classmethod
def as_view(self, *args, **kwargs):
view... | t, *args, **kwargs):
| if request.user.is_staff:
return super(StaffRequiredMixin, self).dispatch(request, *args, **kwargs)
else:
return Http404
class LoginRequiredMixin(object):
@classmethod
def as_view(self, *args, **kwargs):
view = super(LoginRequiredMixin, self).as_view(*args, **kwargs)
... |
ArtemVavilov88/php4dvd_tests | php4dvd/model/user.py | Python | apache-2.0 | 512 | 0.005859 | class User(object):
def __init__(self, username=None, password=None, email=None):
self.username | = username
self.password = password
self.email = email
@classmethod
def admin(cls):
return cls(username="admin", password="admin")
#random values for username and password
@classmethod
def random_data(cls):
from random import randint
return cls(username="us... | ssword="pass" + str(randint(0, 1000)))
|
SimonGreenhill/ABVDGet | abvdget/abvd_download.py | Python | bsd-3-clause | 1,118 | 0.004472 | #!/usr/bin/env python3
#coding=utf-8
import sys
import argparse
from .ABVD import DATABASES, Downloader
from . import __version__
import json
def parse_args(args):
"""
Parses command line arguments
Returns a tuple of (inputfile, method, outputfile)
"""
parser = argparse.ArgumentParser(description... | ion', action='version', version='%s' % __version__)
parser.add_argument("database", help="database", choices=DATABASES)
parser.add_argument("language", help="language", type=int)
| parser.add_argument(
'-o', "--output", dest='output', default=None,
help="output file", action='store'
)
args = parser.parse_args(args)
return (args.database, args.language, args.output)
def main(args=None): # pragma: no cover
if args is None:
args = sys.argv[1:]
datab... |
bdero/edx-platform | lms/djangoapps/instructor/tests/test_legacy_xss.py | Python | agpl-3.0 | 2,400 | 0.000833 | """
Tests of various instructor dashboard features that include lists of students
"""
from django.conf import settings
from django.test.client import RequestFactory
from django.test.utils import override_settings
from markupsafe import escape
from courseware.tests.tests import TEST_DATA_MIXED_MODULESTORE
from student... | lf._reques | t_factory.post(
"dummy_url",
data={"action": action}
)
req.user = self._instructor
req.session = {}
mako_middleware_process_request(req)
resp = legacy.instructor_dashboard(req, self._course.id.to_deprecated_string())
respUnicode = resp.content.dec... |
cwimbrow/veganeyes-api | app/api_1_0/errors.py | Python | mit | 1,089 | 0.000918 | """
The MIT License (MIT)
Copyright (c) 2014 Chri | s Wimbrow
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, publish, distribute, sublicense, and/or sell
cop... | hom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO T... |
erobinson/cloop | device/processes/test/__init__.py | Python | gpl-2.0 | 25 | 0 | __author | __ = ' | erobinson'
|
yamt/neutron | quantum/tests/unit/test_servicetype.py | Python | apache-2.0 | 20,304 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack Foundation.
# 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.apach... | #
import contextlib
import logging
import mock
from oslo.config import cfg
import webob.exc as webexc
imp | ort webtest
from quantum.api import extensions
from quantum import context
from quantum.db import api as db_api
from quantum.db import servicetype_db
from quantum.extensions import servicetype
from quantum import manager
from quantum.plugins.common import constants
from quantum.tests.unit import dummy_plugin as dp
fro... |
lddubeau/glerbl | glerbl/check/__init__.py | Python | gpl-3.0 | 461 | 0 |
class CheckBase(object):
"""
Base class for checks.
"""
| hooks = []
# pylint: disable=W0105
"""Git hooks to which this class applies. A | list of strings."""
def execute(self, hook):
"""
Executes the check.
:param hook: The name of the hook being run.
:type hook: :class:`str`
:returns: ``True`` if the check passed, ``False`` if not.
:rtype: :class:`bool`
"""
pass
|
NDAR/NITRC-Pipeline-for-NDAR | unsupported/tests/test_nifti.py | Python | bsd-2-clause | 1,410 | 0.004965 | import os
import nose.tools
import ndar
def test_nifti_nifti():
"""image is already a NIfTI-1 file"""
im = ndar.Image('test_data/06025B_mprage.nii.gz')
assert im.nifti_1 == im.path(im.files['NIfTI-1'][0])
def test_nifti_unzipped_nifti():
"""image is already an uncompressed NIfTI-1 file"""
im = nda... | ge03_1326225820791.zip')
assert os.path.exists(im.nifti_1)
def test_nifti_nonvolume():
"""image is not a volume"""
im = ndar.Image('test_data/10_425-02_li1_146. | png')
nose.tools.assert_raises(AttributeError, lambda: im.nifti_1)
def test_nifti_mcfail():
"""mri_convert failure (by way of a bad image)"""
im = ndar.Image('test_data/bogus.mnc')
nose.tools.assert_raises(AttributeError, lambda: im.nifti_1)
def test_nifti_nifti_gz():
"""image is a gzipped NIfTI-1... |
KMK-ONLINE/ansible-modules-core | network/openswitch/ops_config.py | Python | gpl-3.0 | 7,945 | 0.001133 | #!/usr/bin/python
#
# 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) any later version.
#
# Ansible is distribut... | set of commands to push on to the command stack if
a change needs to be made. This allows the playbook designer
the opportunity to perform configuration commands prior to pushing
any changes without affecting how the set of commands are matched
against the system.
required: false
... | ike with I(before) this
allows the playbook designer to append a set of commands to be
executed after the command set.
required: false
default: null
match:
description:
- Instructs the module on the way to perform the matching of
the set of commands against the current device... |
lupyuen/RaspberryPiImage | usr/share/pyshared/ajenti/plugins/bind9/__init__.py | Python | apache-2.0 | 313 | 0 | from ajenti.api import *
from | ajenti.plugins import *
info = PluginInfo(
title='BIND9',
description='BIND9 DNS server',
icon='globe',
dependencies=[
PluginDependency('main'),
PluginDependenc | y('services'),
BinaryDependency('named'),
],
)
def init():
import main
|
chrisspen/dtree | setup.py | Python | lgpl-3.0 | 1,398 | 0.007153 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from distutils.core import setup, Command # pylint: disable=no-name-in-module
import dtree
class TestCommand(Command):
description = "Runs unittests."
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
... | able",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"Li | cense :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
],
platforms=['OS Independent'],
# test_su... |
camponez/importescala | test/test_escala.py | Python | gpl-3.0 | 3,876 | 0 | #!/usr/bin/python2
# -*- coding: utf-8 -*-
# coding=utf-8
import unittest
from datetime import datetime
from lib.escala import Escala
import dirs
dirs.DEFAULT_DIR = dirs.TestDir()
class FrameTest(unittest.TestCase):
def setUp(self):
self.escala = Escala('fixtures/escala.xml')
self.dir = dirs.T... | self.assertFalse(p_voo.checkin)
self.assertEqual(p_voo.checkin_time, None)
self.assertEqual(p_voo.flight_no, '2872')
self.assertEqual(p_voo.activity_info, 'AD2872')
def test_calculo_horas_voadas(self):
s_horas = {
'h_diurno': '6:40',
'h_noturno': '6:47',
... | al(self.escala.soma_horas(), s_horas)
def test_ics(self):
"""
Check ICS output
"""
escala = Escala('fixtures/escala_ics.xml')
f_result = open(self.dir.get_data_dir() + 'fixtures/escala.ics')
self.assertEqual(escala.ics(), f_result.read())
f_result.close()
... |
futurepr0n/Books-solutions | Python-For-Everyone-Horstmann/Chapter9-Objects-and-Classes/test_24.py | Python | mit | 718 | 0 | # Unit tests for p24.py
# IMPORTS
from S24 import Item
import unittest
# main
class ItemTests(unittest.TestCase):
def test_empty_constructor(self):
item = Item()
self.assertEqual("", item.get_name())
self.assertEqual(0.0, item.get_price())
def test_constructor_with_name(self):
... | self.assertEqual("Corn Flakes", item.get_name())
self.assertEqual(3.95, item.get_price())
# PROGRAM RUN
if __nam | e__ == '__main__':
unittest.main()
|
rohitranjan1991/home-assistant | homeassistant/components/nexia/entity.py | Python | mit | 4,354 | 0.000689 | """The nexia integration base entity."""
from nexia.thermostat import NexiaThermostat
from nexia.zone import NexiaThermostatZone
from homeassistant.const import ATTR_ATTRIBUTION
from homeassistant.helpers.dispatcher import async_dispatcher_connect, dispatcher_send
from homeassistant.helpers.entity import DeviceInfo
fr... | es an action against
a thermostat, the data for the thermostat and all
connected zone is updated.
Update all the zones on the thermostat.
"""
dispatcher_send(
self.hass, f"{SIGNAL_THERMOSTAT_UPDATE}-{self._thermostat.thermostat_id}"
)
class NexiaThermostatZ... | "Base class for nexia devices attached to a thermostat."""
def __init__(self, coordinator, zone, name, unique_id):
"""Initialize the entity."""
super().__init__(coordinator, zone.thermostat, name, unique_id)
self._zone: NexiaThermostatZone = zone
@property
def device_info(self):
... |
Princessgladys/googleresourcefinder | lib/feedlib/geo.py | Python | apache-2.0 | 2,777 | 0.001801 | # Copyright 2009-2010 by Ka-Ping Yee
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | # we've crossed it
| if lon <= lon_inters:
inside = not inside
lon1, lat1 = lon2, lat2
return inside
|
dungeonsnd/forwarding | EChat/pack.py | Python | bsd-3-clause | 3,621 | 0.023497 | # -*- coding: utf-8 -*-
import hashlib
import math
import struct
import base64
import json
import zlib
import binascii
from Crypto.Cipher import AES
from Crypto import Random
salt ='__E3S$hH%&*KL:"II<UG=_!@fc9}021jFJ|KDI.si81&^&%%^*(del?%)))+__'
fingerprint_len =4
iv_len =16
randomiv_len =4
print_log =False
# 输入密... | randomiv=', repr(randomiv)
print 'pack fingerprint=', repr(fp)
pr | int 'pack encrypted_str=%s, len=%d'% (repr(encrypted_str), len(encrypted_str))
output =base64.b64encode(output)
if print_log:
print 'pack result:%s, len=%d' %(output, len(output))
output =output+'\r\n'
return output
except:
return ''
def unpack(... |
ldemailly/wdt | test/wdt_port_block_test.py | Python | bsd-3-clause | 3,215 | 0.000622 | #! /usr/bin/env python
import re
from threading import Thread
from common_utils import *
# Todo: refactor using more of common_utils
receiver_end_time = 0
receiver_status = 0
def wait_for_receiver_finish(receiver_process):
global receiver_end_time
global receiver_status
receiver_status = receiver_proce... | ceiver_cmd)
receiver_process = subprocess.Popen(
receiver_cmd.split(),
stdout=subprocess.PIPE
)
connection_url = receiver_process.stdout.readline().strip()
print(connection_url)
# wdt url can be of two k | inds :
# 1. wdt://localhost?ports=1,2,3,4
# 2. wdt://localhost:1?num_ports=4
# the second kind of url is another way of expressing the first one
url_match = re.search('\?(.*&)?ports=([0-9]+).*', connection_url)
if not url_match:
url_match = re.search(':([0-9]+)(\?.*)', connection_url)
... |
yamstudio/mysite | personal/apps.py | Python | mit | 91 | 0 | fro | m django.apps import AppConfig
class PersonalConfig(App | Config):
name = 'personal'
|
adykstra/mne-python | mne/datasets/misc/_misc.py | Python | bsd-3-clause | 697 | 0.001435 | # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Martin Luessi <mluessi@nmr.mgh.harvard.edu>
# Eric Larson <larson.eric.d@gmail.com>
# License: BSD Style.
from ...utils import verbose
from ..utils import _data_path, _data_path_doc
@verbose
def data_path(path=None, force_upd... | update_path=update_path, name='misc',
download=download)
data_path.__doc__ = _data_path_doc.format(name='misc',
| conf='MNE_DATASETS_MISC_PATH')
|
coruus/pyasn1 | pyasn1/debug.py | Python | bsd-2-clause | 1,667 | 0.011398 | import sys
from pyasn1.compat.octets import octs2ints
from pyasn1 import error
from pyasn1 import __version__
flagNone = 0x0000
flagEncoder = 0x0001
flagDecoder = 0x0002
flagAll = 0xffff
flagMap = {
'encoder': flagEncoder,
'decoder': flagDecoder,
'all': flagAll
}
class Debug:
defaultPr... | ne
if not self.defaultPrinter:
raise error.PyAsn1Error('Null debug writer specified')
self._printer = self.defaultPrinter
self('running pyasn1 version %s' % __version__)
for f in flags:
if f not in flagMap:
raise error.PyAsn1Error('bad debug flag %... |
self._flags = self._flags | flagMap[f]
self('debug category \'%s\' enabled' % f)
def __str__(self):
return 'logger %s, flags %x' % (self._printer, self._flags)
def __call__(self, msg):
self._printer('DBG: %s\n' % msg)
def __and__(self, flag):
r... |
RexFuzzle/sfepy | sfepy/discrete/fem/linearizer.py | Python | bsd-3-clause | 4,428 | 0.001807 | """
Linearization of higher order solutions for the purposes of visualization.
"""
import numpy as nm
from sfepy.linalg import dot_sequences
from sfepy.discrete.fem.refine import refine_reference
def get_eval_dofs(dofs, dof_conn, ps, ori=None):
"""
Get default function for evaluating field DOFs given a list o... | flag.fill(F | alse)
# Deal with finished elements.
if flag0 is not None:
ii = nm.searchsorted(iels0, iels)
expand_flag0 = flag0[ii].repeat(factor, axis=1)
else:
expand_flag0 = nm.ones_like(flag)
ie, ir = nm.where((flag == False) & (expand_flag0 == True))
... |
mikkylok/mikky.lu | migrations/versions/f045592adab0_add_follow_table.py | Python | mit | 964 | 0.006224 | """add follow table
Revision ID: f045592adab0
Revises: 56a3d184ac27
Create Date: 2017-10-06 00:38:24.001488
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by | Alembic.
revision = 'f045592adab0'
down_revision = '56a3d184ac27'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('follows',
sa.Column('follower_id', sa.Integer(), nullable=False),
sa.Column('followed_id', sa.Integer(... | , nullable=True),
sa.ForeignKeyConstraint(['followed_id'], ['users.id'], ),
sa.ForeignKeyConstraint(['follower_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('follower_id', 'followed_id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust... |
sthysel/sedge | sedge/templates.py | Python | gpl-3.0 | 177 | 0.00565 | sedge_co | nfig_header = """
# :sedge:
#
# this configuration generated | from `sedge' file:
# {}
#
# do not edit this file manually, edit the source file and re-run `sedge'
#
"""
|
KatolaZ/mammult | models/growth/node_deg_over_time.py | Python | gpl-3.0 | 2,400 | 0.01 | # This file is part of MAMMULT: Metrics And Models for Multilayer Networks
#
# 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 ver... | [n1]]
#print neigh_by_time[node_id]
for node_id in sys.argv[3:]:
node_id = int(node_id)
neigh_by_time[node_id].sort()
last_time = neigh_by_time[node_id][0]
#### changed here
k = 1
print "#### | ", node_id
for t in neigh_by_time[node_id][1:]:
if t != last_time:
if last_time < arrival_time[node_id]:
print arrival_time[node_id], k
else:
print last_time, k
last_time = t
k += 1
print max_t, k-1
print
print
|
snemes/pype32 | setup.py | Python | bsd-3-clause | 4,235 | 0.004959 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2013, Nahuel Riva
# 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 copyrigh... | ANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS | FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# I... |
mikedingjan/wagtail | wagtail/documents/urls.py | Python | bsd-3-clause | 298 | 0.003356 | from django.conf.urls import url |
from wagtail.documents.views import serve
urlpatterns = [
url(r'^(\d+)/(.*)$', serve.serve, name='wagtaildocs_serve'),
url(r'^authenticate_with_password/(\d+)/$', serve.authenticat | e_with_password,
name='wagtaildocs_authenticate_with_password'),
]
|
drix00/leepstools | leepstools/file/elastic.py | Python | apache-2.0 | 1,272 | 0.000786 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. py:currentmodule:: leepstools.file.elastic
.. moduleauthor:: Hendrix Demers <hendrix.demers@mail.mcgill.ca>
Read and generate LEEPS elastic file .ees.
"""
######################################################################### | ######
# Copyright 2017 Hendrix Demers
#
# 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 Lice | nse 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 gov... |
ramuta/python101 | slide4.py | Python | gpl-2.0 | 193 | 0.010363 | __author | __ = 'ramuta'
a = 1
b = 2
if a < b:
a = b
print a
print b
"""
Java equivalent
if | (a < b) {
a = b;
}
If you delete parenthesis, brackets and semicolons you get python.
""" |
Elico-Corp/odoo-addons | website_captcha_nogoogle/website.py | Python | agpl-3.0 | 2,704 | 0 | # -*- coding: utf-8 -*-
# © 2015 Elico corp (www.elico-corp.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import base64
import random
import string
from binascii import hexlify, unhexlify
from openerp import api, fields, models
try:
from captcha.image import ImageCaptcha
except ImportE... | one
def _captcha(self):
captcha = ImageCaptcha()
captcha_challenge = self._generate_random_str(
self._get_captcha_chars(), int(self.captcha_length))
self.captcha_crypt_challenge = hexlify(
encrypt(self.captcha_crypt_password, captcha_challenge))
out = captcha.... | in(random.choice(chars) for _ in range(size))
def _default_salt(self):
return self._generate_random_str(
string.digits + string.letters + string.punctuation, 100)
# generate a random salt
def _captcha_length(self):
return [(str(i), str(i)) for i in range(1, 11)]
def _c... |
MadsJensen/agency_connectivity | sorted_scripts/python_processing/preprocessing.py | Python | bsd-3-clause | 9,616 | 0.000416 | """
Preprocessing function for the bdf.
@author: mje
@email: mads [] cnru.dk
"""
import mne
from mne.preprocessing import ICA, create_eog_epochs
import matplotlib.pyplot as plt
import numpy as np
# SETTINGS
n_jobs = 1
reject = dict(eeg=300e-6) # uVolts (EEG)
l_freq, h_freq, n_freq = 0.5, 90, 50 # Frequency setting... | tmax,
picks=picks,
baseline=None,
reject=reject)
results_dict[band] = epochs
return results_dict
def save_ev | ent_file(subject, data_folder):
"""
Parameters
----------
subject : subject name
data_folder : string
Returns
-------
""" |
sussexstudent/falmer | falmer/banners/migrations/0001_initial.py | Python | mit | 924 | 0.002165 | # Generated by Django | 2.0.8 on 2018-08-14 10:45
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Banner',
fields=[
('id', models.AutoField(auto_created=True, pri... | ('display_from', models.DateTimeField(blank=True, null=True)),
('display_to', models.DateTimeField(blank=True, null=True)),
('purpose', models.CharField(choices=[('NOTICE', 'Notice')], max_length=12)),
('heading', models.CharField(blank=True, max_length=256)),... |
simontakite/sysadmin | pythonscripts/headfirst/hfpy_code/01-MeetPython-Everyone-Loves-Lists/page30.py | Python | gpl-2.0 | 399 | 0.010025 |
movies = ["The Ho | ly Grail", 1975, "Terry Jones & Terry Gilliam", 91,
["Graham Chapman", ["Michael Palin", "John Cleese",
"Terry Gilliam", "Eric Idle", "Terry Jones"]]]
def print_lol(a_list):
for each_item in a_list:
if isinstance(each_item, list):
print_lol(each_item)
... | int_lol(movies)
|
kbase/metrics | source/custom_scripts/dump_query_results.py | Python | mit | 4,387 | 0.004559 | #!/usr/local/bin/python
import os
import mysql.connector as mysql
metrics_mysql_password = os.environ["METRICS_MYSQL_PWD"]
sql_host = os.environ["SQL_HOST"]
metrics = os.environ["QUERY_ON"]
def dump_query_results():
"""
It is a simple SQL table dump of a given query so we can supply users with custom tables... | kb_internal_user = 0 and wc.narrative_versio | n > 0 and is_deleted = 0 and is_temporary = 0;
#query = ("select * from metrics_reporting.narrative_app_flows")
query = ("select * from metrics_reporting.user_super_summary")
# CHANGE COLUMN HEADERS HERE TO MATCH QUERY HEADERS
# print("username\temail\tlast_signin_date\tmax_last_seen\tHasBeenSeen")
... |
aferr/LatticeMemCtl | configs/example/memtest.py | Python | bsd-3-clause | 7,651 | 0.01307 | # Copyright (c) 2006-2007 The Regents of The University of Michigan
# 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 ... | eing higher than the L1 latency
m5.ticks.setGlobalFrequency('1ns')
# instantiate configuration
m5.instantiate()
# simulate until program terminates
exit_event = m5.simulate(options.maxtick)
pr | int 'Exiting @ tick', m5.curTick(), 'because', exit_event.getCause()
|
DOE-NEPA/geonode_2.0_to_2.4_migration | migrate_base_topiccategory.py | Python | gpl-2.0 | 1,677 | 0.023256 | #!/usr/bin/python
import os
import psycopg2
import sys
file = open("/home/" + os.getlogin() + "/.pgpass", "r")
pgpasses = []
for line in file:
pgpasses.append(line.rstrip("\n").split(":"))
file.close()
for pgpass in pgpasses:
#print str(pgpass)
if pgpass[0] == "54.236.235.110" and pgpass[3] == "geonode":
sr... | None)
#gn_description
assignments.append(src_row[3])
#gn_description_en
assignments.append(None)
#is_choice
assignments.append(src_row[4])
try:
dst_cur.execute("insert into base_topiccategory(id, identifier, description, description_en, gn_description, gn_description_en, is_choice) | values (%s, %s, %s, %s, %s, %s, %s)", assignments)
dst.commit()
except Exception as error:
print
print type(error)
print str(error) + "select id, identifier, description, gn_description, is_choice from base_topiccategory"
print str(src_row)
dst.rollback()
dst.commit()
src_cur.close()
dst_c... |
mikebryant/tsumufs | lib/tsumufs/metrics.py | Python | gpl-3.0 | 1,997 | 0.008513 | # Copyright (C) 2008 Google, Inc. All Rights Reserved.
# Copyright (C) 2012 Michael Bryant.
#
# 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 opt... |
if not _metrics.has_key(name):
_metrics[name] = [ 1, delta_t ]
else:
_metrics[name][0] += 1
_metrics[name][1] += delta_t
finally:
_metrics_lock.release()
return result
return wrapper
@extendedattribute('root', 'tsumufs.metrics')
def xattr_metrics(type_, path, val... | f len(_metrics.keys()) == 0:
return '{}'
result = '{ '
for name in _metrics.keys():
result += ("'%s': %f (%d), " %
(name, _metrics[name][1] / _metrics[name][0],
_metrics[name][0]))
result = result[:-2]
result += ' }'
return result
finally:
_me... |
Ormod/pghoard | pghoard/common.py | Python | apache-2.0 | 6,515 | 0.001995 | """
pghoard - common utility functions
Copyright (c) 2015 Ohmu Ltd
See LICENSE for details
"""
import fcntl
import logging
import os
try:
from backports import lzma # pylint: disable=import-error, unused-import
except ImportError:
import lzma # pylint: disable=import-error, unused-import
try:
from ur... | ueError("invalid connection_string fragment {!r}".format(rem))
connection_string = rem[i + 1:] # pylint: disable=undefined-loop-variable
else:
res = rem.split(None, 1)
if len(res) > 1:
value, connection_string = res
else:
value, co... | og, connection_string_or_info):
"""Look up password from the given object which can be a dict or a
string and write a possible password in a pgpass file;
returns a connection_string without a password in it"""
info = get_connection_info(connection_string_or_info)
if "password" not in info:
r... |
r39132/airflow | airflow/task/task_runner/__init__.py | Python | apache-2.0 | 1,803 | 0.001109 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | ed 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.
from airflow import configuration
from airflow.task.task_runner.standard_task_runner import StandardTaskRunner
from airflow.exceptions import AirflowException
_TASK_RUNNER = c... |
gylian/sickrage | sickbeard/providers/ezrss.py | Python | gpl-3.0 | 5,370 | 0.003538 | # Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage 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,... | dSearchResults(self, show, episodes, search_mode, manualSearch=False, downCurQuality=False):
self.show = show
results = {}
if show.air_by_date or show.sports:
logger.log(self.name + u" doesn't support air-by-date or sports backloging because of limitations on their RSS search.",
... | ults = generic.TorrentProvider.findSearchResults(self, show, episodes, search_mode, manualSearch, downCurQuality)
return results
def _get_season_search_strings(self, ep_obj):
params = {}
params['show_name'] = helpers.sanitizeSceneName(self.show.name, ezrss=True).replace('.', ' ').encode(... |
bd808/tools-stashbot | stashbot/__init__.py | Python | gpl-3.0 | 845 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of bd808's stashbot application
# Copyright (C) 2015 Bryan Davis and contributors
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3... | any later version.
#
# This program is distributed in | the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <... |
DInnaD/CS50 | pset6/caesar.py | Python | apache-2.0 | 2,532 | 0.011453 | import cs50
import sys
def main():
if len(sys.argv) != 2:
print("You should provide cmd line arguments!")
exit(1)
#if sys.argv[1].isalpha() == False:
#print("You should provide valid key!")
#exit(1)
kplainText = int(sys.argv[1])
cipher = []
plainText = cs50.... |
# print("plaintext: ")#;//ask user
# fgets(plainText, sizeof(plainText), stdin);//get user input & store it in planText var++++++++
# print("ciphertext: ")#;//print the ciphered text
# caesarCipher(plainText,key)
# //system(pause);//connect out if not use wind---------------------------???????????... | int i = 0
# char cipher
# int cipherValue
# while plainText[i] != '\0' and strlen(plainText) -1 > i :break#// for(int i=1,len=strlen(name);i<len;i++)
# if isalpha(plainText[i]) and islower(plainText[i]):
# cipherValue = ((int)((plainText[i]) - 97 + key) % 26 + 97)
# ... |
akvo/akvo-rsr | akvo/rsr/models/organisation_document.py | Python | agpl-3.0 | 6,312 | 0.003485 | # -*- coding: utf-8 -*-
# Akvo RSR is covered by the GNU Affero General | Public License.
# See more details in the license.txt file located at the root folder of the Akvo RSR module.
# For additional details on the GNU license please see < h | ttp://www.gnu.org/licenses/agpl.html >.
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import ugettext_lazy as _
from ..fields import ValidXMLCharField
from akvo.codelists.models import Country, DocumentCategory, Language
from akvo.codelists.store.defau... |
Tocknicsu/nctuoj_contest | test/api/contest/put_contest.py | Python | apache-2.0 | 3,747 | 0.004003 | import datetime
data = [
{
"name": "test_put_contest_no_login",
"url": "/api/contest/",
"method": "put",
"payload": {
"title": "change",
"start": "2001-01-01 00:00:00",
"end": "2001-01-01 00:00:00",
"freeze": "0",
"descripti... | .now())[:-7],
"end": str(datetime.datetime.now() + dat | etime.timedelta(hours=3))[:-7],
"freeze": 0,
"description": "XD"
},
"response_status": 200,
"response_data":{
"msg": {
"title": "change",
"start": str(datetime.datetime.now())[:-7],
"end": str(datetime.datetime.... |
bjuvensjo/scripts | vang/misc/tests/test_wc.py | Python | apache-2.0 | 2,185 | 0.000915 | from unittest.mock import mock_open, patch, call
import pytest
from pytest import raises
from vang.misc.wc import is_excluded, is_i | ncluded, count_words, count_letters, count, count_all, get_files, parse_args
@pytest.mark.parametrize('excluded, | expected', [
[('foo.txt',), True],
[('.*.txt',), True],
[('.*.txt', 'bar.txt'), True],
[('foo.txtx',), False],
])
def test_is_excluded(excluded, expected):
assert is_excluded('foo.txt', excluded) == expected
@pytest.mark.parametrize('included, expected', [
[('foo.txt',), True],
[('.*.txt',... |
hofschroeer/shinysdr | shinysdr/test/test_devices.py | Python | gpl-3.0 | 5,929 | 0.004891 | # Copyright 2014, 2015 Kevin Reid <kpreid@switchb.org>
#
# This file is part of ShinySDR.
#
# ShinySDR 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) a... | name='a'), Device()]).get_name())
| self.assertEqual('a+b', merge_devices([Device(name='a'), Device(name='b')]).get_name())
def test_components_disjoint(self):
d = merge_devices([
Device(components={'a': ExportedState()}),
Device(components={'b': ExportedState()})
])
self.assertEqual(d, IDevice(d)... |
metomi/rose | metomi/rose/task_run.py | Python | gpl-3.0 | 6,607 | 0 | # Copyright (C) British Crown (Met Office) & Contributors.
# This file is part of Rose, a framework for meteorological suites.
#
# Rose 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 L... | (conf_dir):
raise TaskAppNotFoundError(t_prop.task_name, app_key)
opts.conf_dir = conf_dir
return self.app_runner(opts, args)
def main():
"""Launcher for the CLI."""
opt_parser = RoseOptionParser(
usage='rose task-run [OPTIONS] [--] [APP-COMMAND ...]',
... | is worth
noting that if the environment variables are already provided by
`rose task-env`, this command will not override them.
Normally, the suite task will select a Rose application configuration
that has the same name as the task. This can be overridden by the
`--app-key=KEY` option or the `ROSE_TASK_APP` environm... |
google/loaner | loaner/web_app/backend/api/messages/template_messages.py | Python | apache-2.0 | 2,625 | 0.007619 | # Copyright 2018 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | ssages.StringField(3)
class UpdateTemplateRequest(messages.Message):
"""UpdateTemplateRequest request for ProtoRPC message.
Attributes:
name: str, The name of the name being requested.
body: str, the text of the body.
title: str, the subject line or title of the template.
"""
name = messages.Stri... | sages.Message):
"""UpdateTemplateRequest request for ProtoRPC message.
Attributes:
name: The template to remove / delete.
"""
name = messages.StringField(1)
class CreateTemplateRequest(messages.Message):
"""CreateTemplateRequest ProtoRPC message.
Attributes:
template: Template, A Template to cre... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.