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
lidingpku/open-conference-data
iswc-metadata/src/mu/lib_entity.py
Python
mit
3,860
0.013472
""" syntax entity ::= {id(utc millisecond), type, id_from, id_to, status, data, source, note} data example1: search wikipedia { "id":1378327851001, "type":"name-name", "id-from":"MIT", "id-to":"Massachusetts Institute of Technology", "status":"auto", "date":"2013-09-04", "source":"wikipedia...
new_data(self, filemode="w"): headers = DbpediaApi.LIST_HEADER print "{0} new mapping entries added ".format(len(self.list_new_entity)) #start the new data file, to be merged to original data with open (self.config["fn_new"],filemode) as f: c
svwriter = UnicodeWriter(f) for entry in self.list_new_entity: row = UtilString.json2list(entry, headers) csvwriter.writerow(row)
Arno-Nymous/pyload
module/plugins/accounts/ExashareCom.py
Python
gpl-3.0
388
0
# -*- coding: utf-8 -*- from ..internal.XFSAccount import XFSAccount class ExashareCom(XFSAccount): __name__ = "ExashareCom" __type__ = "account" __version__ = "0.06" __status__ = "testing" __description__ = """Exashare.co
m account plugin""" __license__ = "GPLv3" __authors__ = [("Walter Purcaro", "vuolter@gmail.com")] PLUGIN_DOMAIN = "exashare.com"
nmc-probe/emulab-nome
protogeni/test/version1/binduser.py
Python
agpl-3.0
1,946
0.007194
#! /usr/bin/env python # # Copyright (c) 2008-2009 University of Utah and the Flux Group. # # {{{GENIPUBLIC-LICENSE # # GENI Public License # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this softw
are and/or hardware specification (the "Work") to # deal in the Work without restriction,
including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Work, and to permit persons to whom the Work # is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be # included i...
pombredanne/blivet-1
tests/udev_test.py
Python
gpl-2.0
5,747
0.003828
#!/usr/bin/python import unittest import mock import os class UdevTest(unittest.TestCase): def setUp(self): import blivet.udev blivet.udev.os = mock.Mock() blivet.udev.log = mock.Mock() def test_udev_enumerate_devices(self): import blivet.udev ENUMERATE_LIST = [ ...
/devices/virtual/block/ram0', '/sys/devices/virtual/block/ram1', '/sys/devices/virtual/block/dm-0', ] blivet.udev.global_udev.enumerate_devices = mock.Mock(return_value=ENUMERATE_LIST) ret = blivet.udev.udev_enumerate_devices() self.assertEqual(set(ret), ...
es/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda', '/devices/virtual/block/loop0', '/devices/virtual/block/loop1', '/devices/virtual/block/ram0', '/devices/virtual/block/ram1', '/devices/virtual/block/dm-0']) ) def test_udev_get_device_1(self): impo...
mapnik/mapnik
scons/scons-local-4.1.0/SCons/Tool/aixc++.py
Python
lgpl-2.1
1,578
0.000634
"""SCons.Tool.aixc++ Tool-specific initialization for IBM xlC / Visual Age C++ compiler. There nor
mally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # __COPYRIGHT__ # # 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 copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The ab...
Guillaume-Docquier/Thingy
review/apps.py
Python
mit
128
0
from __f
uture__ import unicode_literals from django.apps import AppConfig class ReviewConfig(AppConfig): name =
'review'
bhell/jimi
jimi/jimi/price/models/discount.py
Python
bsd-3-clause
478
0.004184
# Possible discounts: # - Node (ad
minister inline with nodes) # - Bulk amounts on nodes # - User # - Group of users # - Order (this is more-or-less a voucher) # - Shipping costs # Possible amounts: # - Percentage # - Fixed amount # Flag indicating if a discount can be combined with other discounts. # Boolean "offer" to include in list
of offers. Default to true if discount is at node level. # Save all applied discounts when ordering in a ManyToMany relationship with Order.
carthagecollege/django-djsani
djsani/emergency/urls.py
Python
bsd-3-clause
340
0
# -*- coding: utf-8 -*- """URLs for all views."""
from django.urls import path from djmaidez.contact import views urlpatterns = [ path('form/', views.form, name='form'), path('populate/',
views.populate, name='populate'), path('save/', views.save, name='save'), path('test/', views.test, name='test'), ]
AutorestCI/azure-sdk-for-python
azure-mgmt-devtestlabs/azure/mgmt/devtestlabs/models/generate_arm_template_request.py
Python
mit
1,873
0.000534
# 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 ...
The location of the virtual machine. :type location: str :param file_upload_options: Options for uploading the files for the artifact. UploadFilesAndGenerateSasTokens is the default value. Possible values include: 'UploadFilesAndGenerateSasTokens', 'None' :type file_upload_options: str or ~az...
'virtual_machine_name': {'key': 'virtualMachineName', 'type': 'str'}, 'parameters': {'key': 'parameters', 'type': '[ParameterInfo]'}, 'location': {'key': 'location', 'type': 'str'}, 'file_upload_options': {'key': 'fileUploadOptions', 'type': 'str'}, } def __init__(self, virtual_mac...
mikeseven/pyvision
src/pyvision/ml/opencv_ml.py
Python
bsd-3-clause
5,238
0.027682
''' This module includes some helper functions for training OpenCV's machine learning algorithms. Created on Mar 25, 2013 @author: David S. Bolme Oak Ridge National Laboratory ''' import pyvision as pv import cv2 import numpy as np import tempfile import shutil import os class Stat
sModelWrapper(object): ''' This class wraps an opencv stats model to support pickling and other pythonic features, etc. ''' def __init__(self,model): ''' Init the wrapper with the model. ''' self.model = model def predict(self,*args,**kwarg): ...
,*args,**kwarg): ''' Wrapper for the predict function. ''' return self.model.predict_prob(*args,**kwarg) def predict_all(self,*args,**kwarg): ''' Wrapper for the predict function. ''' return self.model.predict_all(*args,**kwarg) d...
PyPSA/PyPSA
test/test_lpf_against_pypower.py
Python
mit
2,335
0.017987
import pypsa #NB: this test doesn't work for other cases because transformer tap #ratio and phase angle not supported for lpf from pypower.api import ppoption, runpf, case30 as case from pypower.ppver import ppver from distutils.version import StrictVersion pypower_version = StrictVersion(ppver()['Version']) import...
"] = True #ppc is a dictionary with details about the network, including baseMVA, branches and generators ppc = case() results,success = runpf(ppc, ppopt) #store results in a DataFrame for easy access results_df = {} #branches columns = 'bus0, bus1, r, x, b, rateA, rateB, rateC, ratio, a...
q0, p1, q1'.split(", ") results_df['branch'] = pd.DataFrame(data=results["branch"],columns=columns) #buses columns = ["bus","type","Pd","Qd","Gs","Bs","area","v_mag_pu_set","v_ang_set","v_nom","zone","Vmax","Vmin"] results_df['bus'] = pd.DataFrame(data=results["bus"],columns=columns,index=results["bus...
ofer43211/unisubs
apps/teams/tests/teamstestsutils.py
Python
agpl-3.0
425
0.007059
from __future__ import absolute_import from django.core.management import call_command from teams.models import Team, TeamMember, Workflow from widget.rpc import Rpc def refresh_obj(m): return m.__class__._default_manager.get(pk=m.pk) def reset_solr(): # cause the default site to load from hays
tack import backend sb = backend.SearchBackend() sb.clear() ca
ll_command('update_index') rpc = Rpc()
pnwairfire/blueskyutils
blueskyutils/bsf2wrfchem/fccs2genveg.py
Python
gpl-3.0
4,872
0.000205
FCCS2GENVEG = { "0": "9", "282": "6", "286": "6", "448": "4", "270": "4", "454": "4", "309": "2", "81": "1", "422": "2", "453": "1", "2": "6", "427": "4", "164": "6", "436": "1", "186": "4", "426": "4", "231": "4", "85": "6", "241": "6", "4...
268": "4", "58": "2", "91": "6", "124": "4", "100": "1", "52": "4", "273": "6", "320": "4", "304": "4", "36": "2", "404": "4", "318": "1", "418": "2", "47": "4", "401": "2", "70": "6", "233": "2", "203": "1", "157": "4", "440": "4", "1
80": "4", "218": "2", "78": "2", "228": "6", "168": "2", "110": "4", "214": "6", "337": "1", "213": "1", "437": "1", "262": "1", "323": "2", "29": "6", "67": "6", "63": "1", "428": "4", "445": "1", "274": "4", "455": "6", "216": "4", "239":...
chippey/gaffer
python/GafferCortexUI/PresetsOnlyParameterValueWidget.py
Python
bsd-3-clause
3,961
0.027771
########################################################################## # # Copyright (c) 2011-2015, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redi...
NY EXPRESS OR IMPLIED WARRANTIES, 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 (...
AUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## from __fu...
cmptrgeekken/evething
thing/models/apikeyfailure.py
Python
bsd-2-clause
1,916
0.005741
# ------------------------------------------------------------------------------ # Copyr
ight (c) 2010-2013, EVEthing team # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, this # list of conditions and...
llowing disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PAR...
tardyp/buildbot
master/buildbot/steps/shell.py
Python
gpl-2.0
22,571
0.00062
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
ram;
if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import re from twisted.internet import defer from twisted.python.deprecate import deprecatedModuleAttribute from twisted.python.versions import Version from buildbot...
maniteja123/sympy
sympy/simplify/simplify.py
Python
bsd-3-clause
40,613
0.000739
from __future__ import print_function, division from collections import defaultdict from sympy.core import (Basic, S, Add, Mul, Pow, Symbol, sympify, expand, expand_mul, expand_func, Function, Dummy, Expr, factor_terms, FunctionClass, symbols, expand_power_exp) from sympy.core.compatibility import (iterab...
ummy(s.name, positive=True)) for s in eq.free_symbols if s
.is_positive is None]) eq = eq.subs(reps) return eq, dict([(r, s) for s, r in reps.items()]) def hypersimp
ddico/account-financial-tools
account_partner_required/models/__init__.py
Python
agpl-3.0
23
0
from
. import accoun
t
belangeo/pyo
pyo/examples/synthesis/05_ring_mod_class.py
Python
lgpl-3.0
980
0.004082
#!/usr/bin/env python # encoding: utf-8 """ Ring modulators used as exciter of a waveguide bank. """ from pyo import * import random s = Server().boot() tab_m = HarmTable([1, 0, 0, 0, 0, 0.3, 0, 0, 0, 0, 0, 0.2, 0, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 0.05]).normalize() tab_p = HarmTable([1, 0, 0.33, 0, 0.2
, 0, 0.143, 0, 0.111]) class Ring: def __init__(self, fport=250, fmod=100, amp=0.3): self.mod = Osc(tab_m, freq=fmod, mul=amp) self.port = Osc(
tab_p, freq=fport, mul=self.mod) def out(self): self.port.out() return self def sig(self): return self.port lf = Sine(0.03, mul=0.5, add=1) rg = Ring( fport=[random.choice([62.5, 125, 187.5, 250]) * random.uniform(0.99, 1.01) for i in range(8)], fmod=lf * [random.choice([25, ...
sirMackk/wintersun
wintersun/exceptions.py
Python
gpl-3.0
391
0
class WintersunException(Exception): """General Wintersun exception""" class IncompletePost(WintersunException): """Post is missing data""" class PostRepoException(WintersunException): """Error with Post Repository""" class NotFound(PostRepoException): """Post not found in Repository""" class Du...
theonion/django-bulbs
tests/special_coverage/test_spec_cov_commands.py
Python
mit
2,296
0
from django.core.management import call_command from django.test.utils import override_settings from bulbs.special_coverage.models import SpecialCoverage from bulbs.utils.methods import today_as_utc_datetime from bulbs.utils.test import
BaseIndexableTestCase class SpecialCoverageCommandTests(BaseIndexableTestCase): def setUp(self): super(SpecialCoverageCommandTests, self).setUp() for i in range(50): SpecialCoverage.objects.create(name="sc{}".format(i), active=True) SpecialC
overage.objects.create(name="inactive-sc{}".format(i)) def test_active_migration_success(self): call_command("migrate_active_to_published") start_qs = SpecialCoverage.objects.filter(start_date__isnull=False) self.assertEqual(start_qs.count(), 50) for sc in start_qs.all(): ...
Bionetbook/bionetbook
bnbapp/schedule/migrations/0003_auto__add_field_calendar_slug.py
Python
mit
4,571
0.008313
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Calendar.slug' db.add_column('schedule_calendar', 'slug', self.gf('dja...
l', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField',...
calendar': { 'Meta': {'ordering': "('-modified', '-created')", 'object_name': 'Calendar'}, 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'data': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}), ...
sghai/robottelo
robottelo/ui/computeresource.py
Python
gpl-3.0
25,187
0.00004
# -*- encoding: utf-8 -*- from robottelo.constants import FILTER, FOREMAN_PROVIDERS from nailgun import entities from robottelo.ui.base import Base, UINoSuchElementError, UIError from robottelo.ui.locators import common_locators, locators, tab_locators from robottelo.ui.navigator import Navigator class ResourceProfil...
ds in UI"""
# if template is the fields to set, it set in priority as, when # selecting a template, configuration data is loaded in UI template_key = 'template' template = kwargs.get(template_key) if template is not None: self.set_value(tem
otsaloma/gaupol
aeidon/revertable.py
Python
gpl-3.0
3,249
0
# -*- coding: utf-8 -*- # Copyright (C) 2005 Osmo Salomaa # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This pr...
Call the reversion function.""" kwargs = self.revert_kwargs.copy() kwargs["register"] = self._get_reversion_register() return self.revert_function(*self.revert_args, **kwargs) class RevertableActionGroup: """
Group of :class:`RevertableAction`. :ivar actions: Sequence of :class:`RevertableAction` in group :ivar description: Short one line description """ def __init__(self, **kwargs): """ Initialize a :class:`RevertableAction` instance. `kwargs` can contain any of the names of publi...
erikdejonge/newsrivr
daemons/get-tweets-rest.py
Python
gpl-2.0
2,792
0.019341
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from builtins import dict from builtins import int from future import standard_library standard_library.install_aliases() from builtins import str #!/usr/bin/env python im...
eturn False def parseDatetime(string): return parse(string) def main(): for user in g
etCollUsers().find(): if "access_token" in user and "twitter_credentials" in user: #if user["screen_name"]=="rabshakeh": print(user["screen_name"]) access_token = dict(urllib.parse.parse_qsl(user["access_token"])) twitter = OAuthApi(consumer_key, consumer_secret, ...
oicr-ibc/riser
bin/make_transcripts.py
Python
gpl-3.0
1,956
0.018916
#!/usr/bin/python from __future__ import division import re, sys from Bio import SeqIO from Bio.SeqRecord import SeqRecord import itertools from utils_make_txs import * import random from random import randint random.seed(1234) dir_in = sys.argv[1] mutations = [int(x) for x in sys.argv[2].split(",")] transcripts_i...
t '1. Reading the transcript file' genecnt = 0 for line in f:
genecnt+=1 a = line.split('\t') lst = a[9].split(',') starts[a[0]] = [int(x) for x in lst] lst = a[10].rstrip('\n').split(',') ends[a[0]] = [int(x) for x in lst] exonnmb = len(starts[a[0]]) gene_name[a[0]] = a[1] gene_id[genecnt] = a[0] strand[a[0]] = a[3] if genecnt == 1:...
davidfraser/python-datetime-tz
datetime_tz/detect_windows.py
Python
apache-2.0
3,815
0.009174
# -*- coding: utf-8 -*- # vim: set ts=2 sw=2 et sts=2 ai: # # Copyright 2014 David M # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Un...
ucture): """ctypes structure for SYSTEMTIME.""" # pylint: disable=too-few-public-methods _fiel
ds_ = [ ("year", ctypes.c_ushort), ("month", ctypes.c_ushort), ("day_of_week", ctypes.c_ushort), ("day", ctypes.c_ushort), ("hour", ctypes.c_ushort), ("minute", ctypes.c_ushort), ("second", ctypes.c_ushort), ("millisecond", ctypes.c_ushort), ] class TZI_c(ctypes.Struc...
phase4ground/DVB-receiver
modem/python/library/generic_modulator.py
Python
gpl-3.0
36,780
0.051713
import numpy as np import fir_filter import gauss_pulse import comms_filters class generic_modulator: def __init__(self, modulation_type, samples_per_symbol, pulse_factor, pulse_length, config): """ Create the generic modulator object and specify the modulation parameters. Supported modulation types ar...
op through each sample modulate the in-phase arm for n in range(number_of_bits): i_da
ta[n*self.samples_per_symbol] = 2*data[n]-1 # the quadrature arm is all zeros q_data = np.zeros(number_of_samples) # essentially OQPSK with half the frequency elif self.modulation_type == "GMSK": # determine the number of samples number_of_bits = len(data) number_of_samples = number_of...
mythmon/kitsune
kitsune/groups/admin.py
Python
bsd-3-clause
212
0.004717
from django.contrib import admin from kitsune.groups.models import GroupP
rofile class GroupProfileAdmin(admin.ModelAdmin): raw_
id_fields = ['leaders'] admin.site.register(GroupProfile, GroupProfileAdmin)
jeeftor/alfredToday
src/lib/googleapiclient/discovery.py
Python
mit
41,531
0.006718
# Copyright 2014 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 ...
salpha(): result.append('x') for c in key: if c.isalnum(): resu
lt.append(c) else: result.append('_') return ''.join(result) @positional(2) def build(serviceName, version, http=None, discoveryServiceUrl=DISCOVERY_URI, developerKey=None, model=None, requestBuilder=HttpRequest, credentials=None, ...
aljim/deploymentmanager-samples
community/cloud-foundation/templates/pubsub/pubsub.py
Python
apache-2.0
3,261
0.00276
# 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...
ion, spec) return subscription def create_iam_policy(bindings_spec): """ Create an IAM policy for the resource. """ return { 'gcpIamPolicy': { 'bindings': bindings_spec } } def set_access_
control(resource, context): """ If necessary, define access control for the resource """ access_control = context.get('accessControl') if access_control is not None: resource['accessControl'] = create_iam_policy(access_control) def create_pubsub(resource_name, pubsub_spec): """ Create a topic ...
kubeflow/testing
py/kubeflow/tests/cleanup_ci_test.py
Python
apache-2.0
1,738
0.014384
from __future__ import print_function import unittest from kubeflow.testing import cleanup_ci import os import yaml class CleanupCiTest(unittest.TestCase): def setUp(self): self.test_dir = os.path.join(os.path.dirname(__file__), "test-data") def test_wait_for_workflow(self): with open(os.path.join(self....
m', 'kfctl-expired@kubeflow-ci.iam.gserviceaccount.com']: self.assertTrue('serviceAccount:' + act in members) cleanup_ci.trim_unused_bindings(iam_bindings, ['kfctl-in-use@kubeflow-ci.iam.gserviceaccount.com'], "k...
'][0]['members'] # binding to non-match service account still exists as it is not created by ci tests. self.assertTrue( 'serviceAccount:my-other-app@appspot.gserviceaccount.com'in trimed_members) # binding to existing service account still exists. self.assertTrue( 'serviceAccount...
marmarek/qubes-core-mgmt-client
qubesadmin/tests/tools/qvm_pause.py
Python
lgpl-2.1
3,376
0.000889
# -*- encoding: utf8 -*- # # The Qubes OS Project, http://www.qubes-os.org # # Copyright (C) 2017 Marek Marczykowski-Górecki # <
marmarek@invisiblethingslab.com> # # This program is free software; you can redi
stribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation; either version 2.1 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even...
nawawi/fail2ban
fail2ban/__init__.py
Python
gpl-2.0
2,770
0.009386
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*- # vi: set ft=python sts=4 ts=4 sw=4 noet : # This file is part of Fail2Ban. # # Fail2Ban 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;...
See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Fail2Ban; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fif
th Floor, Boston, MA 02110-1301, USA. # Author: Cyril Jaquier # __author__ = "Cyril Jaquier" __copyright__ = "Copyright (c) 2004 Cyril Jaquier" __license__ = "GPL" import logging.handlers # Custom debug levels logging.MSG = logging.INFO - 2 logging.TRACEDEBUG = 7 logging.HEAVYDEBUG = 5 logging.addLevelName(loggin...
ahmetdaglarbas/e-commerce
sites/sandbox/apps/sitemaps.py
Python
bsd-3-clause
1,779
0.000562
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.sitemaps import Sitemap from django.core.urlresolvers import reverse from django.utils.translation import get_language, activate from oscar.core.loading import get_model Product = get_model('catalogue', 'Product') Category = get_model('catalo...
ProductSitemap, 'categories': CategorySitemap, } # Construct the sitemaps for every language base_sitemaps = {} for language, __ in settings.LANGUAGES: for name, si
temap_class in language_neutral_sitemaps.items(): base_sitemaps['{0}-{1}'.format(name, language)] = sitemap_class(language)
leesavide/pythonista-docs
Documentation/matplotlib/users/recipes-4.py
Python
apache-2.0
653
0.003063
import matplotlib.pyplot as plt import numpy as np import matplotlib.cbook as cbook # load up some sample financial data datafile = cbook.get_sample_data('goog.npy') r = np.load(datafile).view(np.recarray) # create two subplots with the shared x and y axes fig, (ax1, ax2) = plt.subplots(1,2, sharex=True, sharey=True...
_visible(False) fig.suptitle('Go
ogle (GOOG) daily closing price') fig.autofmt_xdate()
hlzz/dotfiles
graphics/VTK-7.0.0/Imaging/Hybrid/Testing/Python/shepards.py
Python
bsd-3-clause
1,608
0.012438
#!/usr/bin/env
python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot() # Create the RenderWindow, Renderer and both Actors # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # create some points # math = vtk.vtkMath() points = vtk.vtkPoints() ...
kittiu/sale-workflow
sale_order_lot_selection/model/stock.py
Python
agpl-3.0
520
0
# -*- coding: utf-8 -*- # © 2015 Akretion (http://www.akretion.com). # @author Valentin CHEMIERE <valentin.chemiere@akretion.com> # License AGPL
-3.0 or later (http://www.gnu.org/licenses/agpl.html). from odoo import api, models class StockMove(models.Model): _inherit = 'stock.move' @api.multi def _prepare_procurement_from_move(self): self.ensure_one()
vals = super(StockMove, self)._prepare_procurement_from_move() vals['lot_id'] = self.restrict_lot_id.id return vals
yzsz/weibospider
page_get/user.py
Python
mit
6,126
0.001637
import json import re import requests from urllib.parse import quote from db.models import User from logger import storage from .basic import get_page from page_parse import is_404 from config import get_samefollow_uid from db.dao import ( UserOper, SeedidsOper) from page_parse.user import ( enterprise, person...
URL.format(user_id) isFanHtml = get_pag
e(url, auth_level=2) person.get_isFan(isFanHtml, samefollow_uid, user_id) # enterprise or service else: user = get_enterprise_detail(user_id, html) if user is None: return None user.name = public.get_username(html) user.head_img = public....
ericmok/djangosimpleblog
users/test_views.py
Python
mit
2,120
0.006132
from django.test import TestCase from django.test import Client from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.contrib.auth import SESSION_KEY from django.utils.six.moves.urllib.parse import urlparse from users.models import User class RegisterTestCase(TestCase...
scheme, netloc, path, params, query, fragment = urlparse(response.redirect_chain[0][0]) self.assertEqual(path, '/') self.assertEqual(User.objects.count(), 1) class SignInCase(TestCase): def setUp(self):
self.client = Client() def test_can_login(self): user = User.objects.create_user(username='blah', password='blah') response = self.client.post(reverse('users-signin'), data={'username': user.username, 'password': 'blah'}) self.assertEqual(response.status_code, 302) def test_can_logout(...
richardtran415/pymatgen
pymatgen/analysis/tests/test_structure_matcher.py
Python
mit
47,994
0.002563
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import itertools import json import os import unittest import numpy as np from monty.json import MontyDecoder from pymatgen.core.periodic_table import Element from pymatgen.core.lattice import Lattice from p...
um_sites") self.assertEqual(sm._get_supercell_size(s1, s2), (2, False)) self.assertEqual(sm._get_supercell_size(s2, s1), (2, True)) sm = StructureMatcher(supercell_size="Ag") self.assertEqual(sm._get_supercell_size(s1, s2), (2, False)) self.assertEqu
al(sm._get_supercell_size(s2, s1), (2, True)) sm = StructureMatcher(supercell_size=["Ag", "Cu"]) self.assertEqual(sm._get_supercell_size(s1, s2), (1, True)) self.assertEqual(sm._get_supercell_size(s2, s1), (1, True)) sm = StructureMatcher(supercell_size="wfieoh") self.assertRai...
maximeolivier/pyCAF
pycaf/architecture/devices/lists/serverList.py
Python
gpl-3.0
2,525
0.011485
#| This file is part of pyCAF. | #| | #| pyCAF is free software: you can redistribute it and/or modify | #| it under the terms of the GNU General Public License as published by | #| t...
he ident value @param ident : the number corresponding to the server """ if ident in self.dict.
keys(): return self.dict[ident] else: print "Server not found" def __str__(self): """ Print the list of server with their ident value """ # print self.label_interface_list() for identityNb, server in self.dict.items(): pri...
tensorflow/estimator
tensorflow_estimator/python/estimator/tpu/error_handling.py
Python
apache-2.0
5,327
0.004881
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
continue el
se: tf.compat.v1.logging.warn('Reraising captured error') six.reraise(typ, value, traceback) for k, (typ, value, traceback) in kept_errors: tf.compat.v1.logging.warn('Reraising captured error') six.reraise(typ, value, traceback)
rereidy/SPSE
module 4 - Attacking Web Applications/selenium-google.py
Python
gpl-3.0
664
0.004518
from selenium import webdriver from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.ui import WebDriverWait browser = webdriver.Firefox() browser.get("http://www.google.com") prin
t 'page title before search: {0}'.format(browser.title) inputElement = browser.find_element_by_name("q") inputElement.send_keys("seleniumhq") inputElement.submit() try: # we have
to wait for the page to refresh, the last thing that seems to be updated is the title WebDriverWait(browser, 10).until(expected_conditions.title_contains("seleniumhq")) print 'search results title: {0}'.format(browser.title) finally: browser.quit()
chhantyal/referly
referly/users/forms.py
Python
bsd-3-clause
248
0.004032
# -*- coding: utf-8 -*- from django import forms from
.models import User class UserForm(forms.ModelForm): class Meta: model = User # Constrain the UserForm to just thes
e fields. fields = ("first_name", "last_name")
giubil/trackit
api/files/api/app/gcloud/compute_metrics.py
Python
apache-2.0
5,327
0.009011
from app.gcloud.utils import refresh_credentials, get_gapi_authorized_http from datetime import datetime, timedelta import oauth2client import apiclient INSTANCE_METRICS = [ 'compute.googleapis.com/instance/cpu/utilization' ] INSTANCE_DISK_METRICS = [ 'compute.googleapis.com/instance/disk/read_bytes_count', ...
me'] if 'compute.googleapis.com/instance_name' in t['timeseriesDesc']['labels'] else t['timeseriesDesc']['labels']['compute.googleapis.com/resource_id']
base = dict(resource=resource, metric='GCLOUD/COMPUTE:{}'.format(metric_name)) for point in t['points']: if 'int64Value' in point: base.update(value=point['int64Value'], time=point['start']) ...
odoobgorg/addons
base_iso3166/models/__init__.py
Python
lgpl-3.0
120
0
# -*- coding: utf-8 -*- # License AGPL-3.0 or later (http://www.gnu.
org/licenses/agpl.html). from . impor
t res_country
ArcherSys/ArcherSys
Lib/tkinter/font.py
Python
mit
19,973
0.001352
<<<<<<< HEAD <<<<<<< HEAD # Tkinter font wrapper # # written by Fredrik Lundh, February 1998 # __version__ = "0.9" import itertools import tkinter # weight/slant NORMAL = "normal" ROMAN = "roman" BOLD = "bold" ITALIC = "italic" def nametofont(name): """Given the name of a tk named font, returns a Font repre...
self._set(options) if not name: name = "font" + str(next(s
elf.counter)) self.name = name if exists: self.delete_font = False # confirm font exists if self.name not in tk.splitlist(tk.call("font", "names")): raise tkinter._tkinter.TclError( "named font %s does not already exist" % (self.na...
vauxoo-dev/e-commerce
sale_automatic_workflow/sale_workflow_process.py
Python
agpl-3.0
3,372
0
# -*- encoding: utf-8 -*- ############################################################################### # # sale_automatic_workflow for OpenERP # Copyright (C) 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com> # Author: Guewen Baconnier # Copyright 2014 Camptocamp SA # # This program is free s...
on_picking_done', 'After Delivery')], required=True, string='Create Invoice', default='manual', ) validate_invoice = fields.Boolean(string='Validate Invoice') validate_picking = fields.Boolean(string='Confirm and Close Picking') invoice_date_is_order_date = fields.Boolean( ...
'Force Invoice Date', help="When checked, the invoice date will be " "the same than the order's date" ) warning = fields.Text('Warning Message', translate=True, help='If set, display the message when a ' 'user selects the process on a...
jdgwartney/boundary-api-cli
boundary/plugin_add.py
Python
apache-2.0
2,132
0.005159
# # Copyright 2015 BMC Software, 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 i...
, self.organizationName, self.
repositoryName) def get_description(self): return 'Imports a meter plugin from a GitHub repository into a {0} account'.format(self.product_name)
supriyantomaftuh/innstereo
innstereo/layer_view.py
Python
gpl-2.0
2,491
0.001204
#!/usr/bin/python3 """ Controls the behaviour of the treeview for the layer-view. This module contains the LayerTreeView class. It controls the behaviour and appearance of the layer-view which is in the upper left side of the GUI. The class inherits from Gtk.TreeView and requires a Gtk.TreeStore to initialize. """ f...
electionMode.MULTIPLE) self.set_property("can-focus", True) targets = [("text/plain", 0, 0)] self.enable_model_drag_source(Gdk.ModifierType.BUTTON1_MASK, targets, Gdk.DragActio
n.MOVE) self.enable_model_drag_dest(targets, Gdk.DragAction.MOVE) self.renderer_activate_layer = Gtk.CellRendererToggle() self.column_activate_layer = Gtk.TreeViewColumn("", self.renderer_activate_layer, ...
plakesr/bench
bench/app.py
Python
gpl-3.0
5,892
0.025458
import os from .utils import exec_cmd, get_frappe, check_git_for_shallow_clone, get_config, build_assets, restart_supervisor_processes, get_cmd_output, run_frappe_cmd import logging import requests import semantic_version import json import re import subprocess logger = logging.getLogger(__name__) class MajorVersio...
return get_major_version(get_current_version(frappe_dir)) except IOError: return '' def get_current_branch(repo_dir): return get_cmd_output("basename $(git symbolic-ref -q HEAD)", cwd=repo_dir) def fetch_upstream(repo_dir): return exec_cmd("git fetch upstream", cwd=repo_dir) def get_current_version(repo_dir)...
rn get_version_from_string(f.read()) def get_upstream_version(repo_dir): try: contents = subprocess.check_output(['git', 'show', 'upstream/{branch}:setup.py'.format(branch=get_current_branch(repo_dir))], cwd=repo_dir, stderr=subprocess.STDOUT) except subprocess.CalledProcessError, e: if "Invalid object" in e.out...
wagnerand/zamboni
apps/stats/tasks.py
Python
bsd-3-clause
19,050
0.000157
import datetime import httplib2 import itertools import json from django.conf import settings from django.db import connection, transaction from django.db.models import Sum, Max import commonware.log from apiclient.discovery import build from celeryutils import task from oauth2client.client import OAuth2Credentials ...
rties = service.management().webproperties().list( accountId=account_id).execute() webproperty_ids = [p['id'] for p in webproperties.get('items', ())] for webproperty_id in webproperty_ids: profiles = service.management().profiles().list( accountId=account_id, ...
includes "http://", sometimes it doesn't. if '://' in p['websiteUrl']: name = p['websiteUrl'].partition('://')[-1] else: name = p['websiteUrl'] if name == domain: return p['id'] @task def update_google_analyti...
kianby/stacosys
tests/test_config.py
Python
gpl-3.0
1,437
0.002088
#!/usr/bin/python # -*- coding: UTF-8 -*- import unittest from stacosys.conf.config import Config, ConfigParameter EXPECTED_DB_SQLITE_FILE = "db.sqlite" EXPECTED_HTTP_PORT = 8080 EXPECTED_LANG = "fr" class ConfigTestCase(unittest.TestCase): def setUp(self): self.conf = Config() self.conf.put(C...
ef test_get(self): self.assertEqual(self.conf.get(ConfigParameter.DB_SQLITE_FILE), EXPECTED_DB_SQLITE_FILE) self.assertEqual(self.conf.get(ConfigParameter.HTTP_PORT), EXPECTED_HTTP_PORT) self.assertIsNone(self.conf.get(ConfigParameter.HTTP_HOST)) self.assertEqual(self.conf.get(ConfigPara...
.HTTP_PORT), EXPECTED_HTTP_PORT) self.assertEqual(self.conf.get_int(ConfigParameter.HTTP_PORT), 8080) try: self.conf.get_bool(ConfigParameter.DB_SQLITE_FILE) self.assertTrue(False) except AssertionError: pass def test_put(self): self.assertFalse(s...
sinotradition/sinoera
sinoera/ganzhi/wuzi43.py
Python
apache-2.0
227
0.031674
#!/usr/bin/python #coding=utf-8 ''' @author: sheng @cont
act: sinotradition@gmail.com @copyright: License according to the project license. ''' NAME
='wuzi43' SPELL='wùzǐ' CN='戊子' SEQ='25' if __name__=='__main__': pass
synmnstr/flexx
flexx/ui/_splitter.py
Python
bsd-2-clause
16,430
0.005417
""" The splitter layout classes provide a mechanism to horizontally or vertically stack child widgets, where the available space can be manually specified by the user. Example: .. UIExample:: 200 from flexx import ui class Example(ui.Widget): def init(self): with ui.HSplitter(): ...
# Put a divider on all widgets except last, and index them self._ensure_all_dividers() # Set new divider positions; t
ake space from each widget needSize = self.node[clientWidth] / children.length sizeFactor= (self.node[clientWidth] - needSize) / self.node[clientWidth] newTs = [] tPrev = 0 for i in range(len(children)-1): divider = self._dividers[...
davibe/gobject-introspection
docs/giscanner/conf.py
Python
gpl-2.0
8,112
0.007396
# -*- coding: utf-8 -*- # # GObject-Introspection documentation build configuration file, created by # sphinx-quickstart on Tue Apr 16 15:34:52 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated...
nk = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> t...
# This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'GObject-Introspectiondoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or...
bxclib/leetcode
Sqrt(x).py
Python
gpl-3.0
306
0.01634
import math class Solution(object):
def mySqrt(self, x): """ :type x: int :rtype: int """ s=1 while True: s=0.5*(s+x*1.0/s) if abs(s**2-x)<0.001: break print s
return int(math.floor(s))
UCL-CERU/CESMapper
CESMapper/conf.py
Python
gpl-3.0
7,012
0.006703
# -*- coding: utf-8 -*- # # testgdt documentation build configuration file, created by # sphinx-quickstart on Sun Feb 12 17:11:03 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All...
directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minima
l Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.todo', 'sphinx.ext.pngmath', 'sphinx.ext.viewcode'] # Add any paths that contain templates ...
ashwin/json-viewer
json_viewer.py
Python
apache-2.0
4,537
0.000661
#!/usr/bin/env python3 __author__ = "Ashwin Nanjappa" # GUI viewer to view JSON data as tree. # Ubuntu packages needed: # python3-pyqt5 # Std import argparse import collections import json import sys # External from PyQt5 import QtCore from PyQt5 import QtGui from PyQt5 import QtWidgets class TextToTreeItem: ...
# Text box
self.find_box = QtWidgets.QLineEdit() self.find_box.returnPressed.connect(self.find_button_clicked) # Find Button find_button = QtWidgets.QPushButton("Find") find_button.clicked.connect(self.find_button_clicked) layout = QtWidgets.QHBoxLayout() layout.addWidget(self.fin...
mitmedialab/MediaCloud-Web-Tools
server/views/sources/geocount.py
Python
apache-2.0
733
0.002729
import logging import server.util.tags as tag_utl from server.cache import cache from server.auth import user_admin_mediacl
oud_client import server.views.sources.apicache as apicache from server.views.stories import QUERY_LAST_MONTH, QUERY_ENGLISH_LANGUAGE logger = logging.getLogger(__name__) @cache.cache_on_arguments() def cached_geotag_count(query): user_mc = user_admin_mediacloud_client() res = user_mc.storyTagCount(query, [Q...
QUERY_ENGLISH_LANGUAGE], tag_sets_id=tag_utl.GEO_TAG_SET) full_count = apicache.timeperiod_story_count(query, QUERY_LAST_MONTH)['count'] for r in res: r['pct'] = (float(r['count'])/float(full_count)) r['value'] = (float(r['count'])) return res
ml-lab/neon
neon/models/model.py
Python
apache-2.0
2,293
0
# ---------------------------------------------------------------------------- # Copyright 2014 Nervana Systems 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.o...
ams['epochs_complete'] = self.epochs_complete return np_params def set_params(self, params_dict): for i, ll in enumerate(self.layers): if ll.has_params: lkey = ll.name + '_' + str(i) ll.set_params(params_dict[lkey]) self.epochs_complete = params_d...
epochs_complete']
msantl/cryptofolio
cryptofolio/api/Config.py
Python
gpl-3.0
522
0.021073
class Config: BINANCE="Binance"
BITTREX="Bittrex" COINBASE="Coinbase" POLONIEX="Poloniex" COINBASEPRO="CoinbasePro" KRAKEN="Kraken" KUCOIN="Kucoin" BALANCE_ZERO=0.00000001 def get_configured_exchange_names(): return [Config.BINANCE, Config.BITTREX, Config.COINBASE, Config.POLONIEX, Config.COINBASEPRO, Config....
t_names()[0]
petebachant/MicronOpt-Python
setup.py
Python
mit
1,078
0.000928
#!/usr/bin/env python # coding=utf-8 from distutils.core import setup from micronopt import __version__ setup( name='MicronOpt', version=__version__, author='Pete Bachant', author_email='petebachant@gmail.com', py_modules=['micronopt'], scripts=[], url='https://github.com/petebachant/Micro...
long_description=open('README.md').read(), classifiers=[ "Development Status :: 2 - Pre-Alpha", "Intended Audience :: Science/Research", "N
atural Language :: English", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", ...
ericholscher/pypi
gae.py
Python
bsd-3-clause
1,646
0.006683
# Helper for the mirror on GAE # GAE GETs an action gae_file, giving GAE host and a secret # PyPI GETs /mkupload/secret, learning path and upload session # PyPI POSTs to upload session import urllib2, httplib, threading, os, binascii, urlparse POST="""\ --%(boundary)s Content-Disposition: form-data; name="secret" %(s...
ion/octet-stream %(data)s --%(boundary)s """ POST = "\r\n".join(POST.splitlines())+"\r\n" def doit(host, secret, srcdir): x = urllib2.urlopen('http://%s/mkupload/%s' % (host, secret)) if x.code != 200: return path,url = x.read().splitlines() host, session = urlpars
e.urlsplit(url)[1:3] try: data = open(srcdir+"/"+path).read() except IOError, e: return boundary = "" while boundary in data: boundary = binascii.hexlify(os.urandom(10)) body = POST % locals() if ':' in host: host, port = host.split(':') else: port = 8...
Meerkat007/Clothes-Shop-Website
server/clothes/apps.py
Python
mit
89
0
from django.apps import AppConfi
g class ClothesConfig(
AppConfig): name = 'clothes'
brainwane/obamaspeech
docs/source/conf.py
Python
gpl-3.0
6,121
0.002124
# -*- coding: utf-8 -*- # # Silly speech generator documentation build configuration file, created by # sphinx-quickstart on Wed Jul 19 16:57:13 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenera...
can be a ISBN number # or the project homepage. # # epub_identifier = '' # A unique identification for the text. # # epub_uid = '' # A list of files that should not be packed
into the epub file. epub_exclude_files = ['search.html'] # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'https://docs.python.org/': None}
oreno4645/clustering
clusters/kcluster_do.py
Python
mit
323
0.055728
#!/
usr/bin/env python # -*- coding: utf-8 -*- import clusters blognames,words,data=clusters.readfile( './../data/feed_list.csv' ) for k in range( 1, 10 ) : kclust = None kclust = clusters.kcluster(data, blognames, clusters.pearson, k) for k_id in range( len( kclust ) ): print [blognames[r] for r in kclust[k_
id]]
beepscore/greatest_common_divisor
test/test_greatest_common_divisor.py
Python
mit
2,281
0.001315
#!/usr/bin/env python3 import unittest import greatest_common_divisor as gcd class TestGreatestCommonDivisor(unittest.TestCase): def setUp(self): # use tuple of tuples instead of list of tuples because data won't change # https://en.wikipedia.org/wiki/Algorithm # a, b, expected s...
140, 34), (14157, 5950, 1) ) def test_greatest_common_divisor_zero(self): actual = gcd.GreatestCo
mmonDivisor.greatest_common_divisor(12, 0) self.assertEqual(0, actual) actual = gcd.GreatestCommonDivisor.greatest_common_divisor(0, 13) self.assertEqual(0, actual) actual = gcd.GreatestCommonDivisor.greatest_common_divisor(-5, 13) self.assertEqual(0, actual) def test_greate...
CSC-IT-Center-for-Science/spark-analysis
sparkles/modules/tests/dataframe_mock.py
Python
mit
389
0.002571
class DataframeMock(object): def __init__(self): pass def dtypes(s
elf): return ['field1, field2'] def saveAsParquetFile(self, tablepath): if(tablepath not in ['swift://containerFiles.SparkTest/file/file_ORDERS.parquet', 'swift://containerFeatures.SparkTest/feat.p
arquet']): raise RuntimeError('table path error') return 'success'
enavarro222/gsensors
gsensors/i2c_devices.py
Python
agpl-3.0
6,065
0.004453
#-*- coding:utf-8 -*- import sys import struct import array, io, fcntl import smbus from gevent import sleep from gsensors import AutoUpdateValue, DataSource class I2CRaw(object): def __init__(self, device, bus): self.fr = io.open("/dev/i2c-"+str(bus), "rb", buffering=0) self.fw = io.open("/dev/...
ttps://github.com/sparkfun/HTU21D_Breakout remainder = ( ( value[0] << 8 ) + value[1] ) << 8 remainder |= value[2] # POLYNOMIAL = 0x0131 = x^8 + x^5 + x^4 + 1 # divsor = 0x988000 is the 0x0131 polynomial shifted to farthest left of three bytes divsor = 0x988000 ...
ainder ^= divsor divsor = divsor >> 1 return remainder == 0 def read_temp(self): self.dev.write(self.CMD_READ_TEMP_NOHOLD) #measure temp sleep(.1) data = self.dev.read(3) buf = array.array('B', data) if not self.crc8check(buf): raise...
koluku/atcoder-beginner-contest
atcoder-beginner-contest/120/A.py
Python
mit
127
0
import math a, b, c = [int(
x) for x in input().split()] if a*c <= b: print(math.floor(c)) else: print(math.floor(b/
a))
MadsJensen/RP_scripts
extract_ts_epochs.py
Python
bsd-3-clause
1,400
0
import sys import numpy as np import mne from mne.minimum_norm import read_inverse_operator, apply_inverse_epochs from my_settings import (mne_folder, epochs_folder, source_folder, conditions) subject = sys.argv[1] method = "dSPM" snr = 3. lambda2 = 1. / snr**2 # labels = mne.read_labels_from_annot( # subject=s...
condition)) epochs = mne.read_epochs(epochs_folder + "%s_%s-epo.fif" % (subject, condition)) stcs = apply_inverse_epochs( epochs["press"], inv, lambda2, method=method, pick_ori=None) ts = [ ...
stc, labels, inv["src"], mode="mean_flip") for stc in stcs ] # for h, tc in enumerate(ts): # for j, t in enumerate(tc): # t *= np.sign(t[np.argmax(np.abs(t))]) # tc[j, :] = t # ts[h] = tc ts = np.asarray(ts) # stc.save(source_folder + "%s_%s_ar_epo" % (subjec...
faribas/RMG-Py
rmgpy/data/kinetics/family.py
Python
mit
100,418
0.005975
#!/usr/bin/python # -*- coding: utf-8 -*- ################################################################################ # # RMG - Reaction Mechanism Generator # # Copyright (c) 2002-2010 Prof. William H. Green (whgreen@mit.edu) and the # RMG Team (rmg_dev@mit.edu) # # Permission is hereby granted, free of c...
index=index, reactants=reactants, products=products, kinetics=kinetics, reversible=reversible, transitionState=transitionState, duplicate=duplicate, ...
self.estimator = estimator def __reduce__(self): """ A helper function used when pickling an object. """ return (TemplateReaction, (self.index, self.reactants, self.products, ...
FrodeSolheim/fs-uae-launcher
workspace/ui/text_area.py
Python
gpl-2.0
54
0
import fsu
i class TextArea(fsui.TextA
rea): pass
ksmaheshkumar/grr
lib/flows/tests.py
Python
apache-2.0
1,413
0
#!/usr/bin/env python """Loads up all flow tests.""" # pylint: disable=unused-import # These import populate the Flow test registry from grr.lib.flows.console import debugging_test # Cron tests. from grr.lib.flows.cron import compactors_test from grr.lib.flows.cron import filestore_stats_test from grr.lib.flows.cron ...
test from grr.lib.flows.general import artifact_fallbacks_test from grr.lib.flows.general import audit_test from grr.lib.flows.general import checks_test from grr.lib.flows.general import collectors_test from grr.lib.flows.
general import discovery_test from grr.lib.flows.general import endtoend_test from grr.lib.flows.general import export_test from grr.lib.flows.general import file_finder_test from grr.lib.flows.general import filesystem_test from grr.lib.flows.general import filetypes_test from grr.lib.flows.general import find_test fr...
cschu/spoutp_Galaxy
spFilter.py
Python
mit
1,984
0.033266
#!/usr/bin/env python import os import sys import csv import argparse from spoutP import PRED_HEADER def doStuff(args): # def removeRedundantCells(row): # del row[6] # del row[1] uniquePeptides = set() with open(args.filteredFile, 'wb') as out: out.write('\t'.join(PRED_HEADER) + '\n') reader = csv.reader...
r.add_argument('--minSignalLength', type=int, default=5) parser.add_argument('--minMatureLength', type=int, default=10) parser.add_argument('spoutFile', type=str, help='.') parser.add_argument('filteredFile', type=str, help='.') try: args = parser.parse_args() except: # print "xx" sys.exit(1)
if not os.path.exists(args.spoutFile): sys.stderr.write('Input file (%s) is missing.\n' % args.spoutFile) sys.exit(1) doStuff(args) if __name__ == '__main__': main(sys.argv[1:])
txus/docker-launcher
launcher/util/dict_wrapper.py
Python
gpl-3.0
3,553
0
# encoding: utf-8 # # Copyright © 2015 ATS Advanced Telematic Systems GmbH # # This file is part of Docker Launcher. # # Docker Launcher 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...
't import this for some reason import pyrx class SchemaError(Exception): """Exception to indicate a invalid yaml file""" def __init__(self, message): Exception.__init__(self) self.message = message def __str__(self): return self.message class DictWrapper(object): """ Thi...
trieve data from the parsed yaml. """ def __init__(self, data, schema=None): try: self.data = yaml.safe_load(data) except AttributeError: self.data = data if schema is not None: self.validator = pyrx.Factory({"register_core_types": True}) ...
go2net/PythonBlocks
components/ConnectorsInfoWnd.py
Python
mit
5,295
0.015486
from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.uic import * import os class ConnectorsInfoWnd(QDialog): def __init__(self, treeModel, genus): super(ConnectorsInfoWnd, self).__init__() self.genus = genus self.treeModel = treeModel dirname, filename = os.path.sp...
ItemIsEnabled | Qt.ItemIsEditable; def addConnector(self): #return from blocks.BlockImageIcon import BlockImageIcon icon = QPixmap(os.getcwd() + "\\" + 'resource\\117-puzzle.png') img = BlockImageIcon('', 'CENTER', icon, 32, 32, False, False) self.blockImages.append(img) ...
ModelIndex)"), index, index) def setData(self, index, value, role=Qt.DisplayRole): if (index.isValid() and role == Qt.EditRole): connector = self.connectors[index.row()] if(index.column() == 0): connector.label = value if(index.column() == 1): con...
atvcaptain/enigma2
lib/python/Components/FanControl.py
Python
gpl-2.0
4,179
0.032065
from __future__ import print_function from __future__ import absolute_import import os from Components.config import config, ConfigSubList, ConfigSubsection, ConfigSlider from Tools.BoundFunction import boundFunction import NavigationInstance from enigma import iRecordableService, pNavigation from boxbranding import ...
(0, 255)) if getBoxType() == 'tmsingle': fan.pwm = ConfigSlider(default = 100, increment = 5, limits = (0, 255)) else: fan.pwm = ConfigSlider(default = 50, increment = 5, limits = (0, 255)) fan.vlt_standby = ConfigSlider(default = 5, increment = 5, limits = (0, 255)) fan.pwm_standby = ConfigSlider(d...
ts = (0, 255)) fan.vlt.addNotifier(boundFunction(setVlt, self, fanid)) fan.pwm.addNotifier(boundFunction(setPWM, self, fanid)) config.fans.append(fan) def getConfig(self, fanid): return config.fans[fanid] def getFanCount(self): return self.fancount def hasRPMSensor(self, fanid): return os.path.exis...
vojnovski/amadeus-python
amadeus/amadeus.py
Python
bsd-3-clause
4,918
0.001627
# -*- coding: utf-8 -*- import requests import logging import sys API_URL = 'https://api.sandbox.amadeus.com/v1.2' def configure_logger(log_level=logging.WARN): logger = logging.getLogger(__name__) logger.setLevel(log_level) try: sa = logging.StreamHandler(stream=sys.stdout) except TypeError:...
api_url=API_URL): super(C
ars, self).__init__(api_key=api_key, api_url=api_url) self.api_url = "{api_url}/cars".format(api_url=api_url) class CO2Emissions(Transport): def __init__(self, api_key, api_url=API_URL): super(CO2Emissions, self).__init__(api_key=api_key, api_url=api_url) self.api_url = "{api_url}/CO2".for...
danking/hail
hail/python/hailtop/hailctl/dataproc/diagnose.py
Python
mit
5,732
0.004187
import re import json from subprocess import call, Popen, PIPE def init_parser(parser): parser.add_argument('name', type=str, help='Cluster name.') parser.add_argument('--dest', '-d', required=True, type=str, help="Directory for diagnose output -- must be local.") parser.add_argument('--hail-log', '-l', r...
_workers) == 0, "Non-existent workers specified: " + ", ".join(invalid_workers) workers = args.workers i
f args.take: assert args.take > 0 and args.take <= len( workers), "Number of workers to take must be in the range of [0, nWorkers]. Found " + args.take + "." workers = workers[:args.take] def gcloud_ssh(remote, command): return 'gcloud compute ssh {remote} --zone {zone} --comman...
rahulunair/nova
nova/api/openstack/compute/floating_ip_pools.py
Python
apache-2.0
1,765
0
# Copyright (c) 2011 X.commerce, a business unit of eBay 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 req...
'floating_ip_pools': [_translate_floating_ip_view(pool) for pool in pools] } class FloatingIPPoolsController(wsgi.Controller): """The Floating IP Pool API controller for the OpenStack API."
"" def __init__(self): super(FloatingIPPoolsController, self).__init__() self.network_api = neutron.API() @wsgi.Controller.api_version("2.1", MAX_PROXY_API_SUPPORT_VERSION) @wsgi.expected_errors(()) def index(self, req): """Return a list of pools.""" context = req.envir...
tolimit/tp-qemu
qemu/tests/virtual_nic_send_buffer.py
Python
gpl-2.0
3,680
0.000272
import logging from autotest.client import utils from autotest.client.shared import error from virttest import remote from virttest import utils_misc from virttest import utils_test from virttest import utils_net @error.context_aware def run(test, params, env): """ Test Steps: 1. boot up guest with snd...
1, "Wait %s test start" % bg_stress_test): err = "Fail to start netperf test between guest and host" raise error.TestError(err) pin
g_timeout = int(params.get("ping_timeout", 60)) host_ip = utils_net.get_host_ip_address(params) txt = "Ping %s from %s during netperf testing" % (host_ip, dsthost) error.context(txt, logging.info) status, output = utils_test.ping(host_ip, session=dst_ses, ...
josephharrington/ClusterRunner
app/master/build_fsm.py
Python
apache-2.0
8,309
0.002407
from enum import Enum import time from fysom import Fysom, FysomError # WIP(joey): Fysom is not thread safe -- multiple threads could theoretically traverse # WIP(joey): the same state transition simultaneously. from app.util import log class BuildState(str, Enum): """Posssible states for the FSM""" QUEUED ...
""" Register a callback that will be executed by Fysom when the specified state is entered. This leverages Fysom magic which calls methods by name using a convention ("onenter<state_name>"). :type build_state: BuildState :type callback: callable """ setattr(self._fs...
lback) def _record_state_timestamp(self, event): """ Record a timestamp for a given build status. This is used to record the timing of the various build phases and is exposed via the Build object's API representation. """ self._logger.debug('Build {} transitioned from {} to ...
humarf/OHsentinel
OHssdp.py
Python
apache-2.0
2,132
0.026266
# Copyright 2014 Dan Krause #:deploy:OHsentinel:/usr/local/share/OHsentinel # # 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 # # ...
ice, mx=mx), group) if udn == '': while True: try: response = SSDPResponse(sock.recv(1024)) responses[response.location] = response except socket.timeout: break sock.close()
return responses.values() else: while True: try: response = SSDPResponse(sock.recv(1024)) if udn in response.usn: sock.close() return response except socket.timeout: break return None
michaelimfeld/sourcemon
bin/setup_db.py
Python
mit
446
0.002242
#!/usr/bin/python """ setup database script """ from sourcemon.model.basemodel imp
ort BaseModel from sourcemon.model.ipmodel import IPModel from sourcemon.model.servermodel import ServerModel TABLES = [ IPModel, ServerModel ] def main(): """ create database tables """ database = BaseModel().database() database.connect() database.create_tables(TABLES, safe=True)...
f __name__ == "__main__": main()
Code4SA/ndp
ndp/templatetags/sectors.py
Python
mit
480
0.002083
from django import template from django.utils.html import conditional_escape from django.utils.safestring import mark_safe register = template.Library() @register.filter(needs_autoescape=True) def goallist(s, autoesc
ape=True): result = [] f
or line in (l.strip() for l in s.split('\n')): if line: if autoescape: line = conditional_escape(line) result.append('<li>%s</li>' % line) return mark_safe('\n'.join(result))
tensorflow/tensorboard
tensorboard/plugins/metrics/metrics_loader.py
Python
apache-2.0
1,185
0
# Copyright 2020 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...
nguage governing permissions and # limitations under the License. # ============================================================================== """The TensorBoard metrics plugin loader.""" from tensorboard.plugins import base_plugin from tensorboard.plugins import metrics_plugin class MetricsLoader(base_plugin.T...
Args: context: The TBContext instance. """ if not context._data_provider: return None return metrics_plugin.MetricsPlugin(context)
dhermes/project-euler
python/complete/no084.py
Python
apache-2.0
4,565
0.000219
#!/usr/bin/env python from random import choice from python.decorators import euler_timer SQUARES = ["GO", "A1", "CC1", "A2", "T1", "R1", "B1", "CH1", "B2", "B3", "JAIL", "C1", "U1", "C2", "C3", "R2", "D1", "CC2", "D2", "D3", "FP", "E1", "CH2", "E2", "E3", "R3",...
"CH3"]: # 1/16 Go, Jail, C1, E3, H2, R1, next U, back 3 # 1/8 Next R chance_card = (chance_card + 1) % 16 if chance_card == 0: return ("GO", chance_card, chest_card) elif chance_card == 1: return ("JAIL", chance_card, chest_card) elif chan
ce_card == 2: return ("C1", chance_card, chest_card) elif chance_card == 3: return ("E3", chance_card, chest_card) elif chance_card == 4: return ("H2", chance_card, chest_card) elif chance_card == 5: return ("R1", chance_card, chest_card) e...
scheunemann/robotActionController
robotActionController/Processor/event.py
Python
mit
1,561
0
"""credit: http://www.emptypage.jp/notes/pyevent.en.html""" __all__ = ['Event', ] class Event(object): def __init__(self, doc=None): self.__doc__ = doc def __get__(self, obj, objtype=None): if obj is None: return self return EventHandler(self, obj) def __set__(self,...
: def __init__(self, event, obj): self.event = event self.obj = obj def _getfunctionlist(self): """(internal use) """ try: eventhandler = self.obj.__eventhandler__ except AttributeError: eventhandler = self.obj.__eventhandler__ = {} retu...
like func(sender, earg). You can add handler also by using '+=' operator. """ self._getfunctionlist().append(func) return self def remove(self, func): """Remove existing event handler function. You can remove handler also by using '-=' operator. """ ...
bvamanan/ns3
src/internet/bindings/modulegen__gcc_LP64.py
Python
gpl-2.0
946,654
0.014945
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers import pybindgen.settings import warnings class ErrorHandler(pybindgen.settings.ErrorHandler): def handle_error(self, wrapper, exception, traceback_): warnings.warn("exception %r in wrapper %s" % (exception, wrapper)) ...
ocket-address.h (module 'network'): ns3::Inet6SocketAddress [class] root_module['ns3::Inet6SocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] module.add_class('InetSocketAddress', import_from_module='ns.network') ...
## inet-socket-address.h (module 'network'): ns3::InetSocketAddress [class] root_module['ns3::InetSocketAddress'].implicitly_converts_to(root_module['ns3::Address']) ## int-to-type.h (module 'core'): ns3::IntToType<0> [struct] module.add_class('IntToType', import_from_module='ns.core', template_parameters=...
Jonnymcc/ansible
lib/ansible/executor/process/worker.py
Python
gpl-3.0
5,740
0.006098
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) an...
ng more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.compat.six.moves import queue import json import multiprocessing import os import signal import sys import time import traceback import zlib from jinja2.exceptions import TemplateNotFound # TODO:...
RK=False from ansible.errors import AnsibleError, AnsibleConnectionFailure from ansible.executor.task_executor import TaskExecutor from ansible.executor.task_result import TaskResult from ansible.playbook.handler import Handler from ansible.playbook.task import Task from ansible.vars.unsafe_proxy import AnsibleJSONUns...
jcavalieri8619/siamese_sentiment
CNN_model.py
Python
mit
11,371
0.002199
from __future__ import print_function import datetime import os from keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau from keras.engine.training import Model from keras.initializers import RandomUniform from keras.layers import Convolution1D, MaxPooling1D from keras.layers import Dense, Dropou...
u(layer) # if is_IntermediateModel: return Model(inputs=[review_input]
, outputs=[layer], name="CNN_model") # # layer = Dropout(0.5)(layer) layer = Dense(dense_dims_final, activation=dense_activation_final, kernel_initializer=dense_init_final, kernel_regularizer=dense_reg0, name='output_Full')(layer) CNN_model = Model(inputs=[review_i...
mkoura/dump2polarion
dump2polarion/exporters/transform.py
Python
gpl-2.0
8,094
0.001606
"""Helper functions for transforming results.""" import hashlib import logging import os import re import urllib.parse from typing import Optional from docutils.core import publish_parts from dump2polarion.exporters.verdicts import Verdicts # pylint: disable=invalid-name logger = logging.getLogger(__name__) TEST_P...
if it's identical to title if title and result.get("id") ==
title: result["id"] = result["title"] else: # don't parametrize if not specifically configured if "params" in result: del result["params"] def include_class_in_title(result): """Make sure that test class is included in "title". Applies only to titles derived from ...
Juanlu001/poliastro
tests/tests_atmosphere/test_coesa76.py
Python
mit
4,896
0.002042
import pytest from astropy import units as u from astropy.tests.helper import assert_quantity_allclose from poliastro.atmosphere import COESA76 from poliastro.atmosphere.coesa76 import p_coeff, rho_coeff coesa76 = COESA76() def test_outside_altitude_range_coesa76(): with pytest.raises(ValueError) as excinfo: ...
sound over 86
km with pytest.raises(ValueError) as excinfo: coesa76.sound_speed(z) assert ( "ValueError: Speed of sound in COESA76 has just been implemented up to 86km." in excinfo.exconly() ) def test_viscosity_over_86km(): z = 87 * u.km # test viscosity over 86 km with pytest.rais...
Arahabica/NNTrain
train/neural/NeuralTrain.py
Python
mit
318
0.003401
#
-*- coding: utf-8 -*- # 3章 ニューラルネットワーク import numpy as np class NeuralTrain: def step_function(self, x): return np.arr
ay(x > 0, dtype=np.int) def sigmoid_function(self, x): return 1 / (1 + np.exp(-x)) def relu_function(self, x): return np.maximum(0, x)
Infinidat/infi.clickhouse_orm
tests/test_mutations.py
Python
bsd-3-clause
3,619
0.001934
import unittest from infi.clickhouse_orm import F from .base_test_with_data import * from time import sleep class MutationsTestCase(TestCaseWithData): def setUp
(self): super().setUp() if self.database.server_version < (18,): raise unittest.SkipTest('ClickHouse version too old') self._insert_all() def _wait_for_mutations(self): sql = 'SELECT * FROM system.mutations WHERE is_done = 0' while list(self
.database.raw(sql)): sleep(0.25) def test_delete_all(self): Person.objects_in(self.database).delete() self._wait_for_mutations() self.assertFalse(Person.objects_in(self.database)) def test_delete_with_where_cond(self): cond = Person.first_name == 'Cassady' s...
diabolicfreak/url_shortner
src/shortner/migrations/0002_shortnerurl_shortcode.py
Python
mit
504
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-07-13 18:04 from __fu
ture__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shortner', '0001_initial'), ] operatio
ns = [ migrations.AddField( model_name='shortnerurl', name='shortcode', field=models.CharField(default='defaultsc', max_length=15), preserve_default=False, ), ]
himanshusahay/resume-drop
mysite/resumedrop/urls.py
Python
gpl-3.0
715
0.020979
from django.conf.urls import url from django.core import urlresolvers from django.contrib import admin from . import views from django.conf import settings from django.
conf.u
rls.static import static app_name = 'resumedrop' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^create_success/$', views.create_success, name='create_success'), url(r'^success/$', views.success_redirect, name='success_redirect'), # ex: resumedrop/student_create url(r'^student_create/$', views.stu...