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 |
|---|---|---|---|---|---|---|---|---|
muffinresearch/addons-server | lib/es/tests/test_models.py | Python | bsd-3-clause | 3,449 | 0 | import mock
from nose.tools import eq_
import amo.tests
from lib.es.models import Reindexing
class TestReindexManager(amo.tests.TestCase):
def test_flag_reindexing(self):
assert Reindexing.objects.filter(site='foo').count() == 0
# Flagging for the first time.
res = Reindexing.objects._f... | )])
def test_is_reindexing(self):
assert Reindexing.objects.filter(site='foo').count() == 0
assert not Reindexing.objects._is_reindexing('foo')
Rein | dexing.objects.create(site='foo', new_index='bar', old_index='baz',
alias='quux')
assert Reindexing.objects._is_reindexing('foo')
# Reindexing on another site doesn't clash.
assert not Reindexing.objects._is_reindexing('bar')
@mock.patch('lib.es.models.Rei... |
7digital/troposphere | troposphere/template_generator.py | Python | bsd-2-clause | 15,713 | 0.000064 | """
This module makes it possible to instantiate a new Troposphere Template object
from an existing CloudFormation Template.
Usage:
from troposphere.template_generator import TemplateGenerator
import json
with open("myCloudFormationTemplate.json") as f:
json_template = json.load(f)
template =... | tor._inspect_functions = d
return self._inspect_functions
def _get_resource_type_cls(self, resource):
"""Attempts to return troposphere class that represents Type of provided
resource. Attempts to find the troposphere class who's `resource_type | `
field is the same as the provided resources `Type` field.
:param resource: Resource to find troposphere class for
:return: None: If provided resource does not have a `Type` field
If no class found for provided resource
type: Type of provided resource
... |
bioidiap/bob.bio.spear | bob/bio/spear/database/voxforge.py | Python | gpl-3.0 | 6,256 | 0.002877 | #!/usr/bin/env python
# @author: Yannick Dayer <yannick.dayer@idiap.ch>
# @date: Wed 16 Jun 2021 17:21:47 UTC+02
import csv
import logging
from pathlib import Path
import click
from tqdm import tqdm
import bob.io.audio
import bob.io.base
from bob.bio.base.database import CSVDataset
from bob.bio.base.database impo... | bob.extension.download import get_file
from bob.extension.download imp | ort search_file
from bob.extension.scripts.click_helper import verbosity_option
logger = logging.getLogger(__name__)
def get_voxforge_protocol_file():
"""Returns the protocol definition archive, downloading it if necessary.
Looks into ``bob_data_folder``, into the ``datasets`` folder for the file, and
d... |
mhbu50/erpnext | erpnext/patches/v11_1/make_job_card_time_logs.py | Python | gpl-3.0 | 1,348 | 0.011869 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
import frappe
def execute():
frappe.reload_doc('manufacturing', 'doctype', 'job_card_time_log')
if (frappe.db.table_exists("Job Card")
and frappe.get_meta("Job Card").has_f... | _in_mins,
d.for_quant | ity, d.name, 'Job Card', 'time_logs', frappe.generate_hash("", 10)])
if time_logs:
frappe.db.sql(""" INSERT INTO
`tabJob Card Time Log`
(from_time, to_time, time_in_mins, completed_qty, parent, parenttype, parentfield, name)
values {values}
... |
navcoindev/navcoin-core | src/test/navcoin-util-test.py | Python | mit | 410 | 0.017073 | #!/usr/bin/python
# Copyright 2014 BitPay, Inc.
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.ope | nsource.org/licenses/mit-license.php.
from __future__ import division,print_function,unicode_literals
import os
import bctest
import buildenv
if __name__ == '__main__':
bctest.bctester(os.environ["srcdir"] + "/test/data",
"navcoin- | util-test.json",buildenv)
|
opentrials/processors | tests/fixtures/warehouse/pubmed.py | Python | mit | 1,721 | 0.001743 | # -*- coding: utf-8 -*-
fr | om __future | __ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import uuid
import pytest
import datetime
@pytest.fixture
def pubmed_record(conn):
record = {
'meta_id': uuid.uuid1().hex,
'meta_source': 'http://www.ncbi.nlm.ni... |
manuco/LayeredLighting | model/bankaccess.py | Python | gpl-3.0 | 160 | 0.025 | # -*- coding: utf-8 | -*-
class BankAccess(object):
def __init__(self):
self.pendingUid | s = {}
pass
def get(self, uid):
|
laisee/bitfinex | bitfinex/__init__.py | Python | mit | 48 | 0 | from bitfi | nex.client import Cl | ient, TradeClient
|
alviezhang/laputa | laputa/notify.py | Python | mit | 1,042 | 0 | # coding: utf-8
import requests
_IFTTT_URL = 'https://maker.ifttt.com/trigger/{event}/with/key/{key}'
class IFTTTNotifier:
def __init__(self, key, event_name):
self._key = key
self._timeout = 5
self._event = event_name
def trigger(self, **kwargs):
return self._trigger(self.... | f _trigger(self, event, **kwargs):
url = _IFTTT_URL.format(key=self._key, event=event)
valid_params = ('value1', 'value2', 'value3')
query_data = {}
for key in valid_params:
if key in kwargs:
query_data[key] = kwargs[key]
if query_data:
r =... | rl, json=query_data, timeout=self._timeout)
else:
r = requests.post(url, timeout=self._timeout)
if r.status_code == 200:
print(r.text)
elif r.status_code == 401:
raise RuntimeError('IFTTT trigger failed! invalid key')
else:
raise RuntimeErr... |
sils1297/Tale | tests/test_soul.py | Python | gpl-3.0 | 48,428 | 0.00351 | """
Unit tests for the Soul
'Tale' mud driver, mudlib and interactive fiction framework
Copyright by Irmen de Jong (irmen@razorvine.net)
"""
from __future__ import print_function, division, unicode_literals, absolute_import
import unittest
import tale
import tale.base
import tale.soul
import tale.player
... | harry, player)) # you kick harry
self.assertEqual("harry", tale.soul.who_replacement(player, harry, jul | ie)) # fritz kicks harry
self.assertEqual("harry", tale.soul.who_replacement(player, harry, None)) # fritz kicks harry
self.assertEqual("you", tale.soul.who_replacement(julie, player, player)) # julie kicks you
self.assertEqual("Fritz", tale.soul.who_replacement(julie, player, harry))... |
LinDA-tools/LindaWorkbench | linda/endpoint_monitor/models.py | Python | mit | 631 | 0.006339 | from djan | go.db import models
from linda_app.models import DatasourceDescription
# A single test over a data source
class EndpointTest(model | s.Model):
execution_time = models.DateTimeField(auto_now_add=True) # test timestamp
datasource = models.ForeignKey(DatasourceDescription) # tested datasource
up = models.BooleanField(default=False) # was the endpoint up? - simple select query
response_time = models.IntegerField(blank=True, null=True)... |
samarjeet27/ynoteclassic | Code/Clean.py | Python | gpl-2.0 | 894 | 0.010067 | # Deletes the temp files and Compiler-Generated Directory
import os
import shutil
""" Gets a list of files using a extension filter"""
def getFiles(relevant_path):
included_extenstions = ['pdb','txt','config','xml' ]
file_names = [fn for fn in os.listdir(relevant_path) if any([fn.endswith(ext) for ext in inclu... | t's contents"""
def deleteDir(path):
if(os.path.isdir(path)):
shutil.rmtree(path)
else:
print("Directory Deosn't exist")
# delete all directories
deleteDir("SS.Ynote.Classic\\obj")
deleteDir("Docking\\bin")
deleteDir("Docking\\obj")
delet | eDir("FastColoredTextBox\\bin")
deleteDir("FastColoredTextBox\\obj")
|
foursquare/pants | tests/python/pants_test/engine/examples/parsers.py | Python | apache-2.0 | 10,272 | 0.011682 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import functools
import importlib
import inspect
import threading
from builtins import st... | self.symbol_table = symbol_table
def _as_type(self, type_or_name):
return _import(type_or_name) if isinstance(type_or_name, six.string_types) else type_or_name
@staticmethod
def _object_decoder(obj, symbol_table):
# A magic field will indicate type and this can be used to wrap the object in a type.
... | decoder(self):
symbol_table = self.symbol_table.table()
decoder = functools.partial(self._object_decoder,
symbol_table=symbol_table.__getitem__ if symbol_table else self._as_type)
return JSONDecoder(encoding='UTF-8', object_hook=decoder, strict=True)
def parse(self, filepa... |
Frumple/mrt-file-server | mrt_file_server/utils/string_utils.py | Python | mit | 81 | 0.037037 | import re
def str_c | ontains_whi | tespace(str):
return bool(re.search(r"\s", str)) |
SimplyKnownAsG/voluptuous | voluptuous/schema_builder.py | Python | bsd-3-clause | 39,076 | 0.001177 | import collections
import inspect
import re
from functools import wraps
import sys
from contextlib import contextmanager
try:
import error as er
except ImportError:
from . import error as er
if sys.version_info >= (3,):
long = int
unicode = str
basestring = str
ifilter = filter
def iterit... | hema will be included in output
REMOVE_EXTRA = 2 # extra keys not in schema will be excluded from output
def _isnamedtuple(obj):
return isinstance(obj, tuple) and hasattr(obj, '_fields')
class Undefined(object):
def __nonzero__(self):
return False |
def __repr__(self):
return '...'
UNDEFINED = Undefined()
def default_factory(value):
if value is UNDEFINED or callable(value):
return value
return lambda: value
@contextmanager
def raises(exc, msg=None, regex=None):
try:
yield
except exc as e:
if msg is not No... |
zhangg/trove | trove/guestagent/datastore/experimental/vertica/system.py | Python | apache-2.0 | 5,231 | 0.000191 | # Copyright [2015] Hewlett-Packard Development Company, L.P.
# 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... | ESIGN_KSAFE(%s)"
NODE_STATUS = "SELECT node_state FROM nodes where node_state <> '%s'"
STOP_DB = "/opt/vertica/bin/adminTools -t stop_db -F -d %s -p '%s'"
START_DB = "/opt/vertica/bin/adminTools -t start_db -d %s -p '%s'"
STATUS_ACTIVE_DB = "/opt/vertica/bin/adminTools -t show_active_db"
STATUS_DB_DOWN = "/opt/vertica/... | _policy "
"-d %s -p '%s'")
SEND_CONF_TO_SERVER = ("rsync -v -e 'ssh -o "
"UserKnownHostsFile=/dev/null -o "
"StrictHostKeyChecking=no' --perms --owner --group "
"%s %s:%s")
SSH_KEY_GEN = "ssh-keygen -f %s/.ssh/id_rsa -t rsa -N ''... |
qsnake/gpaw | gpaw/dfpt/mixer.py | Python | gpl-3.0 | 17,948 | 0.002953 | # Copyright (C) 2003 CAMP
# Please see the accompanying LICENSE file for further information.
"""
Ref. to Kresse-paper ... XXX
"""
import numpy as np
from gpaw.utilities.blas import axpy
from gpaw.fd_operators import FDOperator
class BaseMixer:
"""Pulay density mixer."""
def __init__(self, beta=0.1, ... | ization and after each move of the atoms.
my_nuclei: All nuclei in local domain.
"""
# History for Pulay mixing of densities:
self.nt_iG = [] # Pseudo-electron densities
self.R_iG = [] # Residuals
self.A_ii = np.zeros((0, 0))
self.dNt = None
... | iap = []
self.dD_iap = []
def get_charge_sloshing(self):
"""Return number of electrons moving around.
Calculated as the integral of the absolute value of the change
of the density from input to output."""
return self.dNt
def set_charge_sloshing(self, dNt):
... |
mscuthbert/abjad | abjad/tools/sequencetools/sum_consecutive_elements_by_sign.py | Python | gpl-3.0 | 1,786 | 0.0028 | # -*- encoding: utf-8 -*-
import itertools
from abjad.tools import mathtools
def sum_consecutive_elements_by_sign(sequence, sign=(-1, 0, 1)):
'''Sums consecutive `sequence` elements by `sign`.
::
>>> sequence = [0, 0, -1, -1, 2, 3, -5, 1, 2, 5, -5, -6]
::
>>> sequencetools.sum_consecut... | -11]
::
>>> sequencetools.sum_consecutive_elements_by_sign(sequence, sign=[0, 1])
[0, -1, -1, 5, -5, 8, -5, -6]
::
>>> sequencetools.sum_consecu | tive_elements_by_sign(sequence, sign=[-1, 0, 1])
[0, -2, 5, -5, 8, -11]
When ``-1`` in `sign`, sum consecutive negative elements.
When ``0`` in `sign`, sum consecutive ``0`` elements.
When ``1`` in `sign`, sum consecutive positive elements.
Returns list.
'''
result = []
generat... |
DataONEorg/d1_python | lib_common/src/d1_common/iter/bytes.py | Python | apache-2.0 | 1,660 | 0 | # This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you ma... | IONS OF ANY KIND, e | ither express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generator that returns a ``bytes`` object in chunks."""
import io
import d1_common.const
class BytesIterator(object):
"""Generator that returns a ``bytes`` object in chunks."""
... |
open-synergy/partner-contact | base_location_lau/__openerp__.py | Python | agpl-3.0 | 496 | 0 | # -*- coding: utf-8 -*-
# © 2016 Daniel Reis
# License AGPL-3.0 or later (http://www.gnu.org/licens | es/agpl).
{
'name': 'Local Administrative Units',
'category': 'Localisation/Europe',
'version': '8.0.1.0.0',
'depends': [
'base',
],
'data': [
'views/res_partner_lau_view.xml',
'security/ir.model.access.csv',
],
'author': 'Daniel Reis, '
'Odoo Commun... | sociation (OCA)',
'license': 'AGPL-3',
'installable': True,
}
|
ngannguyen/aimseqtk | src/overlap/overlap_numsam.py | Python | mit | 6,583 | 0.001823 | #Copyright (C) 2013 by Ngan Nguyen
#
#Released under the MIT license, see LICENSE.txt
'''
1/ split the clones by number of samples that share them
2/ randomly select n clones for each number of samples
3/ print summary results: numsam2clonecount
Input: the clone2sample2size directory
minimum number of samples
... | ath.join(self.outdir, str(num))
pickle.dump(clones, gzip.open(outfile, "wb"))
class SplitClonesByNumsamAgg(Target):
def __init__(self, indir, outdir, sampling):
Target.__init__(self)
self.indir = indir
self.outdir = outdir
self.sampling = sampling
def run(self):
... | for v in os.listdir(self.indir):
vdir = os.path.join(self.indir, v)
for num in os.listdir(vdir):
if num not in nums:
nums.append(num)
numsam2clonecount = {}
f2 = None
if self.sampling is not None:
samplingfile = os.pat... |
drakipovic/deep-learning | 1. labos/data.py | Python | mit | 2,378 | 0.009672 | import math
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, precision_score, recall_score
class Random2DGaussian(object):
min_x = 0
max_x = 10
min_y = 0
max_y = 10
def __init__(self):
self.mean = [(self.max_x-se... | ], c=Y_[wrong_idx], marker='s', label='wrong', s=s[wrong_idx])
plt.legend(loc='upper left')
plt.show()
def eval_perf_binary(Y, Y_):
acc = accuracy_score(Y, Y_)
prec = precision_score(Y, Y_, average='binary')
rec = recall_score(Y, Y_, average='binary')
return acc, prec, rec
def graph_surface(... | [1][1]
xx, yy = np.meshgrid(np.linspace(x_min, x_max, num=100),np.linspace(y_min, y_max, num=100))
x = xx.flatten()
y = yy.flatten()
XX = np.stack((x, y), axis=1)
Z = fun(XX)
plt.pcolormesh(xx, yy, Z.reshape(xx.shape))
plt.contour(xx, yy, Z.reshape(xx.shape), levels = [offset])
|
dwadler/QGIS | tests/src/python/test_qgslayoutpolyline.py | Python | gpl-2.0 | 12,207 | 0.000573 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsLayoutItemPolyline.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.... | ert myTestResult, myMessage
self.polyline.deselectNode()
self.polyline.setDisplayNodes(False)
checker = QgsLayoutChecker(
'composerpolyline_defaultstyle', self.layout)
checker.setControlPathPrefix("composer_polyline")
myTestResult, myMessage = checker.testLayout()
... | .removeNode(100)
self.assertEqual(rc, False)
checker = QgsLayoutChecker(
'composerpolyline_defaultstyle', self.layout)
checker.setControlPathPrefix("composer_polyline")
myTestResult, myMessage = checker.testLayout()
assert myTestResult, myMessage
self.assert... |
kubernetes/perf-tests | clusterloader2/pkg/prometheus/manifests/dashboards/network.dashboard.py | Python | apache-2.0 | 5,840 | 0.00274 | #!/usr/bin/env python3
# Copyright 2019 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | : sync rules duation",
description="Latency of one round of kube-proxy syncing proxy rules.",
targets=d.show_quantiles(
"histogram_quantile({quantile}, sum(rate(kubeproxy_sync_proxy_rules_duration_seconds_bucket[5m])) by (le))"
),
yAxes=g.single_y_axis(format=g.SECONDS_FORMAT... | y_rules_service_changes_total[5m]))",
description="Rate of service changes that the proxy has seen over 5m",
legend="rate",
),
d.simple_graph(
"kube-proxy: pending service changes",
"sum(kubeproxy_sync_proxy_rules_service_changes_pending)",
description="Number of pending ... |
thomas-schmid-ubnt/avocado | avocado/utils/software_manager.py | Python | gpl-2.0 | 32,736 | 0.000122 | # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# bu... | ,
'zypper': ZypperBackend}
if backend_type not in backend_mapping.keys():
raise NotImplementedError('Unimplemented package management '
'system: %s.' % backend_type)
backend = backend_mapping[backend_type]... | nitialized = True
def __getattr__(self, name):
self._init_on_demand()
return self.backend.__getattribute__(name)
class BaseBackend(object):
"""
This class implements all common methods among backends.
"""
def install_what_provides(self, path):
"""
Installs packag... |
ulethHCI/GLuskap | plugins/moment_curve.py | Python | gpl-2.0 | 3,644 | 0.003293 | #!/usr/bin/python2.3
# This is the short name of the plugin, used as the menu item
# for the plugin.
# If not specified, the name of the file will be used.
shortname = "Moment Curve layout (Cohen et al. 1995)"
# This is the long name of the plugin, used as the menu note
# for the plugin.
# If not specified, the short ... | ?",
"Would you like to apply the layout to the current grap | h? If not, a complete graph will be generated and the current graph cleared.")
if res:
generate = False
# Go through and eliminate any existing bend points
from graph import DummyVertex
for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]:
... |
sou81821/chainer | chainer/testing/__init__.py | Python | mit | 336 | 0 | import nose
def run_ | module(name, file):
"""Run current test cases of the file.
Args:
name: __name__ attrinute of the file.
file: __file__ attribute of the file.
"""
if name == '__main__':
nose.runmodule(argv=[file, '-vvs', '-x', '--pdb', '--pdb-failu | re'],
exit=False)
|
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractSweetjamtranslationsCom.py | Python | bsd-3-clause | 561 | 0.033868 |
def extractSweetjamtranslation | sCom(item):
'''
Parser for 'sweetjamtranslations.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item | ['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl... |
facebookexperimental/eden | eden/integration/linux_cgroup_test.py | Python | gpl-2.0 | 2,902 | 0.001723 | #!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
import os
import os.path
import pathlib
import platform
import unittest
from .lib.testcase import IntegrationTestCase
if plat... | .scope\n"
b"8:cpuset:/\n"
b"7:pids:/user.slice/user-2233.slice/session-163872.scope\n"
b"6:devices:/user.slice\n"
b"5:memory:/user.slice/user-2233.slice/session-163872.scope\n"
b"4:perf_event:/\n"
b"3:net_cls,net_prio:/\n"
b"2:cpu:/user... | 233.slice/session-163872.scope\n"
b"1:name=systemd:/user.slice/user-2233.slice/session-163872.scope\n"
)
with self.assertRaises(NotImplementedError):
LinuxCgroup._parse_proc_file(proc_file_content)
def test_cgroup_from_sys_fs_cgroup_path(self) -> None:
path = pathlib... |
IKAcc/Serlina | rest_cms/Blog/apps.py | Python | mit | 83 | 0 | from | djang | o.apps import AppConfig
class BlogConfig(AppConfig):
name = 'Blog'
|
jonasjberg/autonameow | autonameow/extractors/text/extractor_epub.py | Python | gpl-2.0 | 2,705 | 0.00074 | # -*- coding: utf-8 -*-
# Copyright(c) 2016-2020 Jonas Sjöberg <autonameow@jonasjberg.com>
# Source repository: https://github.com/jonasjberg/autonameow
#
# This file is part of autonameow.
#
# autonameow is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public L... | book = epub.read_epub(unicode_filepath)
except epub.EpubException as e:
raise ExtractorError(e)
except Exceptio | n as e:
raise ExtractorError('Unhandled exception in "ebooklib": {!s}'.format(e))
# TODO: The epub text extractor repeats a lot of text.
# NOTE: Books produced by 'calibre' are messy. Seems to use tables for
# formatting and classes "calibreN" with N being just about any number..
text_lines = l... |
steveb/heat | heat/tests/engine/service/test_stack_create.py | Python | apache-2.0 | 18,029 | 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
# ... |
stk.t.t, {}, None, {})
self.assertEqual(exception.StackValidationFailed, ex.exc_info[0])
def test_stack_create_no_credentials(self):
c | fg.CONF.set_default('deferred_auth_method', 'password')
stack_name = 'test_stack_create_no_credentials'
params = {'foo': 'bar'}
template = '{ "Template": "data" }'
stk = tools.get_stack(stack_name, self.ctx)
# force check for credentials on create
stk['WebServer'].requir... |
dannyperry571/theapprentice | plugin.video.Carrera/default.py | Python | gpl-2.0 | 19,611 | 0.037275 | # -*- coding: utf-8 -*-
'''
Template Add-on
Copyright (C) 2016 Demo
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 ... | Menu((name).replace('/',''),url3,8,ICON,FANART,'','','')
else:
Clean_name(name,url3)
################################### TIDY UP NAME #############################
def Clean_name(name, | url3):
name1 = (name).replace('S01E','S01 E').replace('(MovIran).mkv','').replace('The.Walking.Dead','').replace('.mkv','').replace('Tehmovies.com.mkv','').replace('Nightsdl','').replace('Ganool','')
name2=(name1).replace('.',' ').replace(' (ParsFilm).mkv','').replace('_TehMovies.Com.mkv','').replace(' (SaberFu... |
TheCacophonyProject/Full_Noise | test/test_device_query.py | Python | agpl-3.0 | 3,489 | 0.002006 | import pytest
from test.testexception import AuthenticationError, UnprocessableError
class TestDeviceQuery:
def test_query(self, helper):
admin_user = helper.admin_user()
clare = helper.given_new_user(self, "clare")
clares_group = helper.make_unique_group_name(self, "clares_group")
... | devices = clare.query_devices(devices=[terminator, terminator2])["devices"]
ids = set([device["id"] for device in devices])
assert ids == set([terminator.get_id(), terminator2.get_id()])
new_group = helper.make_unique_group_name(self, "clares_group")
with pytest.raises(Authenticatio... | nator2], groups=[clares_group], operator="AND"
)["devices"]
ids = set(device["id"] for device in devices)
assert ids == set([terminator.get_id(), terminator2.get_id()])
with pytest.raises(UnprocessableError):
devices = clare.query_devices(devices=[terminator, terminator2], op... |
felix-dumit/campusbot | yowsup2/yowsup/layers/protocol_contacts/protocolentities/__init__.py | Python | mit | 302 | 0.003311 | from .iq_sync import SyncIqProtocolEntity
from .iq_sync_get import GetSyncIqProtocolEntity
from .iq_sync_result import Resul | tSyncIqProtocolEntity
from .notification_contact_add import AddContactNotificationProtocolEntity
from .notification_contact_remove import RemoveContactNotificationP | rotocolEntity
|
alexef/gobject-introspection | misc/update-gobject-annotations.py | Python | gpl-2.0 | 909 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
srcdir = sys.argv[1]
sources = []
projname = 'gobject'
subdir = os.path.join(srcdir, projname)
headersfile = os.path.join(subdir, projname + '-public-headers.txt')
f = open(headersfile)
line = f.read()
f.close()
... |
['./g-ir-annotation-tool', '--extract', '-DGOBJECT_COMPILATION',
'-I' + srcdir,
'-I' + os.path.join(srcdir, 'glib'),
| '-I' + os.path.join(srcdir, 'gobject'),
'-I' + os.path.join(srcdir, 'gmodule')] + sources)
|
kbase/narrative | src/biokbase/narrative/tests/test_content_manager_util.py | Python | mit | 1,027 | 0 | import unittest
from biokbase.narrative.contents.manager_util import base_model
class ManagerUtilTestCase(unittest.TestCase):
def test_base_model(self):
name = "foo"
path = "bar"
model = base_model(name, path)
self.assertIn("name", mode | l)
self.assertEqual(model["name"], name)
self.assertIn("path", model)
self.assertEqual(model["path"], path)
self.assertIn("last_modified", model)
self.assertEqual(model["last_modified"], "00-00-0000")
self.assertIn("created", model)
self.assertEqual(model["created... | self.assertIsNone(model["content"])
self.assertIn("format", model)
self.assertIsNone(model["format"])
self.assertIn("mimetype", model)
self.assertIsNone(model["mimetype"])
self.assertIn("writable", model)
self.assertFalse(model["writable"])
self.assertIn("type", ... |
spencerkclark/aospy | aospy/automate.py | Python | apache-2.0 | 20,123 | 0 | """Functionality for specifying and cycling through multiple calculations."""
from __future__ import print_function
from distutils.version import LooseVersion
from multiprocessing import cpu_count
import dask
import dask.bag as db
import distributed
import itertools
import logging
import pprint
import traceback
from... | parent):
"""Get all attributes of the given type from the given object.
Parameters
----------
type_ : The desired type
parent : The object from which to get the attributes with type matching
'type_'
Returns
-------
A list (possibly empty) of attributes from 'parent'
"""
... | ecifications."""
_CORE_SPEC_NAMES = {_OBJ_LIB_STR, _PROJECTS_STR, _MODELS_STR, _RUNS_STR}
_AUX_SPEC_NAMES = {_VARIABLES_STR,
_REGIONS_STR,
'date_ranges',
'input_time_intervals',
'input_time_datatypes',
... |
swirlingsand/self-driving-car-nanodegree-nd013 | play/advanced_lane_finding-direction_of_the_gradient_exercise.py | Python | mit | 1,656 | 0.001208 | import | numpy | as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import pickle
# Read in an image
image = mpimg.imread('signs_vehicles_xygrad.png')
# Define a function that applies Sobel x and y,
# then computes the direction of the gradient
# and applies a threshold.
def dir_threshold(img, sobel_... |
charanpald/wallhack | wallhack/egograph/EgoSimulator.py | Python | gpl-3.0 | 7,289 | 0.009878 | '''
Created on 23 Jul 2009
@author: charanpal
'''
from exp.sandbox.data.ExamplesList import ExamplesList
from apgl.graph.DictGraph import DictGraph
from apgl.graph.SparseGraph import SparseGraph
from sandbox.util.Parameter import Parameter
import numpy
class EgoSimulator:
"""
A class which simula... | Network. In
this case one models information by taking as input a graph and then iterating using
a classifie | r for all pairs of vertices. The presence of information is stored
in the last index of the VertexList as a (0, 1) value.
"""
def __init__(self, graph, egoPairClassifier, preprocessor=None):
self.graph = graph
self.egoPairClassifier = egoPairClassifier
self.preprocessor = pre... |
Richard-Mathie/cassandra_benchmark | vendor/github.com/datastax/python-driver/tests/integration/long/test_ipv6.py | Python | apache-2.0 | 4,499 | 0.005112 | # Copyright 2013-2016 DataStax, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... | raise unittest.SkipTest("Libev does not appear to be i | nstalled properly")
class AsyncoreConnectionTests(IPV6ConnectionTest, unittest.TestCase):
connection_class = AsyncoreConnection
def setUp(self):
if os.name == "nt":
raise unittest.SkipTest("IPv6 is currently not supported under Windows")
if AsyncoreConnection == -1:
... |
smn/blinky | blinky/core/migrations/0005_workertype_is_active.py | Python | bsd-3-clause | 455 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-16 12:50
from __fut | ure__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0004_auto_20161116_1209'),
]
operations = [
migratio | ns.AddField(
model_name='workertype',
name='is_active',
field=models.BooleanField(default=True),
),
]
|
erasmospunk/pychohistory | modules/BusinessLogic.py | Python | mit | 3,917 | 0.009957 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
import csv
import pprint
import sys
from modules import GoogSuggestMe, StampThatBit, TweetCatcher
__author__ = 'Giannis Dzegoutanis'
class BusinessLogic:
def __init__(self, db_directory, namespace=False):
self._db_directory = db_directory
... | r", time=1, output_format='python'):
if module.lower() == "GoogSuggestMe".lower():
with GoogSuggestMe.GoogSuggestMe(self._path()) as bucket:
self.printBucket(bucket, time, output_format)
elif module.lower() == "StampThatBit".lower():
with StampThatBit.Stamp | ThatBit(self._path()) as bucket:
self.printBucket(bucket, time, output_format)
elif module.lower() == "TweetCatcher".lower():
with TweetCatcher.TweetCatcher(self._path()) as bucket:
self.printBucket(bucket, time, output_format)
class TsvWriter:
"""
A CSV writer which will write rows to C... |
aledista/django-view-timer | django_view_timer/urls.py | Python | bsd-3-clause | 2,142 | 0.001867 | import warnings
from django.core.urlresolvers import ResolverMatch
from django.core.urlresolvers import (
RegexURLPattern as DjangoRegexURLPattern,
RegexURLResolver
)
from django.core.exceptions import ImproperlyConfigured
from django.utils import six
from django.utils.deprecation import RemovedInDjango20Warni... | Pattern):
def resolve(self, path):
match = self.regex.search(path)
if match:
kwargs = match.groupdic | t()
if kwargs:
args = ()
else:
args = match.groups()
kwargs.update(self.default_args)
callback = ViewTimeProfiler(self.callback) if DJANGO_VIEW_TIMER_ENABLED else self.callback
return ResolverMatch(callback, args, kwargs, self.n... |
Vaishal-shah/Envision | InformationScripting/scripts/evaluation/nonFinalPublic.py | Python | bsd-3-clause | 345 | 0.005797 | for astTuple in Query.input.tuples('ast'):
if type(astTuple.ast) is Field:
modifiers = astTuple.ast.modifiers
nonFinalPublic = modifiers.isSet(Modifier.ModifierFlag.Public) and n | ot modifiers.isSet(Modifier.Modi | fierFlag.Final)
if not nonFinalPublic:
Query.input.remove(astTuple)
Query.result = Query.input |
scemama/EZFIO | src/test.py | Python | gpl-2.0 | 1,581 | 0.010753 | #!/usr/bin/env python2
# EZFIO is an automatic generator of I/O libraries
# Copyright (C) 2009 Anthony SCEMAMA, CNRS
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 ... | lin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Anthony Scemama
# LCPQ - IRSAMC - CNRS
# Universite Paul Sabatier
# 118, route de Narbonne
# 31062 Toulouse Cedex 4
# scemama@irsamc.ups-tlse.fr
from ezfio import ezfio
EZFIO=ezfio
EZFIO.set_file('icule')
EZFIO.set_system_num_alpha(4)
E... |
EZFIO.write_buffer(indices,values,isize)
EZFIO.write_buffer(indices,values,isize)
EZFIO.close_write_ao_two_int()
indices = []
values = []
isize = 5
EZFIO.open_read_ao_two_int()
indices,values = EZFIO.read_buffer(isize)
print indices
print values
EZFIO.close_read_ao_two_int()
|
rocky/python-uncompyle6 | uncompyle6/scanners/pypy27.py | Python | gpl-3.0 | 901 | 0.00111 | # Copyright (c) 2016-2017, 2021 by Rocky Bernstein
"""
Python PyPy 2.7 bytecode scanner/deparser
This overlaps Python's 2.7's dis module, b | ut it can be run from
Python 3 and other versions of Python. Also, we save token
information for later use in deparsing.
"""
import uncompyle6.scanners.scanner27 as scan
# bytecode verification, verify(), uses JUMP_OPs from here
from xdis.opcodes import opcode_27pypy
JUMP_OPS = opcode_27pypy.JUMP_OPS
# We base this ... | r way around
# because we cleaned things up this way.
# The history is that 2.7 support is the cleanest,
# then from that we got 2.6 and so on.
class ScannerPyPy27(scan.Scanner27):
def __init__(self, show_asm):
# There are no differences in initialization between
# pypy 2.7 and 2.7
scan.Scan... |
bwasti/caffe2 | caffe2/python/examples/resnet50_trainer.py | Python | apache-2.0 | 16,263 | 0.000492 | ## @package resnet50_trainer
# Module caffe2.python.examples.resnet50_trainer
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import logging
import numpy as np
import time
import os
from caffe2.python ... | al_batch_size * args.num_shards
epoch_iters = int(args.epoch_size / global_batch_size)
args.epoch_size = epoch_iters * global_batch_size
log.info("Using epoch size: {}".format(args.epoch_size))
# Create ModelHelper object
train_arg_scope = {
'order': 'NCHW',
'use_cudnn': True,
... | me="resnet50", arg_scope=train_arg_scope
)
num_shards = args.num_shards
shard_id = args.shard_id
if num_shards > 1:
# Create rendezvous for distributed computation
store_handler = "store_handler"
if args.redis_host is not None:
# Use Redis for rendezvous if Redis hos... |
citrix-openstack-build/taskflow | taskflow/atom.py | Python | apache-2.0 | 6,234 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) 2013 Rackspace Hosting Inc. All Rights Reserved.
# Copyright (C) 2013 Yahoo! 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... | res=None, rebind=None,
auto_extract=True):
self.rebind = _build_arg_mapping(self.name, requires, rebind,
executor, auto_extract)
out_of_order = self.provides.intersection(self.requires)
if out_of_order:
raise excepti... | ns.InvariantViolation(
"Atom %(item)s provides %(oo)s that are required "
"by this atom"
% dict(item=self.name, oo=sorted(out_of_order)))
@property
def name(self):
return self._name
def __str__(self):
return "%s==%s" % (self.name, misc.get_ve... |
NickShaffner/rhea | test/test_system/test_memmap.py | Python | mit | 992 | 0.00504 |
from __future__ import print_function, division
import myhdl
from myhdl import instance, StopSimulation
from rhea.system import Global, Clock, Reset
from rhea.system import Barebone, Wishbone, AvalonMM, AXI4Lite
from rhea.utils.test import run_testbench, tb_args, tb_default_args
from rhea.cores.memmap import periph... | @myhdl.block
def bench_memmap():
tbdut = peripheral(csbus)
tbclk = clock.gen()
print( | csbus.regfiles)
@instance
def tbstim():
yield reset.pulse(111)
raise StopSimulation
return tbdut, tbclk, tbstim
run_testbench(bench_memmap)
if __name__ == '__main__':
testbench_memmap(args=tb_args())
|
stBecker/CB-CTT_Solver | Course timetabling solver/hard.py | Python | gpl-3.0 | 3,933 | 0.003814 | """ Curriculum-based course timetabling solver;
solves timetabling problems formulated in .ectt file format (http://tabu.diegm.uniud.it/ctt/)
Copyright (C) 2013 Stephan E. Becker
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License a... | "
# if data.timetable[position] is None and courseFitsIntoTimeslot(course, position[1]):
data.timetable[position] = course
data.empt | yPositions.remove(position)
data.forbiddenPositions.append(position)
def removeCourseAtPosition(position):
"""
remove the course which was assigned at the position from the timetable
and add it to unassigned events
returns the removed course
"""
ev = data.timetable[position]
if not ev ... |
pointhi/kicad-footprint-generator | scripts/Inductors/vishay_IHSM.py | Python | gpl-3.0 | 3,297 | 0.029117 | """
vishay IHSM series inductors
http://www.vishay.com/docs/34018/ihsm3825.pdf
http://www.vishay.com/docs/34019/ihsm4825.pdf
http://www.vishay.com/docs/34020/ihsm5832.pdf
http://www.vishay.com/docs/34021/ihsm7832.pdf
"""
#sizes,shapes,etc]
#name, L, W, pad-w, pad-w, pad-gap, pad-h, datasheet
inductors = [
[3825, 11.18... | nd(PolygoneLine(polygone=poly, x_mirror=0))
#Add a model
fp.append(Model(filename="Inductors.3dshapes/" + fp_name + ".wrl"))
#filename
filename = output_dir + fp_name + ".kicad_mod"
file_handler = KicadFileHandler(fp) |
file_handler.writeFile(filename)
print(fp_name)
|
jeffery9/mixprint_addons | sale/report/sale_report.py | Python | agpl-3.0 | 5,578 | 0.003227 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | lds.date('Date Order', readonly=True),
'date_confirm': fields.date('Date Confirm', readonly=True),
'year': fields.char('Year', size=4, readonly=True),
'month': fields.selection([('01', 'January'), ('02', 'February'), ('03', 'March'), ('04', 'April'),
('05', 'May'), ('06', 'June'), ('... | ber'),
('10', 'October'), ('11', 'November'), ('12', 'December')], 'Month', readonly=True),
'day': fields.char('Day', size=128, readonly=True),
'product_id': fields.many2one('product.product', 'Product', readonly=True),
'product_uom': fields.many2one('product.uom', 'Unit of Measure',... |
jamielennox/python-keystoneclient | keystoneclient/tests/v2_0/test_tokens.py | Python | apache-2.0 | 874 | 0 | # Licensed under the Apache License | , Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distri... | itations
# under the License.
import uuid
import httpretty
from keystoneclient.tests.v2_0 import utils
class TokenTests(utils.TestCase):
@httpretty.activate
def test_delete(self):
id_ = uuid.uuid4().hex
self.stub_url(httpretty.DELETE, ['tokens', id_], status=204)
self.client.toke... |
frostidaho/qtile | libqtile/widget/launchbar.py | Python | mit | 9,146 | 0.000547 | # Copyright (c) 2014 Tycho Andersen
# Copyright (c) 2014 dequis
# Copyright (c) 2014-2015 Joseph Razik
# Copyright (c) 2014 Sean Vig
# Copyright (c) 2015 reus
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
... | self.icons_files = {}
self.icons_widths = {}
self.icons_offsets = {}
# For now, ignore th | e comments but may be one day it will be useful
self.progs = dict(enumerate([{'name': prog[0], 'cmd': prog[1],
'comment': prog[2] if len(prog) > 2 else
None} for prog in progs]))
self.progs_name = set([prog['name'] for prog in s... |
avanzosc/project-addons | project_task_milestone/report/project_task_plan.py | Python | agpl-3.0 | 1,073 | 0 | # Copyright 2018 Oihane Crucelaegui - AvanzOSC
# License AGPL-3 | - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import tools
from odoo import api, fields, models
class ProjectTaskPlan(models.Model):
_name = 'project.task.plan'
_description = 'Project Task Plan'
_ | auto = False
_rec_name = 'project_id'
project_id = fields.Many2one(comodel_name='project.project')
phase_id = fields.Many2one(comodel_name='project.task.phase')
start_date = fields.Date()
end_date = fields.Date()
@api.model_cr
def init(self):
tools.drop_view_if_exists(self.env.cr, ... |
aschnell/libstorage-ng | integration-tests/filesystems/set-uuid.py | Python | gpl-2.0 | 477 | 0.002096 | #!/usr/bin/python3
# requirements: partition /dev/sdc1 with swap
from storage import *
from storageitu import *
set_logger(get_logfile_logger())
environment = E | nvironment(False)
storage | = Storage(environment)
storage.probe()
staging = storage.get_staging()
print(staging)
sdc1 = BlkDevice.find_by_name(staging, "/dev/sdc1")
blk_filesystem = sdc1.get_blk_filesystem()
blk_filesystem.set_uuid("7420b069-cd50-464e-b0b2-66c1fdc75bcd")
print(staging)
commit(storage)
|
kyvinh/home-assistant | tests/components/device_tracker/test_mqtt.py | Python | apache-2.0 | 2,571 | 0 | """The tests for the MQTT device tracker platform."""
import unittest
from unittest.mock import patch
import logging
import os
from homeassistant.bootstrap import setup_component
from homeassistant.components import device_tracker
from homeassistant.const import CONF_PLATFORM
from tests.common import (
get_test_h... | MQTT(unittest.TestCase):
"""Test MQTT device tracker platform."""
def setUp(self): # pylint: disable=invalid-name
"""Setup things to be run when tests are started."""
self.hass = get_test_home_assistant()
mock_mqtt_component(self.hass)
def tearDown(self): # pylint: disable=invali... | try:
os.remove(self.hass.config.path(device_tracker.YAML_DEVICES))
except FileNotFoundError:
pass
def test_ensure_device_tracker_platform_validation(self): \
# pylint: disable=invalid-name
"""Test if platform validation was done."""
def mock_setup_... |
mayababuji/MyCodefights | addBorder_BACKUP_4896.py | Python | apache-2.0 | 872 | 0.022936 | #!/usr/bin/env/python
# -*-coding : utf-8 -*-
<<<<<<< HEAD
'''
Given a rectangular matrix of characters, add a border of asterisks(*) to it.
For
picture = ["abc",
"ded"]
the output should be
addBorder(picture) = ["*****",
"*abc*",
"*ded*",
"**... | asterisks(* | ) to it.
"""
>>>>>>> 21f9d6ac126a25331fed7b68271620f143e23a1d
def addBorder(picture):
picture = [''.join(('*',i,'*')) for i in picture]
for item in picture:
border = '*'*len(item)
indx = [0,(len(picture)+1)]
for item in indx:
picture.insert(item,border)
return picture
if __n... |
lmazuel/azure-sdk-for-python | azure-cognitiveservices-vision-customvision/azure/cognitiveservices/vision/customvision/training/models/image_url.py | Python | mit | 774 | 0 | # 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 ... | ---------------- | -----------
from msrest.serialization import Model
class ImageUrl(Model):
"""ImageUrl.
:param url:
:type url: str
"""
_attribute_map = {
'url': {'key': 'Url', 'type': 'str'},
}
def __init__(self, url=None):
super(ImageUrl, self).__init__()
self.url = url
|
cloudspaces/interop-protocol | csinterop/csinterop/views.py | Python | gpl-2.0 | 6,787 | 0.001326 | import urllib
from django.http import HttpResponseRedirect
from django.http.response import HttpResponseBadRequest, HttpResponse
from django.shortcuts import get_object_or_404, render
from django.core.urlresolvers import reverse
from rest_framework import viewsets
from csinterop.forms import InteropServiceForm
from csi... | t.GET.get('auth_protocol_version')
if share_id is None:
return HttpResponseBadRequest('share_id is missing')
if auth_protocol is None:
return HttpResponseBadRequest('auth_protoc | ol is missing')
if auth_protocol_version is None:
return HttpResponseBadRequest('auth_protocol_version is missing')
if auth_protocol == 'oauth' and auth_protocol_version == '1.0a':
# TODO: get oauth 1.0a parameters and save them for future use
# oauth_consumer_key
# oauth_token... |
yangshun/tech-interview-handbook | experimental/utilities/python/is_subsequence.py | Python | mit | 289 | 0 | def is_subsequence(s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) > len(t):
return False
matched_s = 0
for char in t:
i | f matched_s < len(s) and s[matched_s] == char | :
matched_s += 1
return matched_s == len(s)
|
jimmylai/spoj | DIVSUM/DIVSUM.py | Python | apache-2.0 | 544 | 0 | #!/usr/bin/env python
# -*- encoding: utf8 -*-
'''Program
'''
import sys
import math
__author__ = 'noahsark'
t = int(sys.stdin.readline().strip())
output = ''
for i in xrange(t):
n = int(sys.stdin.readline().strip())
answer = 0
for | j in xrange(1, int(math.sqrt(n)) + 1):
if n % j == 0:
num = n / j
if num == j:
answer += num
else:
| answer += j
if num < n:
answer += num
output += '%d\n' % (answer)
print output
|
dsm054/pandas | pandas/tests/strings/test_split_partition.py | Python | bsd-3-clause | 21,379 | 0.001544 | from datetime import datetime
import numpy as np
import pytest
import pandas as pd
from pandas import (
DataFrame,
Index,
MultiIndex,
Series,
_testing as tm,
)
def test_split(any_string_dtype):
values = Series(["a_b_c", "c_d_e", np.nan, "f_g_h"], dtype=any_string_dtype)
result = values.... | blank_string(any_string_dtype):
# expand | blank split GH 20067
values = Series([""], name="test", dtype=any_string_dtype)
result = values.str.split(expand=True)
exp = DataFrame([[]], dtype=any_string_dtype) # NOTE: this is NOT an empty df
tm.assert_frame_equal(result, exp)
values = Series(["a b c", "a b", "", " "], name="test", dtype=any_... |
deapplegate/wtgpipeline | subarucorr.py | Python | mit | 4,836 | 0.019644 | import astropy, astropy.io.fits as pyfits, numpy, scipy, sys, re,pylab
def mypoly(a, x):
#n = n terms in fit
# float *a = poly terms,
# x; = val array
y = [1.]
t = [x]
print 'printing x'
print x
z=y[0]*t[0]
#NORMPOINT = 10000
for i in range(1,len(a)+1):
t.app... | n; i++) {
# y += a[i]*t
# t *= x
#print y
#
# y *= x
#NORMPOINT = 10000
#scale = NORMPOINT/mypoly(a, NORMPOINT)
return z
def mypoly_char(txt,x):
# here txt must be the early chip name.
params={}
params['w9c2']=[-6.85636e-05,
7.34... | -5.86075e-12,
3.40795e-16,
-5.24326e-21,
-3.25813e-25,
1.12422e-29]
params['w6c1']= [-7.02288e-05,
7.6895e-09,
-3.75244e-13,
6.88234e-18]
par... |
danielrh/repeatexec | build.py | Python | bsd-2-clause | 1,647 | 0.013965 | import os
import subprocess
import sys
import threading
try:
os.mkfifo("/tmp/shutdown",0666)
except OSError:
pass
try:
os.mkfifo("/tmp/abort",0666)
except OSError:
pass
subprocess.check_call(["go","build", "-ldflags", "-X main.FALLBACK_SHUTDOWN_PIPE /tmp/shutdown -X main.FALLBACK_ABORT_PIPE /tmp/abort -... | sys.stderr. | write(stderr.readline())
thread = threading.Thread(target=echo_stderr)
thread.setDaemon(True)
thread.start()
repeatexec = subprocess.Popen(["sudo","./repeatexec"],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=sys.stderr)
with open("example_commands.json") as example:
for line in example.readlines():
i... |
redhat-cip/edeploy | tools/grapher/models/basegraph.py | Python | apache-2.0 | 2,819 | 0.003902 | #!/usr/bin/env python
#
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com>
#
# Author: Matthieu Huin <mhu@enovance.com>
#
# 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:/... | """
import os
path = os.path.abspath(__file__)
localpath = os.path.dirname(path)
import re
def prettify_keys(string):
"""Uti | lity function used to clean keys with numerical values, so that
they can be ordered alphabetically the way they should be."""
r = re.compile("bandwidth_([0-9]{1,3})")
def replacer(match):
m = match.groups()[0]
return "bandwidth " + m
return r.sub(replacer, string)
def comp_fnc... |
SU-ECE-17-7/hotspotter | hotspotter/HotSpotterAPI.py | Python | apache-2.0 | 39,134 | 0.003859 | from __future__ import division, print_function
from hscom import __common__
(print, print_, print_on, print_off,
rrr, profile) = __common__.init(__name__, '[hs]')
import sys
# Standard
import os
from os.path import exists, join, split, relpath
from itertools import izip
imp | ort shutil
import datetime
# Science
import numpy as np
from PIL import Image
# Hotspotter
from hscom import fileio as io
from hscom import helpers
from hscom import tools
from hscom.Printable i | mport DynStruct
from hscom.Preferences import Pref
import DataStructures as ds
import Config
import chip_compute2 as cc2
import feature_compute2 as fc2
import load_data2 as ld2
import match_chips3 as mc3
import matching_functions as mf
def _checkargs_onload(hs):
'checks relevant arguments after loading tables'
... |
nearai/program_synthesis | program_synthesis/karel/scripts/split_indexed.py | Python | apache-2.0 | 1,949 | 0.000513 | import argparse
import os
import struct
import tqdm
from program_synthesis.karel.tools import indexed_file
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--input', required=True)
parser.add_argument('--num-pieces', required=True, type=int)
args = parser.parse_args... | output_file.write(chunk)
total_written += len(chunk)
piece_index = [
v - piece_start
for v in index[index_offset:index_offset + | piece_num_elems]
]
with open(piece_name + '.index', 'w') as index_file:
for v in piece_index:
index_file.write(struct.pack('<Q', v))
index_offset += piece_num_elems
|
dspelaez/dspelaez.github.io | resources/dotfiles/dot.emacs.d.own/elpa/elpy-20170214.318/elpy/compat.py | Python | mit | 673 | 0 | """Python 2/3 compatibility definitions.
These are used by the rest of Elpy to keep compatibility definitions
in one place.
"""
import sys
if sys.version_info >= | (3, 0):
PYTHON3 = True
from io import StringIO
def ensure_not_unicode(obj):
return obj
else:
PYTHON3 = False
from StringIO import StringIO # noqa
def ensure_not_unicode(obj):
"""Return obj. If it's a unicode string, convert it to str first.
Pydoc functions simply do... | ce(obj, unicode):
return obj.encode("utf-8")
else:
return obj
|
beeftornado/sentry | src/sentry/api/endpoints/project_plugins.py | Python | bsd-3-clause | 605 | 0.001653 | from __future__ import absolute_import
from rest_framework.response import Response
from sentry.plugins.base import plugins
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.serializers import serialize
from sentry.api.serializers.models.plugin import PluginSerializer
class ProjectPluginsEndpoint... | oject, ve | rsion=None)],
request.user,
PluginSerializer(project),
)
return Response(context)
|
SMTG-UCL/galore | docs/source/figures/ir_schematic.py | Python | gpl-3.0 | 840 | 0.00119 | #! /usr/bin/env python3
import os
import matplotlib.pyplot as plt
import galore
import galore.formats
import galore.plot
from tempfile import mkstemp
fd, tmp = mkstemp(suffix='.txt', text=True)
os.close(fd)
sim_xvals = [10, 15, 19.5, 20, 20.5, 21]
sim_yvals = [12, 6, 3, 2, 1, 2]
galore.formats.write_txt(sim_xvals, ... | fig.add_subplot(1, 2, 1)
for x, y in zip(sim_xvals, sim_yvals):
ax1.plot([x, x], [0, y], 'k-')
ax1.set_xticklabels([])
ax1.set_yticklabels([])
ax1.set_title("Ideal peaks")
x, y = galore.process_1d_data(input=tmp, gaussian=2)
ax2 = fig.add_subplot(1, 2, 2, sharey=ax1)
ax2.plot(x, y, 'k-')
ax2.set_ylim((0, None))
... | ls([])
ax2.set_title("With broadening")
fig.savefig('docs/source/figures/ir_schematic.pdf')
|
rolando/scrapy-slidebot | slidebot/pipelines.py | Python | mit | 2,428 | 0 | import re
import subprocess
import weakref
from scrapy.contrib.pipeline.files import FilesPipeline
from scrapy.exceptions import DropItem
from scrapy.utils.httpobj import urlparse_cached
from twisted.internet import threads
class SlideDefaults(object):
"""Set up defaults items."""
def process_item(self, ite... | ImageMagick.
cmd = ['convert'] + image_files + [dest]
try:
# TODO: capture errors
subprocess.check_call(cmd, stdout=subprocess.PIPE)
except subprocess.CalledProcessError:
raise DropItem("failed to generate PDF")
retu | rn item
|
jeremiah-c-leary/vhdl-style-guide | vsg/token/interface_unknown_declaration.py | Python | gpl-3.0 | 1,016 | 0 |
from vsg import parser
class identifier(parser.identifier):
'''
unique_id = interface_unknown_declaration : identifier
'''
def __init__(self, sString):
parser.identifier.__init__(self, sString)
class colon(parser.colon):
'''
unique_id = interface_unknown_declaration : colon
'''... | String=':'):
parser.colon.__init__(self)
class subtype_indication(parser.subtype_indication):
'''
unique_id = interface_unknown_declaration : subtype_indication
'''
def __init__(self, sString):
parser.subtype_indication.__init__(self, sString)
class bus_keyword(parser.keyword):
| '''
unique_id = interface_unknown_declaration : bus_keyword
'''
def __init__(self, sString):
parser.keyword.__init__(self, sString)
class assignment(parser.assignment):
'''
unique_id = interface_unknown_declaration : assignment
'''
def __init__(self, sString):
parser.as... |
stuartarchibald/numba | numba/tests/test_target_extension.py | Python | bsd-2-clause | 27,864 | 0.000323 | """This tests the target extension API to ensure that rudimentary expected
behaviours are present and correct. It uses a piece of fake hardware as a
target, the Dummy Processing Unit (DPU), to do this. The DPU borrows a lot from
the CPU but is part of the GPU class of target. The DPU target has deliberately
strange imp... | lerBase, DefaultPassBuilder
from numba.core.compiler_machinery import FunctionPass, register_pass
from numba.core.typed_passes import PreLowerStripPhis
# Define a new target, this target extends GPU, this places the DPU in the
# target hierarchy as a type of GPU.
class DPU(GPU):
...
# register the dpu target h... | try["dpu"] = DPU
# Create a JIT DPU codegen for the DPU target
class JITDPUCodegen(CPUCodegen):
# This largely rips off the CPU for ease
_library_class = JITCodeLibrary
def _customize_tm_options(self, options):
# Customize the target machine options.
options["cpu"] = self._get_host_cpu_... |
cvegaj/ElectriCERT | venv3/lib/python3.6/site-packages/mock/tests/testcallable.py | Python | gpl-3.0 | 4,431 | 0.002708 | # Copyright (C) 2007-2012 Michael Foord & the mock team
# E-mail: fuzzyman AT voidspace DOT org DOT uk
# http://www.voidspace.org.uk/python/mock/
import unittest2 as unittest
from mock.tests.support import is_instance, X, SomeClass
from mock import (
Mock, MagicMock, NonCallableMagicMock,
NonCallableMock, pat... | result.foo(3, 2, 1)
result.foo.assert_called_once_with(3, 2, 1)
def test_create_autospec(self):
mock = create_autospec(X)
instance = mock()
self.assertRaises(TypeError, instance)
| mock = create_autospec(X())
self.assertRaises(TypeError, mock)
def test_create_autospec_instance(self):
mock = create_autospec(SomeClass, instance=True)
self.assertRaises(TypeError, mock)
mock.wibble()
mock.wibble.assert_called_once_with()
self.assertRaises(T... |
0u812/matplotlib2tikz | test/acidtest.py | Python | lgpl-3.0 | 6,448 | 0.000931 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010--2014 Nico Schlömer
#
# This file is part of matplotlib2tikz.
#
# matplotlib2tikz 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.
#
# matplotlib2tikz is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRA... | # You should have received a copy of the GNU General Public License along with
# matplotlib2tikz. If not, see <http://www.gnu.org/licenses/>.
#
from os import path
from matplotlib import pyplot as pp
import matplotlib2tikz
import testfunctions
# XXX: There seems to be an issue with the legends that do not appear in t... |
sony/nnabla | python/test/function/test_random_flip.py | Python | apache-2.0 | 3,044 | 0.000329 | # Copyright 2017,2018,2019,2020,2021 Sony Corporation.
# Copyright 2021 Sony Group Corporation.
#
# 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-... | parametrize("axes", [None, (1,), (2,), (-1,), (-2,)])
def test_random_flip_forward_backward(seed, axes, ctx, func_name):
from nbla_test_utils import cap_ignore_region, function_tester
rng = np.random.RandomState(seed)
inputs = [rng.randn(2, 3, 4).astype(np.float32)]
i = nn.Variable(inputs[0].shape, need... | , seed)
flip_close = np.allclose(o.d, ref_flip(inputs[0], axes))
assert flip_close or (not flip_close and np.allclose(o.d, i.d))
assert o.parent.name == func_name
# NNabla backward
orig_grad = rng.randn(*i.shape).astype(i.data.dtype)
i.g[...] = orig_grad
o_grad = rng.randn(*i.shape).astype(... |
fernandezcuesta/ansible | lib/ansible/modules/network/junos/junos_netconf.py | Python | gpl-3.0 | 6,106 | 0.00131 | #!/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... | port %s' % want['netconf_port']
)
elif want['state'] == 'absent' and have['state'] == 'pres | ent':
commands.append('delete system services netconf')
elif want['state'] == 'present':
if want['netconf_port'] != have.get('netconf_port'):
commands.append(
'set system services netconf ssh port %s' % want['netconf_port']
)
return commands
def parse_... |
garethr/django-test-extensions | src/test_extensions/testrunners/xmloutput.py | Python | mit | 5,341 | 0.004494 | import time, traceback, string
from xmlunit.unittest import _WritelnDecorator, XmlTextTestRunner as his_XmlTextTestRunner
from django.test.simple import *
from xml.sax.saxutils import escape
try:
# The django.utils.unittest alias is available in Django >= 1.3
from django.utils import unittest
except ImportEr... | for l in line.split("\n")[:-1]:
self._errorsAndFailures += escape(l)
self._errorsAndFailures += "</error>"
def addFailure(self, test, err):
unittest.TestResult.addFailure(self, test, err)
if err[0] is KeyboardInterrupt:
self.shouldStop = 1
self._lastWa... | failure type="%s">' % err[0].__name__
for line in apply(traceback.format_exception, err):
for l in line.split("\n")[:-1]:
self._errorsAndFailures += escape(l)
self._errorsAndFailures += "</failure>"
def printErrors(self):
pass #assert False
def printErrorList(s... |
ANR-COMPASS/shesha | data/par/par4tests/test_custom_dm_diam_dm_proj.py | Python | gpl-3.0 | 2,303 | 0 | import shesha.config as conf
simul_name = "bench_scao_sh_16x16_8pix"
layout = "layoutDeFab_SH"
# loop
p_loop = conf.Param_loop()
p_loop.set_niter(1000)
p_loop.set_ittime(0.002) # =1/500
# geom
p_geom = conf.Param_geom()
p_geom.set_zenithangle(0.)
# tel
p_tel = conf.Param_tel()
p_tel.set_diam(4.0)
p_tel.set_cobs... | ers = [p_centroider0]
p_centroider0.set_nwfs(0)
p_centroider0.set_type("cog")
# p_centroider0.set_typ | e("corr")
# p_centroider0.set_type_fct("model")
# controllers
p_controller0 = conf.Param_controller()
p_controllers = [p_controller0]
p_controller0.set_type("ls")
p_controller0.set_nwfs([0])
p_controller0.set_ndm([0, 1])
p_controller0.set_maxcond(1500.)
p_controller0.set_delay(1.)
p_controller0.set_gain(0.4)
p_contr... |
jkimbo/freight | freight/tasks/execute_task.py | Python | apache-2.0 | 7,033 | 0.000995 | from __future__ import absolute_import, unicode_literals
import logging
import sys
from datetime import datetime
from flask import current_app
from subprocess import PIPE, Popen, STDOUT
from threading import Thread
from time import sleep, time
from freight import notifiers
from freight.notifiers import NotifierEvent... | e
def save_chunk(self, text):
# we also want to pipe this to stdout
sys.stdout.write(text)
text_len = len(text)
db.session.add(LogChunk(
| task_id=self.task_id,
text=text,
offset=self.cur_offset,
size=text_len,
))
# we commit immediately to ensure the API can stream logs
db.session.commit()
self.cur_offset += text_len
def terminate(self):
self.active = False
de... |
guyrt/teaching | 2017/Com597I/babynames/week4_solution.py | Python | mit | 438 | 0 | import ssadata
hist = {}
for key in | ssadata.boys:
first_letter = key[0]
value = ssadata.boys[key]
if first_letter not in hist:
hist[first_letter] = 0
hist[first_letter] = hist[first_letter] + value
for key in ssadata.girls:
first_letter = key[0]
value = ssadata.girls[key]
| if first_letter not in hist:
hist[first_letter] = 0
hist[first_letter] = hist[first_letter] + value
print(hist)
|
dholm/voidwalker | voidwalker/backends/test/target.py | Python | gpl-3.0 | 2,273 | 0 | # (void)walker unit test backend
# Copyright (C) 2012 David Holm <dholmster@gmail.com>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any... | def name(self):
return ('thread %d' % self._thread_id)
def id(self):
return self._thread_id
def is_valid(self):
return True
class TestThreadFactory(ThreadFactory):
def create_thread(self, inferior, thread_id):
thread = TestThr | ead(inferior, thread_id)
inferior.add_thread(thread)
return thread
|
iancze/Starfish | Starfish/grid_tools/utils.py | Python | bsd-3-clause | 10,682 | 0.002528 | import os
import logging
import tqdm
from urllib.request import urlretrieve, URLError
import multiprocessing as mp
import itertools
import numpy as np
log = logging.getLogger(__name__)
def download_PHOENIX_models(path, ranges=None, parameters=None):
"""
Download the PHOENIX grid models from the Goettingen ... | and np.all(p <= max_params):
params.append(p)
pbar = tqdm.tqdm(params)
for p in pbar:
# Skip irregularities from grid
try:
grid.check_params(p)
except ValueError:
continue
tmp_p = [p[0], p[1]]
# Create the Z string. Have to do this b... | sign for 0.0
Zstr = "-0.0" if p[2] == 0 else "{:+.1f}".format(p[2])
tmp_p.append(Zstr)
# Create the Alpha string, which is nothing if alpha is 0 or unspecified
if len(p) == 4:
Astr = "" if p[3] == 0 else ".Alpha={:+.2f}".format(p[3])
else:
Astr = ""
... |
sevgo/Programming101 | week1/warmups/count_consonants.py | Python | bsd-3-clause | 468 | 0.002137 | #! | /usr/bin/env python3
def count_consonants(string):
""" Function which returns the count of
all consonants in the string \"string\" """
consonants = "bcdfghjklmnpqrstvwxz"
counter = 0
if | string:
for ch in string.lower():
if ch in consonants:
counter += 1
return counter
if __name__ == "__main__":
strng = "MOnty PYthon!"
print ("%s contains %d consonants" % (strng, count_consonants(strng)))
|
thauser/pnc-cli | pnc_cli/swagger_client/models/bpm_task_page.py | Python | apache-2.0 | 4,612 | 0 | # coding: utf-8
"""
Copyright 2015 SmartBear Software |
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 WAR... |
asrashley/ieee-802-11-timeline | report/models.py | Python | apache-2.0 | 3,172 | 0.010088 | #############################################################################
#
# 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/licen | ses/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
# l... |
cernops/keystone | keystone/common/context.py | Python | apache-2.0 | 2,088 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | (name):
return property(lambda x: getattr(x, name),
lambda x, y: setattr(x, name, y))
class RequestContext(oslo_context.RequestContext):
def __init__(self, **kwargs):
self.project_name = kwargs.pop('project_name', None)
self.domain_name = kwargs.pop('domain_name', None)
... | self.user_domain_name = kwargs.pop('user_domain_name', None)
self.project_domain_name = kwargs.pop('project_domain_name', None)
self.is_delegated_auth = kwargs.pop('is_delegated_auth', False)
self.trust_id = kwargs.pop('trust_id', None)
self.trustor_id = kwargs.pop('trustor_id', ... |
mari-linhares/tensorflow-workshop | code_samples/RNN/sentiment_analysis/samples/canned_sentiment_analysis.py | Python | apache-2.0 | 4,929 | 0.004058 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
from input_functions import get_input_fn
import tensorflow as tf
from tensorflow.contrib.keras.python.keras.datasets import imdb
from tensorflow.contrib.learn.python.learn import learn_runner
f... | eval_input_fn=test_input,
)
return _experiment_fn
def main(unused_argv):
# Loading the data
# data from: https://keras.io/datasets/
# Dataset of 25,000 movies reviews from IMDB, labeled by sentiment
# (positive/negative).
# Reviews have been preprocessed, and each review is encoded as a sequence
... | words are indexed by overall frequency in the dataset.
print('Loading data...')
(x_train, y_train), (x_test, y_test) = imdb.load_data(
num_words=FLAGS.num_words)
print('size of the train dataset:', x_train.shape[0])
print('size of the test dataset:', x_test.shape[0])
# run experiment
run_config = ... |
istinspring/grab | tests/grab_xml_processing.py | Python | mit | 1,247 | 0 | # coding: utf-8
from tests.util import build_grab
from tests.util import BaseGrabTestCase
class | GrabXMLProcessingTestCase(BaseGrabTestCase):
def setUp(self):
self.server.reset()
def test_xml_with_declaration(self):
s | elf.server.response['get.data'] =\
b'<?xml version="1.0" encoding="UTF-8"?>'\
b'<root><foo>foo</foo></root>'
grab = build_grab()
grab.go(self.server.get_url())
self.assertTrue(grab.doc.select('//foo').text() == 'foo')
def test_declaration_bug(self):
"""
... |
yosi-dediashvili/nth_combination | nth_combination.py | Python | gpl-2.0 | 2,156 | 0.004174 | def nth_combination(start_combination, combination_options, n_value):
"""
Calculate the N-th combination of a string. The function does not evaluate
n combination before outputing the n combination. The function acts upon
the combination as a "natural number" with radix equals to the number of
comb... | st be within the combination_options space.
combination_options is the range from which the combination is constructed.
n_value is the combination index relative to the start_combination value.
The output of the function is the nth_combination. The combination string
length is identical to the lengt... | tore the result.
remainder_temp = remainder = n_value
# For each char.
for i in range(len(start_combination)):
c_i = start_combination[i]
c_idx = combination_options.find(c_i)
remainder_temp = (c_idx + remainder) / radix
n_idx = (c_idx + remainder) % radix
remainder =... |
sminteractive/ndb-gae-admin | smadmin/__init__.py | Python | apache-2.0 | 282 | 0 | fr | om core.adminmodel import *
from core.adminsearch import *
from core.decorators import *
from core import errors
from core.list_filter import *
from core.list_search import *
fro | m core.request_handlers import *
from core.app import *
from core import html
__version__ = '1.0.0'
|
ajdeziel/quiz-evaluator | quiz_pass_ratio.py | Python | gpl-3.0 | 1,673 | 0.028093 | import libxml2
import sys
import quiz_library
'''
purpose
Accept 1 or more log file names on the command line.
Accumulate across all the log files the pass ratio for each question.
A question result is considered a pass if it is not 0 or None
and fail otherwise.
The pass ratio for a question is the number of p... | ):
correct_answers += 1 #Increment when correct answer is found
pass_ratio = correct_answers / target
list_marks.append(pass_ratio)
question_total += 1 #Increment total questions visited
'''
The following lines prints list_marks in CSV format
with a special condition for its first element
'''
output = '' + s... | ]:
output = output + ',' + str(i)
print output
|
gunnarbeutner/sbncng | src/plugins/admincmd.py | Python | gpl-2.0 | 8,968 | 0.009701 | # sbncng - an object-oriented framework for IRC
# Copyright (C) 2011 Gunnar Beutner
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any l... | ui_svc.send_sbnc_reply(subclientobj, 'Global message: %s' % (message), notice=False)
def _cmd_broadcast_handler(self, clientobj, params, notice):
if len(params) < 1:
ui_svc.send_sbnc_reply(clientobj, 'Syntax: broadcast <tex | t>', notice)
return
self.broadcast(' '.join(params))
ui_svc.send_sbnc_reply(clientobj, 'Done.', notice)
pass
def _cmd_deluser_handler(self, clientobj, params, notice):
if len(params) < 1:
ui_svc.send_sbnc_reply(client... |
007gzs/django_restframework_apiview | example/example_app/models.py | Python | lgpl-3.0 | 925 | 0.003308 | # encoding: utf-8
from __future__ import absolute_import, unicode_literals
from apiview.model import AbstractUserMixin, BaseModel
from django. | contrib.auth.base_user import AbstractBaseUser
from django.db import models
class User(AbstractUserMixin, BaseModel, AbstractBaseUser):
is_staff = False
def get_short_name(self):
return self.name
| def get_full_name(self):
return self.nickname
USERNAME_FIELD = 'username'
username = models.CharField('用户名', unique=True, max_length=64, editable=False, null=False, blank=False)
password = models.CharField('密码', max_length=128, unique=True, editable=False, null=False, blank=True)
nickname =... |
mapbased/vitess | test/base_sharding.py | Python | bsd-3-clause | 16,306 | 0.003925 | #!/usr/bin/env python
#
# Copyright 2013, Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
"""This module contains a base class and utility functions for sharding tests.
"""
import struct
import logging
from vtdb import keyrange_c... | 'values(%d, %d, "%s", 0x%x) /* vtgate:: keyspace_id:%s */ '
'/* id:%d */' %
(table, fixed_parent_id, mid, msg, keyspace_id, k, mid),
'commit'],
write=True)
def _get_value(self, tablet_obj, table, mid):
"""Returns the row(s) from the table for the provided id, using MySQL... | A tuple of results.
"""
return tablet_obj.mquery(
'vt_test_keyspace',
'select parent_id, id, msg, custom_ksid_col from %s '
'where parent_id=%d and id=%d' %
(table, fixed_parent_id, mid))
def _check_value(self, tablet_obj, table, mid, msg, keyspace_id,
s... |
liam2/liam2 | liam2/config.py | Python | gpl-3.0 | 585 | 0 | # encoding: utf-8
from __future__ import absolute_import, division, print_function
import os
# TODO: most of these (except possibly input_dire | ctory) should be moved to
# Simulation attributes (or in the context)
debug = os.environ.get("DEBUG", "False").lower() == "true"
input_directory = "."
output_directory = "."
skip_shows = False
# should be one of raise, warn, skip
assertions = "raise"
show_timings = True
# should be one of periods, functions, p... | e
autodump_file = None
autodiff = None
|
googleads/google-ads-python | google/ads/googleads/v10/services/services/keyword_plan_service/transports/__init__.py | Python | apache-2.0 | 1,049 | 0 | # -*- coding: utf-8 -*-
# Copyright 20 | 20 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/ | licenses/LICENSE-2.0
#
# Unless required by applicable law or 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 ... |
mallipeddi/django-taskforce | utils.py | Python | bsd-3-clause | 381 | 0.007874 | from | django.conf import settings
def get_server_loc():
if hasattr(settings, 'TASKFORCE_SERVER'):
address, port = settings.TASKFORCE_SERVER.split(':')
port = int(port)
else:
address = '127.0.0.1'
port = 9000
return address, port
def get_server_base_uri():
address, port = get... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.