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
pridkett/pyexiv2
test/rational.py
Python
gpl-2.0
3,750
0
# -*- coding: utf-8 -*- # ****************************************************************************** # # Copyright (C) 2008-2010 Olivier Tilloy <olivier@tilloy.net> # # This file is part of the pyexiv2 distribution. # # pyexiv2 is free software; you can redistribute it and/or # modify it under the terms of the GNU...
pass else: self.fail('Denominator is not read-only.') def test_match_string(self): self.assertEqual(Rational.match_string('4/3'), (4, 3)) self.assertEqual(Rational.match_string('-4/3'), (-4, 3)) self.assertEqual(Rational.match_string('0/3'), (0, 3)) self...
ual(Rational.match_string('0/0'), (0, 0)) self.assertRaises(ValueError, Rational.match_string, '+3/5') self.assertRaises(ValueError, Rational.match_string, '3 / 5') self.assertRaises(ValueError, Rational.match_string, '3/-5') self.assertRaises(ValueError, Rational.match_string, 'invalid'...
pcmoritz/ray-1
rllib/tests/test_exec_api.py
Python
apache-2.0
2,301
0
import unittest import ray from ray.rllib.agents.a3c import A2CTrainer from ray.rllib.execution.common import STEPS_SAMPLED_COUNTER, \ STEPS_TRAINED_COUNTER from ray.rllib.utils.test_utils import framework_iterator class TestDistributedExecution(unittest.TestCase): """General tests for the distributed execut...
0, "framework": fw, }) res1 = trainer.train() checkpoint = trainer.save() for _ in
range(2): res2 = trainer.train() assert res2["timesteps_total"] > res1["timesteps_total"], \ (res1, res2) trainer.restore(checkpoint) # Should restore the timesteps counter to the same as res2. res3 = trainer.train() assert res...
funbaker/astropy
astropy/samp/tests/test_standard_profile.py
Python
bsd-3-clause
8,591
0.001048
import ssl import tempfile import pytest from ...utils.data import get_pkg_data_filename from ..hub import SAMPHubServer from ..integrated_client import SAMPIntegratedClient from ..errors import SAMPProxyError # By default, tests should not use the internet. from .. import conf from .test_helpers import random_par...
# Test notify params = random_params(self.tmpdir) self.client1.notify(self.client2.get_public_id(), {'samp.mtype': 'table.load.votable', 'samp.params': params}) assert_output('table.load.votable', self.client2.get_private_key(), ...
nt1_id, params, timeout=60) params = random_params(self.tmpdir) self.client1.enotify(self.client2.get_public_id(), "table.load.votable", **params) assert_output('table.load.votable', self.client2.get_private_key(), self.client1_id, params, tim...
Rene90/dl4nlp
hw6_babi_qa/babi2.py
Python
mit
6,138
0.006191
#!/usr/bin/python # # author: # # date: # description: # '''Trains a memory network on the bAbI dataset. References: - Jason Weston, Antoine Bordes, Sumit Chopra, Tomas Mikolov, Alexander M. Rush, "Towards AI-Complete Question a1ing: A Set of Prerequisite Toy Tasks", http://arxiv.org/abs/1502.05698 - Sainbayar...
)) #m2 = Sequential() #m2.add(Embedding(input_dim=vocab_size, #output_dim=embedding_dim,
#input_length=story_maxlen)) #w2 = Sequential() #w2.add(Merge([m2, u2], mode='dot', dot_axes=[2, 2])) #c2 = Sequential() #c2.add(Embedding(input_dim=vocab_size, #output_dim=query_maxlen, #input_length=story_maxlen)) #o2 = Sequential() #o2.add(Merge([w2, c2], mode='sum')) #...
yast/yast-python-bindings
examples/Heading2.py
Python
gpl-2.0
361
0.01662
# encoding: utf-8 from yast import
import_module import_module('UI') from yast import * class Heading2Client: def main(self): UI.OpenDialog( VBox( Heading("This Is a Heading."), Label("This is a Label."), PushButton("&OK") ) )
UI.UserInput() UI.CloseDialog() Heading2Client().main()
bdacode/hoster
hoster/junocloud_me.py
Python
gpl-3.0
3,651
0.003561
# -*- coding: utf-8 -*- """Copyright (C) 2013 COLDWELL AG 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 program is dist...
1)[1]) + time.time() for result, challenge in chunk.solve_captcha('recaptcha', parse=resp.text, retries=5): data['recaptcha_challenge_field'] = challenge data['recaptcha_response_field'] = result if wait and wait - time.time() > 0: c
hunk.wait(wait - time.time()) resp = submit(allow_redirects=False) if resp.status_code == 302: return resp.headers['Location'] check_errors(chunk, resp)
matt-deboer/marathon-lb
zdd_exceptions.py
Python
apache-2.0
2,721
0
""" Exit Status 1 is already used in the script. Zdd returns with exit status 1 when app is not force deleted either through argument or through prompt. Exit Status 2 is used for Unknown Exceptions. """ class InvalidArgException(Exception): """ This exception indicates invalid combination of arguments...
rathonEndpointException(Exception): """ This excaption indicates issue with marathon endpoint specified as argument to Zdd""" def __init__(self, msg, url, error): super(MarathonEndpointException, s
elf).__init__(msg) self.msg = msg self.url = url self.error = error self.zdd_exit_status = 6 class AppCreateException(Exception): """ This exception indicates there was a error while creating the new App and hence it was not created.""" def __init__(self, msg, url, payl...
dadasoz/dj-translate
autotranslate/views.py
Python
mit
22,363
0.002862
from django.conf import settings from django.contrib.auth.decorators import user_passes_test from django.core.paginator import Paginator from django.core.urlresolvers import reverse from django.http import Http404, HttpResponseRedirect, HttpResponse from django.shortcuts import render from django.utils.encoding import ...
plural_string = fix_nls(entry.msgid_plural, value) entry.msgstr_plural[plural_id] = plural_string else: entry.msgstr = fix_nls(entry.msgid, value) is_fuzzy = bool(request.POST.get('f_%s'...
entry.flags if old_fuzzy and not is_fuzzy: entry.flags.remove('fuzzy') elif not old_fuzzy and is_fuzzy: entry.flags.append('fuzzy') file_change = True if old_msgstr...
sjperkins/tensorflow
tensorflow/contrib/__init__.py
Python
apache-2.0
3,181
0
# Copyright 2015 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...
ntrib import nccl from t
ensorflow.contrib import nn from tensorflow.contrib import opt from tensorflow.contrib import quantization from tensorflow.contrib import rnn from tensorflow.contrib import saved_model from tensorflow.contrib import seq2seq from tensorflow.contrib import signal from tensorflow.contrib import slim from tensorflow.contri...
studiawan/pygraphc
pygraphc/abstraction/AbstractionUtility.py
Python
mit
2,712
0.001475
import json class AbstractionUtility(object): @staticmethod def read_json(json_file): # read json data with open(json_file, 'r') as f: data = json.load(f) # change json key string to int converted_data = {} for key, value in data.iteritems(): co...
ems(): for line_id in abstraction['original_id']: abstraction_label[line_id] = abstraction_id # write log per line with abstraction id f_perline = open(perline_file, 'w') for line_id, log in enumerate(logs): f_perline.write(str(abstraction_label[line_id])...
le, abstractions): # read ground truth abstraction_groundtruth = AbstractionUtility.read_json(logid_abstractionid_file) groundtruth_length = len(abstraction_groundtruth.keys()) abstractions_edited_id = {} for abstraction_id, abstraction in abstractions.iteritems(): #...
christianurich/VIBe2UrbanSim
3rdparty/opus/src/sanfrancisco/zone/SSS_travel_time_to_DDD.py
Python
gpl-2.0
1,871
0.017103
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from urbansim.abstract_variables.abstract_travel_time_variable_for_non_interaction_dataset import abstract_travel_time_variable_for_non_interaction_dataset class SSS_travel_time_to_DDD(abstract...
f __name__=='__main__': opus_uni
ttest.main()
llambeau/finitio.py
tests/type/set_type/test_low.py
Python
isc
619
0.001616
#!/usr/bin/env python # -*- coding: ut
f-8 -*- """ test_equality ---------------------------------- Tests for the `SetType` low() method """ import unittest from finitio.types import SetType, BuiltinType, Type builtin_string = BuiltinType(str) class TestSetTypeLow(unittest.TestCase): class HighType(Type): def low(self): retu...
self.assertEqual(self.subject.low(), expected) if __name__ == '__main__': import sys sys.exit(unittest.main())
strogo/djpcms
djpcms/models.py
Python
bsd-3-clause
354
0.019774
from djpcms import sites
if sites.settings.CMS_ORM == 'django': from djpcms.core.cmsmodels._django import * elif sites.sett
ings.CMS_ORM == 'stdnet': from djpcms.core.cmsmodels._stdnet import * else: raise NotImplementedError('Objecr Relational Mapper {0} not available for CMS models'.format(sites.settings.CMS_ORM))
ahhz/raster
benchmarks/benchmark_3_layers_arcpy.py
Python
mit
478
0.004184
import time import arcpy from arcpy import env from arcpy.sa import * # Set environment settings env.workspace = "" # set your workspace arcpy.env.overwriteOutput = True # Check out the ArcGIS Spatial Analyst extension license arcpy.CheckOutExtension("Spatial") tic = time.clock() a_file = "random_a.tif" b
_fil
e = "random_b.tif" c_file = "random_c.tif" out_file = "output.tif" a = Raster(a_file) b = Raster(b_file) c = Raster(c_file) out = 3 * a + b * c out.save(out_file)
emineKoc/WiseWit
wisewit_front_end/node_modules/pygmentize-bundled/vendor/pygments/pygments/styles/vs.py
Python
gpl-3.0
1,073
0
# -*- coding: utf-8 -*- """ pygments.styles.vs ~~~~~~~~~~~~~~~~~~ Simple style with MS Visual Studio colors. :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.style import Styl
e from pygments.token import Keyword, Name, Comment, String, Error, \ Operator, Generic class VisualStudioStyle(Style): background_color = "#ffffff" default_style = "" styles
= { Comment: "#008000", Comment.Preproc: "#0000ff", Keyword: "#0000ff", Operator.Word: "#0000ff", Keyword.Type: "#2b91af", Name.Class: "#2b91af", String: "#a31...
haizawa/odenos
src/test/python/org/o3project/odenos/core/component/network/flow/basic/test_flow_action.py
Python
apache-2.0
1,561
0.001281
# -*- coding:utf-8 -*- # Copyright 2015 NEC 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-2.0 # # # # Unless required by applicable law or agreed to in writing,...
acsone/multi-company
purchase_sale_inter_company/models/purchase_order.py
Python
agpl-3.0
9,730
0.000103
# -*- coding: utf-8 -*- # © 2013-Today Odoo SA # © 2016 Chafique DELLI @ Akretion # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import api, models, _, fields from openerp.exceptions import Warning as UserError class PurchaseOrder(models.Model): _inherit = 'purchase.order' ...
y_uos=0, uos=False, name='', partner_id=sale_order.partner_id.id, lang=False, update_tax=True, date_order=sale_order.date_order, packaging=False, fiscal_p
osition=sale_order.fiscal_position.id, flag=False, warehouse_id=sale_order.warehouse_id.id) sale_line_data['value']['product_id']
tpainter/df_everywhere
df_everywhere/util/consoleInput.py
Python
gpl-2.0
1,794
0.007246
#from: http://stackoverflow.com/questions/10361820/simple-twisted-echo-client #and #from: http://stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user from twisted.internet.threads import deferToThread as _deferToThread from twisted.internet import reactor class ConsoleInput(object): de...
unction, reconnectFunction): self.stopFunction = stopFunction self.reconnectFunction = reconnectF
unction def start(self): self.terminator = 'q' self.restart = 'r' self.getKey = _Getch() self.startReceiving() def startReceiving(self, s = ''): if s == self.terminator: self.stopFunction() elif s == self.restart: self.reconnectFunctio...
atiqueahmedziad/addons-server
src/olympia/bandwagon/tests/test_serializers.py
Python
bsd-3-clause
6,482
0
# -*- coding: utf-8 -*- import mock from rest_framework import serializers from waffle.testutils import override_switch from olympia.amo.tests import ( BaseTestCase, addon_factory, collection_factory, TestCase, user_factory) from olympia.bandwagon.models import CollectionAddon from olympia.bandwagon.serializers im...
et-spam-check', active=True) @mock.patch('olympia.lib.akismet.models.AkismetReport.comment_check') def test_spam(self, comment_check_mock): comment_check_mock.return_value =
AkismetReport.MAYBE_SPAM with self.assertRaises(serializers.ValidationError): self.validator(self.data) # Akismet check is there assert AkismetReport.objects.count() == 2 name_report = AkismetReport.objects.first() # name will only be there once because it's duplic...
MachineandMagic/django-avatar
tests/urls.py
Python
bsd-3-clause
108
0
from django.conf
.urls import include, url urlpatterns = [ url(
r'^avatar/', include('avatar.urls')), ]
electronic-structure/sirius
python_module/setup.py
Python
bsd-2-clause
499
0.002004
import setuptools setuptools.setup( name="sirius", version="0.
5", author="", author_email="simon.pintarelli@cscs.ch", description="pySIRIUS", url="https://github.com/electronic_structure/SIRIUS", packages=['sirius'], install_requires=['mpi4py', 'voluptuous', 'numpy', 'h5py', 'scipy', 'PyYAML'], classifiers=[ "Programming Language :: Python :: 3...
nkoech/csacompendium
csacompendium/locations/api/precipitation/precipitationviews.py
Python
mit
2,016
0.002976
from csacompendium.locations.models import Precipitation from csacompendium.utils.pagination import APILimitOffsetPagination from csacompendium.utils.permissions import IsOwnerOrReadOnly from csacompendium.utils.viewsutils import DetailViewUpdateDelete, CreateAPIViewHook from rest_framework.filters import DjangoFilterB...
minUser] lookup_field
= 'pk' return { 'PrecipitationListAPIView': PrecipitationListAPIView, 'PrecipitationDetailAPIView': PrecipitationDetailAPIView, 'PrecipitationCreateAPIView': PrecipitationCreateAPIView }
JohnUrban/poreminion
poreminion/poreminion_main.py
Python
mit
59,570
0.012641
#!/usr/bin/env python import os.path import sys import argparse from poretools.Fast5File import * #logger import logging logger = logging.getLogger('poreminion') # poreminion imports import poreminion.version def run_subtool(parser, args): if args.command == 'uncalled': import findUncalled as submodule ...
Errors ########## parser_timetest = subparsers.add_parser('timetest', help='Find Fast5 files that have event times that are earlier than event times before it suggesting malfunction/erroneous read.') pars
er_timetest.add_argument('files', metavar='FILES', nargs='+', help='The input FAST5 files.') parser_timetest.add_argument('--outprefix', "-o", type=str, default=False, help='Uses this as basename for file containing list of ...
zhangg/trove
trove/guestagent/strategies/restore/experimental/couchbase_impl.py
Python
apache-2.0
9,593
0
# Copyright (c) 2014 eBay Software Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
str(replica_number) + '"' + ' -d replicaIndex="' + str(replica_index) + '"' + ' -d threadsNumber="' + str(threads) + '"' + ...
str(flush) + '" ' + system.COUCHBASE_REST_API + '/pools/default/buckets') utils.execute_with_timeout(create_bucket_cmd, shell=True, timeout=300) ...
michaelpacer/scikit-image
skimage/feature/_hog.py
Python
bsd-3-clause
7,022
0.000142
from __future__ import division import numpy as np from .._shared.utils import assert_nD from . import _hoghistogram def hog(image, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(3, 3), visualise=False, normalise=False): """Extract Histogram of Oriented Gradients (HOG) for a given image. Co...
+ eps) """ The final step collects the HOG descriptors from all blocks of a dense overlapping grid of blocks covering the detection window into a combined feature vector for use in the window classifier.
""" if visualise: return normalised_blocks.ravel(), hog_image else: return normalised_blocks.ravel()
olivierlemasle/murano
murano/common/i18n.py
Python
apache-2.0
1,149
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 # d...
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # u
nder the License. """oslo.i18n integration module. See http://docs.openstack.org/developer/oslo.i18n/usage.html """ import oslo_i18n _translators = oslo_i18n.TranslatorFactory(domain='murano') # The primary translation function using the well-known name "_" _ = _translators.primary # Translators for log levels. ...
makinacorpus/ionyweb
ionyweb/website/models.py
Python
bsd-3-clause
9,120
0.004715
# -*- coding: utf-8 -*- " WebSite models " import os import shutil from django.conf import settings from django.contrib.auth.models import User from django.contrib.sites.models import Site from django.db import connection from django.db import models from django.db.utils import IntegrityError from django.utils.transla...
s WebSite(models.Model): ''' WebSite New contract of WebSite. Everything is linked to an instance of this model. (Pages, Files, ...) ''' slug = models.SlugField(_(u"url"), max_length=100, unique=True) title = models.CharField(_(u"title...
"), upload_to='media_root', # TEMP -> pbs with PIL... blank=True) ndds = models.ManyToManyField(Site, related_name="website") owners = models.ManyToManyField(User, ...
clebergnu/avocado-vt
virttest/virsh.py
Python
gpl-2.0
152,004
0.000329
""" Utility classes and functions to handle connection to a libvirt host system The entire contents of callables in this module (minus the names defined in NOCLOSE below), will become methods of the Virsh and VirshPersiste
nt classes. A Closure class is used to wrap the module functions, lambda does not properly store instance state in this implementation. Because none of the methods have a 'self' parameter defined, the classes are defined to be dict-like, and get passed in to the methods as a the special ``**dargs`` parameter. All v
irsh module functions _MUST_ include a special ``**dargs`` (variable keyword arguments) to accept non-default keyword arguments. The standard set of keyword arguments to all functions/modules is declared in the VirshBase class. Only the 'virsh_exec' key is guaranteed to always be present, the remainder may or may not...
frossigneux/blazar
climate/tests/db/test_utils.py
Python
apache-2.0
741
0
# -*- coding: utf-8 -*- # # Author: François Rossigneux <francois.ro
ssigneux@inria.fr> # # 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 speci...
Bolt64/my_code
Code Snippets/domain_coloring.py
Python
mit
3,030
0.022112
#!/home/bolt/.python_compiled/bin/python3 import math from PIL import Image def complex_wrapper(func, scale_factor=1): """ Modifies a complex function that takes a complex argument and returns a complex number to take a tuple and return a tuple. """ def inner(real, imag): complex_num=c...
dient """ x,y=position shade_tuple=assign_color_shade(position) if x**2+y**2<radius**2: r,b,g=shade_tuple ratio=((x**2+y**2)/(radius**2))**gradient r_new,b_new,g_new=255-ratio*(255-r),255-ratio*(255-b),255-ratio*(255-g) return r_new,b_new,g_new else: ratio=((r...
2 functions and returns the shade of each point """ r,b,g=color_intensity(position, radius, gradient) return round(r), round(b), round(g) def generate_plane_image(x_size, y_size, radius, gradient): """ This function generates the domain plane """ image=Image.new('RGB', (x_size, y_size)) ...
sanyaade-mobiledev/clusto
src/clusto/commands/console.py
Python
bsd-3-clause
2,107
0.003322
#!/usr/bin/env python # -*- mode: python; sh-basic-offset: 4; indent-tabs-mode: nil; coding: utf-8 -*- # vim: tabstop=4 softtabstop=4 expandtab shiftwidth=4 fileencodi
ng=utf-8 # # Shell command # Copyright 2010, Jeremy Grosser <synack@digg.com> i
mport argparse import os import sys import clusto from clusto import script_helper class Console(script_helper.Script): ''' Use clusto's hardware port mappings to console to a remote server using the serial console. ''' def __init__(self): script_helper.Script.__init__(self) def _ad...
kschoelz/abacuspb
test/test_data.py
Python
gpl-2.0
5,915
0.005748
from datetime import datetime ##################### # Account Test Data # ##################### account = { 'name': 'Test Account Name', 'type': 'Checking', 'bank_name': 'Bank of Catonsville', 'account_num': '1234567890' } account_put = { 'name': 'Savings Account', 'type': 'Savings' } db_accou...
sville', 'account_num': '0987654320', 'bal_uncleared': 500.00, 'bal_cleared': 500.00, 'bal_reconciled': 600.00, 'budget_monitored': False } ######################### # Transaction Test Data # ######################### transaction = { 'date': '2014-08-10', 'type': 'EFT', 'payee': 'Giant'...
'date': '2014-08-10', 'type': 'XFER', 'payee': 'Move to Savings', 'reconciled': '', 'amount': -100.00, 'memo': '', 'cat_or_acct_id': 'acct_toaccountname' } transaction_put_amount = { # id = 53f69e77137a001e344259cb (Amazon.com) 'amount': -14.01, 'memo': 'Birthday present' } transactio...
adobe-research/spark-cluster-deployment
application-deployment-fabfile.py
Python
apache-2.0
4,180
0.013636
# fabfile.py # TODO - Description. # ########################################################################### ## ## Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved. ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the Lice...
g['remote_jar_dir'] )) @task @roles('master') def start(): outIO = io.BytesIO(); errIO = io.BytesIO() sudo(' '.join([ config['remote_spark_dir'] + '/bin/spark-submit ', '--class', config['main_class'], '--master', config['spark_master'], '--deploy-mode', 'cluster', config['remote_jar_dir'] + '/' + ...
r = outIO.read() driverRe = re.search("State of (driver-\d*-\d*) is (\S*)", outStr) driverId = driverRe.group(1) status = driverRe.group(2) print(" DriverID: " + driverId) print(" Status: " + status) if status == "ERROR": msg = """ The error state occurs when the Spark Master rejects the job, ...
earwig/mwparserfromhell
src/mwparserfromhell/definitions.py
Python
mit
3,915
0
# Copyright (C) 2012-2020 Ben Kurtovic <ben.kurtovic@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. """ Contains data about certain markup, like HTML tags and external links. When updating this file, please...
wparserfromhell/parser/ctokenizer/definitions.c - mwparserfromhell/parser/ctokenizer/definitions.h """ __all__ = [ "get_html_tag", "is_parsable", "is_visible", "is_single", "is_single_only", "is_scheme", ] URI_SCHEMES = { # [wikimedia/mediawiki.git]/includes/DefaultSettings.php @ 5c660de5d...
fabioz/PyDev.Debugger
tests_python/resources/_debugger_case_wait_for_attach.py
Python
epl-1.0
174
0.005747
if _
_name__ == '__main__': # We want to call _enable_attach inside an import to make sure that it works properly that way. import _debugger_case_wait_for
_attach_impl
Alex-Diez/python-tdd-katas
old-katas/sort-kata/day-1.py
Python
mit
2,549
0.002354
# -*- codeing: utf-8 -*- def bubble_sort(to_sort): index = 0 while index < len(to_sort): offset = index while offset > 0 and to_sort[offset - 1] > to_sort[offset]: temp = to_sort[offset] to_sort[offset] = to_sort[offset - 1] to_sort[offset - 1] = temp ...
(e) if e > eq: gt.append(e) return (lt, gt) import unittest class BubbleSortTest(unittest.TestCase): def test_sorts_empty_list(self): self.assertEqual([],
bubble_sort([])) def test_sorts_single_element_list(self): self.assertEqual([1], bubble_sort([1])) def test_sorts_two_elements_sorted_list(self): self.assertEqual([1, 2], bubble_sort([1, 2])) def test_sorts_two_elements_unsorted_list(self): self.assertEqual([1, 2], bubble_sort([2...
alfa-jor/addon
plugin.video.alfa/channels/peliculasyseries.py
Python
gpl-3.0
12,489
0.008091
# -*- coding: utf-8 -*- # -*- Channel PeliculasySeries -*- # -*- Created for Alfa-addon -*- # -*- By the Alfa Develop Group -*- import re import urllib import base64 from channelselector import get_thumb from core import httptools from core import jsontools from core import scrapertools from core import ...
s', action='list_all', thumbnail=get_thumb('all', auto=True), type='movies')) itemlist.append(Item(channel=item.channel, title='Genero', action='section', thumbnail=get_thumb('genres', auto=True), type='movies')) return itemlist def get_source(url): ...
>|\s{2,}', "", data) return data def get_language(lang_data): logger.info() language = [] lang_data = lang_data.replace('language-ES', '').replace('medium', '').replace('serie', '').replace('-','') if 'class' in lang_data: lang_list = scrapertools.find_multiple_matches(lang_data, ...
eventql/eventql
deps/3rdparty/spidermonkey/mozjs/build/subconfigure.py
Python
agpl-3.0
14,193
0.000705
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # This script is used to capture the content of config.status-generated # files and subsequently restore their timestamp...
d msys remangles it even when giving it is already a msys # $PATH. Fortunately, the mangling/demangling is just find for $PATH, so # we can just take the value from the environment. Msys will convert it # back properly when calling subconfigure. input = sys.stdin.read() if input: data = {a: ...
TH'] args = data['args'] else: environ = os.environ args, others = parser.parse_known_args(args) data = { 'target': args.target, 'host': args.host, 'build': args.build, 'args': others, 'shell': shell, 'srcdir': srcdir, 'env': environ,...
mate-desktop/python-mate-desktop
tests/runtests.py
Python
lgpl-2.1
722
0.00554
#!/usr/bin/env python import glob import os impor
t sys import unittest import common if len(sys.argv) > 1: builddir = sys.argv[1] no_import_hooks = True else: builddir = '..' no_import_hooks = False common.run_import_tests(builddir, no_import_hooks) SKIP_FILES = ['common', 'runtests'] dir = os.path.split(os.path.abspath(__file__))[0] os.chdir(dir)...
ES] return files suite = unittest.TestSuite() loader = unittest.TestLoader() for name in gettestnames(): suite.addTest(loader.loadTestsFromName(name)) testRunner = unittest.TextTestRunner() testRunner.run(suite)
Fullbiter/EECS-293
pa12-13/airville/src/passenger.py
Python
gpl-3.0
1,260
0.000794
# Kevin Nash (kjn33) # EECS 293 # Assignment 12 from entity import Entity from random import randint class Passenger(Entity): """ Entities that need to be checked in fol
lowing queueing """ def __init__(self): """ Passengers follow Entity initialization, are randomly given special parameters """ super(Passenger, self).__init__() # 50% chance of being a frequent flyer self.frequent = randint(1, 2) % 2 == 0 # ...
= 0 self.overbook = randint(1, 10) % 10 == 0 self.time = 2 self.calc_time() def __str__(self): """ Represent Passenger by name, ID, and flyer type """ flyer_type = "regular" if self.frequent: flyer_type = "frequent" return "%s %d (%s)" % (self.__...
stivosaurus/rpi-snippets
reference_scripts/basic_pygame.py
Python
unlicense
266
0.015038
import pygame pygame.i
nit() screen = pygame.display.set_mode((
400, 300)) done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True pygame.display.flip()
walterfan/snippets
python/exam/EchoServer.py
Python
apache-2.0
296
0.013514
from twisted.internet import protocol, reactor class Echo(protocol.Protocol): def dataReceived(self, data): self.transport.write(data) class E
cho
Factory(protocol.Factory): def buildProtocol(self, addr): return Echo() reactor.listenTCP(1234, EchoFactory()) reactor.run()
huku-/pyrsistence
tests/em_dict_basic.py
Python
bsd-2-clause
766
0
#!/usr/bin/env python '''em_dict_basic.py - Basic benchmark for external memory dictionary.''' __author__ = 'huku <huku@grhack.net>' import sys import shutil import random import time import util import pyrsistence def main(argv): # Initialize new external memory dictionary. util.msg('Populating external...
util.msg('Done in %d sec.' % (t2 - t1)) #
Close and remove external memory dictionary from disk. em_dict.close() shutil.rmtree(dirname) return 0 if __name__ == '__main__': sys.exit(main(sys.argv)) # EOF
Lyleo/OmniMarkupPreviewer
OmniMarkupLib/Renderers/libs/python2/docutils/parsers/rst/languages/zh_tw.py
Python
mit
5,129
0.001366
# -*- coding: utf-8 -*- # $Id$ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. # New language mappings are welcome. Before doing a new translation, please # read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be # translated for each language...
'superscript', 'sup (translation required)': 'superscript',
'title-reference (translation required)': 'title-reference', 'title (translation required)': 'title-reference', 't (translation required)': 'title-reference', 'pep-reference (translation required)': 'pep-reference', 'pep (translation required)': 'pep-reference', 'rfc-reference (translation require...
tsujamin/digi-approval
src/digiapproval_project/digiapproval_project/apps/digiapproval/migrations/0009_add_last_read_mm_auto.py
Python
gpl-3.0
8,804
0.007383
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding M2M table for field last_read_by on 'Message' m2m_table_name = d...
nKey', [], {'related_name': "'workflow_customer'", 'to': u"orm['digiapproval.Custome
rAccount']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'spec': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['digiapproval.WorkflowSpec']"}), 'state': ('django.db.models.fields.CharField', [], {'default': "'STARTED'", 'max_length':...
stormi/tsunami
src/secondaires/auberge/commandes/auberge/liste.py
Python
bsd-3-clause
3,069
0.000979
# -*-coding:Utf-8 -* # Copyright (c) 2013 LE GOFF Vincent # 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 # lis...
"Chambres | Occupé |\n" msg += en_tete for auberge in auberges: cle = auberge.cle ident = auberge.ident_comptoir nb_chambres = len(auberge
.chambres) pct_occupation = auberge.pct_occupation msg += "\n| {:<15} | {:<25} | {:>8} | {:>5}% |".format( cle, ident, nb_chambres, pct_occupation) msg += "\n" + en_tete personnage << msg else: personnage << "Aucune aub...
waltBB/neutron_read
neutron/agent/metadata_agent.py
Python
apache-2.0
1,584
0
# Copyright 2015 OpenStack Foundation. # # 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...
onfig as metadata_conf from neutron.common import config from neut
ron.common import utils from neutron.openstack.common.cache import cache LOG = logging.getLogger(__name__) def main(): cfg.CONF.register_opts(metadata_conf.UNIX_DOMAIN_METADATA_PROXY_OPTS) cfg.CONF.register_opts(metadata_conf.METADATA_PROXY_HANDLER_OPTS) cache.register_oslo_configs(cfg.CONF) cfg.CONF...
CN-UPB/OpenBarista
components/sandman-pasta/sandman_pasta/sandman_pasta.py
Python
mpl-2.0
14,698
0.004763
""" sandman_pasta reimplements the behaviour of decaf-masta, but instead evaluates all calls to deployable heat templates """ import json from decaf_storage.json_base import StorageJSONEncoder from decaf_storage import Endpoint from decaf_utils_components.base_daemon import daemonize import yaml import time import u...
er(self, datacenter): """ Adds a datacenter entry to the database. :param datacenter: A Datacenter dictionary containing information of the datacenter. :return: The id of the new entry in the datab
ase. """ return int(datacenter.datacenter_id) @Out("datacenter_list", list) def get_datacenters(self): """ Get datacenter entries contained in the database. :return: A list of datacenter entries currently existing in the Masta database. """ return [da...
hal0x2328/neo-python
neo/Storage/Common/CloneCache.py
Python
mit
828
0
from neo.Storage.Common.DataCache import DataCache class CloneCache(DataCache): def __init__(self, innerCache): super(CloneCache, self).__init__() self.innerCache = innerCache def AddInternal(self, key, value): self.innerCache.Add(key, value) def DeleteInternal(self, key): ...
lf.innerCache[key].Clone() def TryGetInternal(self, key): res = self.innerCache.TryGet(key) if res is None: return None else: return r
es.Clone() def UpdateInternal(self, key, value): self.innerCache.GetAndChange(key).FromReplica(value)
bretlowery/snakr
lib/PyOpenGraph/PyOpenGraph.py
Python
bsd-3-clause
3,011
0.016274
#!/usr/bin/env python #Copyright (c) 2010 Gerson Minichiello # #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...
elf.metadata.keys()).intersection(required)) == required: return True else: return False def __str__(
self): return self.metadata['title'] class PyOpenGraphParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.properties = {} def handle_starttag(self, tag, attrs): if tag == 'meta': attrdict = dict(attrs) if attrdict.has_key(...
energyPATHWAYS/energyPATHWAYS
energyPATHWAYS/_obsolete/temp.py
Python
mit
11,014
0.003087
# -*- coding: utf-8 -*- """ Created on Thu Aug 06 13:07:14 2015 @author: Ryan Jones """ class DemandTechnology: def __init__(self, drivers, ID, **kwargs): self.ID = ID self.drivers = drivers for col, att in util.object_att_from_table('DemandTechs', ID): setattr(self, col, att)...
tages) if eff_def == "absolute": decay_df = 1 - (decay_df * getattr(stock.techs[ID], decay)) else: decay_df = 1 - (decay_df * getattr(stock.techs[ref_ID], decay)) eff = eff.transpose() eff = (decay_df.values * eff.values, years, vintages) setattr(stock.te...
_unit' % efficiency, clean_eff_numerator_unit) setattr(stock.techs[ID], 'clean_%s_efficiency_denominator_unit' % efficiency, clean_eff_denominator_unit) def stock_efficiency(self): sd_unit_type = self.service_demand.unit_type if sd_unit_type == 'energy': # ======================...
dyoung418/tensorflow
tensorflow/examples/image_retraining/retrain_test.py
Python
apache-2.0
4,548
0.005057
# Copyright 2015 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...
GetImagePath(self): image_lists = self.dummyImageLists() self.assertEqual('image_dir/somedir/image_one.jpg', retrain.get_image_path( image_lists, 'label_one', 0, 'image_dir', 'training')) self.assertEqual('image_dir/otherdir/image_four.jpg', retrain.get_image_path(image_lists, '...
(self): image_lists = self.dummyImageLists() self.assertEqual('bottleneck_dir/somedir/image_five.jpg_imagenet_v3.txt', retrain.get_bottleneck_path( image_lists, 'label_one', 0, 'bottleneck_dir', 'validation', 'imagenet_v3')) def testShoul...
AsherBond/MondocosmOS
grass_trunk/raster/r.gwflow/valid_calc_excavation.py
Python
agpl-3.0
1,561
0.012172
#!/usr/bin/env python # Shellscript to verify r.gwflow calculation, this calculation is based on # the example at page 167 of the following book: # author = "Kinzelbach, W. and Rausch, R.", # title = "Grundwassermodellierung", # publisher = "Gebr{\"u}der Borntraeger (Berlin, Stuttgart)", # year = "1995" # import sys im...
.run_command("r.mapcalc", expression="recharge=0.000000006") grass.run_command("r.mapcalc", expression="top=20") grass.run_command("r.mapcalc", expression="bottom=0") grass.run_command("r.mapcalc", expression="syield=0.001") grass.run_command("r.mapcalc", expression="null
=0.0") #compute a steady state groundwater flow grass.run_command("r.gwflow", "f", solver="cholesky", top="top", bottom="bottom", phead="phead", \ status="status", hc_x="hydcond", hc_y="hydcond", s="syield", \ recharge="recharge", output="gwresult", dt=864000000000, type="unconfined", budget="water_budget")
courtneypattison/second-response
secondresponse/database/dbconnect.py
Python
mit
483
0.00207
""" Module summary: Variables: db_session - A connection to the farmfinder database. """ from sqlalc
hemy import create_engine from sqlalchemy.orm import sessionmaker from dbsetup import Base ###############################################################
############# # Connect to database and create database session: engine = create_engine("sqlite:///secondresponse/database/sr.db") Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) db_session = DBSession()
youtube/cobalt
third_party/web_platform_tests/tools/wptrunner/wptrunner/wptmanifest/tests/test_static.py
Python
bsd-3-clause
2,576
0.001553
import unittest from cStringIO import StringIO from ..backends import static # There aren't many tests here because it turns out to be way more convenient to # use test_serializer for the majority of cases class TestStatic(unittest.TestCase): def compile(self, input_text, input_data): return static.com...
= 1: value_1 if a == 2: value_2 value_3 """ manifest = self.compile(data, {"a": 2}) self.assertEquals(manifest.get("key"), "value") children = list(item for item in manifest.iterchildren()) self.assertEquals(len(ch
ildren), 1) section = children[0] self.assertEquals(section.name, "Heading 1") self.assertEquals(section.get("other_key"), "value_2") self.assertEquals(section.get("key"), "value") def test_get_1(self): data = """ key: value [Heading 1] other_key: if a == 1: value_1 ...
NoSmartNoMan/algorithm-1
lib/queue.py
Python
gpl-2.0
833
0.002466
#!/usr/bin/env python # -*- coding:UTF-8 __author__ = 'shenshijun' import copy class Queue(object): """ 使用Python的list快速实现一个队列 """ def __init__(self, *arg): super(Queue, self).__init__() self.__queue = list(copy
.copy(arg)) self.__size = len(self.__queue) def enter(self, value): self.__size += 1 self.__queue.append(value) def exit(self): if self.__size <= 0: return None else: value = self.__queue[0] self.__size -= 1 del self.__que...
return self.__size def empty(self): return self.__size <= 0 def __str__(self): return "".join(["Queue(list=", str(self.__queue), ",size=", str(self.__size)])
benoitfragit/VOXGenerator
setup.py
Python
gpl-2.0
1,170
0.026496
from distutils.core import setup setup( name = 'voxgenerator', packages = ['voxgenerator', 'voxgenerator.core', 'voxgenerator.plugin', 'voxgenerator.pipeline', 'voxgenerator.generator', 'voxgenerator.service', 'voxge...
1.0.3', des
cription = 'Vox generator', url = 'https://github.com/benoitfragit/VOXGenerator/tree/master/voxgenerator', author = 'Benoit Franquet', author_email = 'benoitfraubuntu@gmail.com', scripts = ['run_voxgenerator.py', 'run_voxgenerator', 'run_voxgenerator_gui.py'], keywords = ['voice', 'control', 'pocket...
zstackorg/zstack-woodpecker
integrationtest/vm/multiclusters/data_migration/test_migrate_migrated_vm.py
Python
apache-2.0
791
0.006321
''' New Integration Test for migrate between clusters @author: Legion ''' import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_state as test_state import zstackwoodpecker.test_lib as test_lib test_obj_dict = test_
state.TestStateDict() test_stub = test_lib.lib_get_test_stub() data_migration = test_stub.DataMigration() def test(): data_migration.create_vm() data_migration.migrate_vm() test_stu
b.migrate_vm_to_random_host(data_migration.vm) data_migration.vm.check() data_migration.vm.destroy() test_util.test_pass('Migrate migrated VM Test Success') #Will be called only if exception happens in test(). def error_cleanup(): if data_migration.vm: try: data_migration.vm.destro...
django-danceschool/django-danceschool
danceschool/financial/migrations/0002_auto_20170425_0010.py
Python
bsd-3-clause
3,541
0.003106
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-25 00:10 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import filer.fields.file class Migration(migrations.Migration): initial = True dependen...
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='financial.ExpenseCategory'), ), migrations.AddField( model_name='expenseitem', name='event', field=models.ForeignKey(blank=True, help_text='If this item is associated with an Event, en...
migrations.AddField( model_name='expenseitem', name='eventstaffmember', field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='core.EventStaffMember'), ), migrations.AddField( model_name='expenseitem', ...
Jumpscale/jumpscale_core8
lib/JumpScale/tools/objectinspector/ObjectInspector.py
Python
apache-2.0
17,296
0.003296
import os import inspect import types from collections import OrderedDict import json from JumpScale import j # api codes # 4 function with params # 7 ??? # 8 property class Arg: """ Wrapper for argument """ def __init__(self, name, defaultvalue): self.name = name self.defaultval...
is not None and counter > -1: defval = inspected.defaults[counter] if j.data.types.string.check(defval): defval = "'%s'" % defval else: defval = None counter += 1 if param != "self": self.params.appen...
ne: self.params.append(Arg("**%s" % inspected.keywords, None)) self.comments = inspect.getdoc(method) if self.comments is None: self.comments = "" self.comments = j.data.text.strip(self.comments) self.comments = j.data.text.wrap(self.comments, 90) self.l...
afbarnard/barnapy
barnapy/test/numpy_utils_test.py
Python
mit
1,182
0
"""Tests `numpy_utils.py`.""" # Copyright (c) 2021 Aubrey Barnard. # # This is free, open software released under the MIT license. See # `LICENSE` for details. import random import unittest import numpy.random from .. import numpy_utils class NumpyAsStdlibPrngTest(unittest.TestCase): def test_random_floats...
AsStdlibPrng( numpy.random.default_rng(seed)) actual = [wrap_prng.random() for _ in range(n_samples)] self.assertEqual(expected, actual) class NumpyBitGeneratorTest(unittest.TestCase): def test_random_floats(self): seed = 0xdeadbeeffeedcafe n_samples = 10 old_p...
random.Random(seed))) actual = [new_prng.random() for _ in range(n_samples)] self.assertEqual(expected, actual)
TouK/vumi
vumi/tests/test_connectors.py
Python
bsd-3-clause
14,757
0
from twisted.internet.defer import inlineCallbacks, returnValue from vumi.connectors import ( BaseConnector, ReceiveInboundConnector, ReceiveOutboundConnector, IgnoreMessage) from vumi.tests.utils import LogCatcher from vumi.worker import BaseWorker from vumi.message import TransportUserMessage from vumi.middl...
up=False): if worker is None: worker = yield self.worker_hel
per.get_worker(DummyWorker, {}) if connector_name is None: connector_name = "dummy_connector" connector = self.connector_class(worker, connector_name, prefetch_count=prefetch_count, middlewares=middlewares) ...
hpfn/charcoallog
charcoallog/investments/apps.py
Python
gpl-3.0
265
0
from django.apps import AppConfig class InvestmentsConfig(AppConfig
): name = 'charcoallog.investments' def ready(self): # using @receiver decorator # do not optimize
import !!! import charcoallog.investments.signals # noqa: F401
edisonlz/fruit
web_project/base/site-packages/docutils/frontend.py
Python
apache-2.0
33,065
0.000726
# $Id: frontend.py 6154 2009-10-05 19:08:10Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Command-line and common processing for Docutils front-end tools. Exports the following classes: * `OptionParser`: Standard Docutils command-line process...
config_parser=None, config_section=None):
try: codecs.lookup_error(value) except AttributeError: # TODO: remove (only needed prior to Python 2.3) if value not in ('strict', 'ignore', 'replace', 'xmlcharrefreplace'): raise (LookupError( 'unknown encoding error handler: "%s" (choices: ' '"st...
ankutty/OCR-Tesseract
ocr_app.py
Python
apache-2.0
1,764
0.00907
import os from flask import Flask, render_template, request from PIL import Image import sys import pyocr import pyocr.builders import re import json __author__ = 'K_K_N' app = Flask(__name__) APP_ROOT = os.path.dirname(os.path.abspath(__file__)) def ocr(image_file): tools = pyocr.get_available_tools() if l...
s(data) @app.route("/") def index(): return render_template("upload.html") @app.route("/upload", methods=['POST']) def upload(): target = os.path.join(APP_ROOT, 'images/') print(target) if not os.path.isdir(target): os.mkdir(target) for file in request.files.getlist
("file"): print(file) filename = file.filename destination = "/".join([target, filename]) print(destination) file.save(destination) #Return JSON #print txt #file.delete(destination) return ocr(destination) #return json.dumps(txt) if __name__ == ...
shishaochen/TensorFlow-0.8-Win
third_party/grpc/src/python/grpcio/tests/unit/_links/_lonely_invocation_link_test.py
Python
apache-2.0
3,549
0.001691
# Copyright 2015, Google 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: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this softwar
e without specific prior written permission. # # 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 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE CO...
seba-1511/nnexp
examples/mnist_simple.py
Python
apache-2.0
293
0.006826
#!/usr/bin/env python import numpy as np import torch as th from torchvision import datasets, transforms from nnexp import learn
if __name__ == '__main__': dataset = datasets.MNIST('./data', train=True, download=True, transform=transforms.ToTensor()) learn('mnist_simple', data
set)
piratica/ptf
vulnerability-analysis/arachni.py
Python
gpl-3.0
614
0.016287
#!/usr/bin/env python ######################################### # Installation module for arachni ################################
######### # AUTHOR OF MODULE NAME AUTHOR="Nathan Underwood (sai nate)" # DESCRIPTION OF THE MODULE DESCRIPTION="Website / webapp vulnerability scanner." # INSTALLATION TYPE # OPTIONS GIT, SVN, FILE, DOWNLOAD INSTALL_TYPE="GIT" #LOCATION OF THE FILE OR GIT / SVN REPOSITORY REPOSITORY_LOCATION="https://github.com/Ar...
IAN INSTALLS DEBIAN="" #COMMANDS TO RUN AFTER AFTER_COMMANDS=""
SebastianoF/LabelsManager
nilabels/definitions.py
Python
mit
1,452
0.006198
import os __version__ = 'v0.0.7' # update also in setup.py root_dir = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) info = { "name": "NiLabels", "version": __version__, "description": "", "repository": {
"type": "git", "url": "" }, "author": "Sebastiano Ferraris", "dependencies": { # requirements.txt automatically generated using pipreqs "python requirements" : "{0}/requirements.txt".format(root_...
f the same anatomy, or in genreral of different objects that share common features. """ definition_atlas = """ An atlas is the segmentation of the template, obtained averaging with a chosen protocol, the series of segmentations corresponding to the series of images acquisition that generates the template. """ definit...
gisce/primestg
primestg/ziv_service.py
Python
agpl-3.0
959
0.005214
from requests import post import io import base64 class ZivService(object): def __init__(self, cnc_url, user=None, password=None, sync=True): self.cnc_url = cnc_url self.sync = sync self.auth = None if user and password: self.auth = (user,password) def send_cycle(se...
t matter) cycle_filedata -- the file to send, encoded as a base64 string """ filecontent = base64.b64decode(cycle_filedata) url = self.cnc_url + ('/' if (self.cnc_url[-1] != '/') else '') +'cct/cycles/' result = None if self.auth:
result = post(url, files={'file': (filename, filecontent)}, auth=self.auth) else: result = post(url, files={'file': (filename, filecontent)}) return result
rmcintosh/ipy
setup.py
Python
mit
155
0
from setuptools import setup setup( name='ipy', packages=['ipy'], include_package_data=True
, install_requires=[ 'flask'
], )
k0001/python-libmemcached
setup.py
Python
bsd-3-clause
517
0.040619
#!/usr/bin/env python from setuptools import setup, Extension setup( name = "python-libmemcached", version
= "0.17.0", description="python memcached client wrapped on libmemcached", maintainer="subdragon", maintainer_email="subdragon@gmail.com", requires = ['pyrex'], # This assumes that libmemcache is installed with base /usr/local ext_modules=[Extension('cmemcached', ['cmemcached.pyx'], ...
ijat/Hotspot-PUTRA-Auto-login
PyInstaller-3.2/PyInstaller/hooks/hook-sysconfig.py
Python
gpl-3.0
1,238
0.002423
#----------------------------------------------------------------------------- # Copyright (c) 2005-2016, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this s...
em. # TODO Verify that bundling Makefile and pyconfig.h is still required for Python 3. import sysconfig import os from PyInstaller.utils.hooks import relpath_to_config_or_make _CONFIG_H = sysconfig.get_config_h_filename() if hasattr(sysconfig, 'get_makefile_filename'): # sysconfig.get_makefile_filename is missi...
to_config_or_make(_CONFIG_H))] # The Makefile does not exist on all platforms, eg. on Windows if os.path.exists(_MAKEFILE): datas.append((_MAKEFILE, relpath_to_config_or_make(_MAKEFILE)))
mick-d/nipype
nipype/interfaces/fsl/tests/test_auto_Level1Design.py
Python
bsd-3-clause
1,023
0.012708
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from __future__ import unicode_literals from ..model import Level1Design def test_Level1Design_inputs(): input_map = dict(bases=dict(mandatory=True, ), contrasts=dict(), ignore_exception=dict(nohash=True, usedefault=True, ), interscan_i...
assert getattr(inputs.traits()[key], metakey) == value def test_Level1Design_outputs(): output_map = dict(ev_files=dict(), fsf_files=dict(), ) outputs = Level1Design.output_spec() for key, metadata
in list(output_map.items()): for metakey, value in list(metadata.items()): assert getattr(outputs.traits()[key], metakey) == value
jbowens/taboo
wordgen/data-importer.py
Python
mit
1,307
0.007651
#!/usr/bin/env python import sys, json, psycopg2, argparse parser = argparse.ArgumentParser(description='Imports word data into the ta
boo database.') parser.add_argument('--verified', dest='verified', action='store_true', help='include if these words are verified as good quality') parser.add_argument('--source', dest='source', help='include to set the source of these imported words') args = parser.parse_args() CONN_STR = 'dbname=prod user=prod' da...
= '\n'.join(sys.stdin.readlines()) data = json.loads(data_str) conn = psycopg2.connect(CONN_STR) conn.autocommit = True cur = conn.cursor() count = 0 for word in data: try: cur.execute("INSERT INTO words (word, skipped, correct, status, source) VALUES(%s, %s, %s, %s, %s) RETURNING wid", (w...
ponty/psidialogs
psidialogs/examples/choice.py
Python
bsd-2-clause
109
0
import psidialogs s = psidialogs.choice(["1", "2", "3"], "Choose a number!") if s is not None: print(s)
jeremiedecock/pyarm
pyarm/model/muscle/fake_muscle_model.py
Python
mit
1,107
0.00543
# -*- coding: utf-8 -*- # Copyright (c) 2010 Jérémie DECOCK (http://www.jdhp.org) import numpy as np from pyarm import fig class MuscleModel: "Muscle model." # CONSTANTS ############################################################### name = 'Fake' ##################################################...
xlabel='time (s)', ylabel='Command', ylim=[-0.1, 1.1]) #legend=('shoulder +', 'shoulder -', # 'elbow +', 'elbow -')) def compute_torque(self, angles, velocit
ies, command): "Compute the torque" torque = np.zeros(2) if len(command) > 2: torque[0] = (command[0] - command[1]) torque[1] = (command[2] - command[3]) fig.append('command', command[0:4]) else: torque = np.array(command) fig....
regardscitoyens/nosdeputes.fr
batch/hemicycle/parse_hemicycle.py
Python
agpl-3.0
4,977
0.005231
#!/usr/bin/env python # -*- coding: utf8 -*- import sys import bs4 import json import re def xml2json(s): global timestamp timestamp = 0 s = s.replace(u'\xa0', u' ') soup = bs4.BeautifulSoup(s, features="lxml") intervention_vierge = {"intervenant": "", "contexte": ""} intervention_vierge["sourc...
intervenants = i['intervenant'].split(' et ') timestamp += 10 for intervenant in intervenants: i['timestamp'] = str(timestamp) i['intervenant'] = intervenant
print(json.dumps(i)) content_file = sys.argv[1] with open(content_file, encoding='utf-8') as f: xml2json(f.read())
zerothi/sisl
toolbox/siesta/minimizer/_minimize.py
Python
mpl-2.0
13,374
0.002094
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at https://mozilla.org/MPL/2.0/. from hashlib import sha256 from abc import abstractmethod from pathlib import Path from numbers import Real import warni...
"jac"): # transform the jacobian # The jacobian is dM / dx with dx possibly being scaled # S
o here we change multiply by dx / dv result.jac_norm = result.jac.copy() result.jac /= minimizer.reverse_normalize(np.ones(len(minimizer)), with_offset=False) return result class BaseMinimize: # Basic minimizer basically used for figuring out...
philpep/testinfra
testinfra/modules/iptables.py
Python
apache-2.0
2,936
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 th...
Y KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from testinfra.modules.base import InstanceModule class Iptables(InstanceModule): """Test iptables rule exists""" def __init__(self, *args, **kwargs): super().__i...
tos 6 has no support # centos 7 has 1.4 patched self._has_w_argument = None def _iptables_command(self, version): if version == 4: iptables = "iptables" elif version == 6: iptables = "ip6tables" else: raise RuntimeError("Invalid version: %...
VitalLabs/gcloud-python
gcloud/storage/blob.py
Python
apache-2.0
37,138
0
# 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 a...
bucket: The bucket to which this blob belongs. :type chunk_size: integer :param
chunk_size: The size of a chunk of data whenever iterating (1 MB). This must be a multiple of 256 KB per the API specification. """ _chunk_size = None # Default value for each instance. _CHUNK_SIZE_MULTIPLE = 256 * 1024 """Number (256 KB, in bytes) that m...
TWAtGH/pilot2
pilot.py
Python
apache-2.0
4,338
0.001844
#!/usr/bin/env python # 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 # # Authors: # - Mario Lassnig, mario.lassnig@cern.ch, 2016-2017 # - Daniel Dr...
r.info('workflow: %s' % arg
s.workflow) workflow = __import__('pilot.workflow.%s' % args.workflow, globals(), locals(), [args.workflow], -1) return workflow.run(args) if __name__ == '__main__': arg_parser = argparse.ArgumentParser() arg_parser.add_argument('-d', dest='debug', ...
arugifa/website
website/deployment/__init__.py
Python
gpl-3.0
51
0
"""Colle
ction of helpers for online deployment."""
mick-d/nipype
nipype/interfaces/slicer/registration/tests/test_auto_BRAINSResample.py
Python
bsd-3-clause
1,633
0.021433
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from __future__ import unicode_literals from ..brainsresample import BRAINSResample def test_BRAINSResample_inputs(): input_map = dict(args=dict(argstr='%s', ), defaultValue=dict(argstr='--defaultValue %f', ), deformationVolume=dict(argstr='--d...
ception=dict(nohash=True, usedefault=True, ), inputVolume=dict(argstr='--inputVolume %s', ), interpolationMode=dict(argstr='--interpolationMode %s', ), inverseTransform=dict(argstr='--inverseTransform ', ), numberOfThreads=dict(argstr='--numberOfThreads %d', ), outputVolume=d...
l_output=dict(deprecated='1.0.0', nohash=True, ), warpTransform=dict(argstr='--warpTransform %s', ), ) inputs = BRAINSResample.input_spec() for key, metadata in list(input_map.items()): for metakey, value in list(metadata.items()): assert getattr(inputs.traits()[key], me...
RedHatQE/cfme_tests
cfme/fixtures/v2v_fixtures.py
Python
gpl-2.0
22,048
0.002812
import json from collections import namedtuple import fauxfactory import pytest from riggerlib import recursive_update from widgetastic.utils import partial_match from cfme.cloud.provider.openstack import OpenStackProvider from cfme.fixtures.provider import setup_or_skip from cfme.infrastructure.provider.rhevm import...
instantiate(display_name=transformation_method) return tag1, tag2 def set_conversion_instance_for_rhev(appliance, transformation_method, rhev_hosts): """Assigning tags to conversion host. In 5.1
0 rails console commands are run to configure all the rhev hosts. Args: appliance: transformation_method : vddk or ssh as per test requirement rhev_hosts: hosts in rhev to configure for conversion """ for host in rhev_hosts: # set conversion host via rails console #...
RaJiska/Warband-PW-Punishments-Manager
scripts/process_dialogs.py
Python
gpl-3.0
3,283
0.018581
import proces
s_common as pc import process_operations as po import module_dialogs import module_info from header_dialogs import * start_states = [] end_states = [] def compile_dialog_states(processor, dialog_file): global start_states global end_states unique_state_list = ["start", "party_encounter", "prisoner_liberated", "...
d", "close_window", "trade", "exchange_members", "trade_prisoners", "buy_mercenaries", "view_char", "training", "member_chat", "prisoner_chat"] unique_state_usages = [1 for i in unique_state_list] unique_states = dict((k, i) for i, k in enumerate(unique_state_list)) last_index = len(unique_state_list) for...
google/megalista
megalista_dataflow/uploaders/google_ads/customer_match/contact_info_uploader.py
Python
apache-2.0
1,678
0.005364
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
ing permissions and # limitations under the License. import apache_beam as beam import logging from typing import Dict, Any, List from uploaders.google_ads.customer_match.abstract_uploader import GoogleAdsCustomerMatchAbstractUploaderDoFn from uploaders import utils from models.execution import DestinationType, Acco...
f, account_config: AccountConfig, destination_metadata: List[str]) -> Dict[str, Any]: list_name = destination_metadata[0] return { 'membership_status': 'OPEN', 'name': list_name, 'description': 'List created automatically by Megalista', 'membership_life_span': 10000, 'crm_based_use...
shteeven/conference
holder/test/test_appengine_api.py
Python
apache-2.0
1,694
0.002361
import unittest import urllib import logging from google.appengine.ext import testbed from goog
le.appengine.api import urlfetch from conference import ConferenceApi from models import ConferenceForm from models import ConferenceForms from models import ConferenceQueryForm from models import ConferenceQueryForms from protorpc.remote import protojson def init_stubs(tb): tb.init_urlfetch_stub() tb.init_app...
() tb.init_channel_stub() tb.init_datastore_v3_stub() tb.init_files_stub() # tb.init_mail_stub() tb.init_memcache_stub() tb.init_taskqueue_stub(root_path='tests/resources') tb.init_user_stub() tb.init_xmpp_stub() return tb class AppEngineAPITest(unittest.TestCase): def setUp(s...
jeremiah-c-leary/vhdl-style-guide
vsg/tests/architecture/test_rule_016.py
Python
gpl-3.0
2,048
0.003418
import os import unittest from vsg.rules import architecture from vsg import vhdlFile from vsg.tests
import utils sTestDir = os.path.dirname(__file__) lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_016_test_input.vhd')) lExpected_require_blank = [] lExpected_require_blank.append('') utils
.read_file(os.path.join(sTestDir, 'rule_016_test_input.fixed_require_blank.vhd'), lExpected_require_blank) lExpected_no_blank = [] lExpected_no_blank.append('') utils.read_file(os.path.join(sTestDir, 'rule_016_test_input.fixed_no_blank.vhd'), lExpected_no_blank) class test_architecture_rule(unittest.TestCase): ...
starforgelabs/py-korad-serial
koradserial.py
Python
mit
10,720
0.001679
""" Serial communication with Korad KA3xxxP power supplies. The intent is to give easy access to the power supply as Python objects, eliminating the need to know special codes. The object supports the python `with` statement to release the serial port automatically: from koradserial import KoradSerial with KoradSer...
f.debug = debug self.port = serial.Serial(port, 9600, timeout=1) def read_character(self): c = self.port.read(1).decode('ascii') if self.debug:
if len(c) > 0: print("read: {0} = '{1}'".format(ord(c), c)) else: print("read: timeout") return c def read_string(self, fixed_length=None): """ Read a string. It appears that the KoradSerial PSU returns z...
zdlm/conext
manage.py
Python
mit
305
0.003279
#!/usr/bin/env python import os, sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODU
LE", "conext.settings") from django.core.management import execute_from_command_line import conext.startup as startup startup.run()
execute_from_command_line(sys.argv) pass
dslackw/slpkg
slpkg/health.py
Python
gpl-3.0
3,641
0.000824
#!/usr/bin/python3 # -*- coding: utf-8 -*- # health.py file is part of slpkg. # Copyright 2014-2021 Dimitris Zlatanidis <d.zlatanidis@gmail.com> # All rights reserved. # Slpkg is a user-friendly package manager for Slackware installations # https://gitlab.com/dslackw/slpkg # Slpkg is free software: you can redistr...
self.red = _meta_.color["RED"] self.yellow = _meta_.color["YELLOW"] self.endc = _meta_.color["ENDC"] self.msg = Msg
() self.pkg_path = _meta_.pkg_path self.installed = [] self.cn = 0 def packages(self): """Get all installed packages from /var/log/packages/ path """ self.installed = find_package("", self.pkg_path) def check(self, line, pkg): line = line.replace("\n", "...
darthbhyrava/pywikibot-local
pywikibot/daemonize.py
Python
mit
2,017
0
# -*- coding: utf-8 -*- """Module to daemonize the current process on Unix.""" # # (C) Pywikibot team, 2007-2015 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __version__ = '$Id$' import codecs import os import sys is_daemon = False def daemonize(cl...
return else: # Write out the pid path = os.path.basename(sys.argv
[0]) + '.pid' with codecs.open(path, 'w', 'utf-8') as f: f.write(str(pid)) os._exit(0) else: # Exit to return control to the terminal # os._exit to prevent the cleanup to run os._exit(0)
oguayasa/tobii_pro_wrapper
tobii_pro_wrapper/__init__.py
Python
apache-2.0
34
0
from .tobii_p
ro_wrapper
import *
pasinskim/integration
backend-tests/tests/test_devauth_v2.py
Python
apache-2.0
45,297
0.003378
# Copyright 2018 Northern.tech AS # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
auth=(user.name, user
.pwd)) assert r.status_code == 200 utoken = r.text # id data not json priv, pub = util.crypto.rsa_get_keypair() id_data = '{\"mac\": \"foo\"}' body = deviceauth_v2.preauth_req( id_data, pub) r = devauthm.with_auth(utoken)....
mjwtom/swift
test/dedupe/bin/remakerings.py
Python
apache-2.0
1,973
0.003548
#!/home/mjwtom/install/python/bin/python # -*- coding: utf-8 -*- import os import subprocess from nodes import storage_nodes as ips def generate_rings(): print (os.environ["PATH"]) os.environ["PATH"] = '/home/mjwtom/install/python/bin' + ":" + os.environ["PATH"] print (os.environ["PATH"]) dev = 'sdb...
i = 1 for ip in ips: cmd = ['swift-ring-builder', '%s' % builder, 'add', 'r%dz%d-%s:%d/%s' % (i, i, ip, port, dev), '1'] subprocess.call(cmd) i += 1 cmd = ['swift-ring
-builder', '%s' % builder, 'rebalance'] subprocess.call(cmd) if __name__ == '__main__': generate_rings()
pakodekker/oceansar
oceansar/surfaces/balancer.py
Python
gpl-3.0
13,512
0.001998
from mpi4py import MPI import numpy as np from oceansar import utils class OceanSurfaceBalancer(object): """ Ocean Surface Balancer class This class is used to access a surface from different MPI processes so that each one is assigned an azimuth (y) portion of the surface and al...
self.counts, self.displ = utils.balance_elements( self.Ny_full, self.size) self.counts *= self.Nx self.displ *= self.Nx # Process-dependent properties self.Ny = np.int(self.counts[self.rank] / self.Nx) self.y = np.empty(self.Ny, dtype=np.float32) if self....
: y = None self.comm.Scatterv(y, (self.y, MPI.FLOAT), root=self.root) # INITIALIZE SURFACE # Memory allocation (LOW (0) / HIGH (1) dt values) if 'D' in self.compute: self._Dx = (np.empty(2 * int(self.counts[self.rank]), dtype=np.float32). ...
vgrem/SharePointOnline-REST-Python-Client
tests/outlook_case.py
Python
mit
1,082
0.003697
from unittest import TestCase from settings import settings from office365.outlookservices.outlook_client import OutlookClient from office365.runtime.auth.authentication_context import AuthenticationContext class OutlookClientTestCase(TestCase): """SharePoint specific test case base class""" @classmethod ...
settings['tenant']) ctx_auth.acqui
re_token_password_grant(client_credentials=settings['client_credentials'], user_credentials=settings['user_credentials']) cls.client = OutlookClient(ctx_auth)
freedomsponsors/www.freedomsponsors.org
djangoproject/bitcoin_frespo/models.py
Python
agpl-3.0
1,943
0.001544
from django.db import models from django.utils import timezone class ReceiveAddress(models.Model): address = models.CharField(max_length=128, blank=True) available = models.BooleanField(default=True) @classmethod def newAddress(cls, address): receive_address = cls() receive_address.add...
from_address = models.CharField(max_length=128) to_address = models.CharField(max_length=128) value = models.DecimalField(max_digits=16, decimal_places=8) transaction_hash = models.CharField(max_length=128, null=True) status = models.CharField(max_length=30) creationDate = m
odels.DateTimeField() lastChangeDate = models.DateTimeField() CREATED = 'CREATED' SENT = 'SENT' CONFIRMED_IPN = 'CONFIRMED_IPN' CONFIRMED_TRN = 'CONFIRMED_TRN' @classmethod def newMoneySent(cls, from_address, to_address, value): money_sent = cls() money_sent.from_address = ...
ikn/wvoas
game/level.py
Python
gpl-3.0
21,546
0.003063
from math import cos, sin, pi, ceil from random import randint, random, expovariate, shuffle import pygame as pg from pygame import Rect from ext import evthandler as eh from conf import conf from obj import Player, Star from util import ir import ui random0 = lambda: 2 * random() - 1 def tile (screen, img, rect, ...
# clouds: randomise initial positions and velocities self.clouds = cs = [] w, h = conf.RES imgs = self.imgs vx0 = conf.CLOUD_SPEED vy0 = vx0 * conf.CLOUD_VERT_SPEED_RATIO self.cloud_vel = [vx0 * random0(), vy0 * random0()] vx = co...
c in conf.CLOUDS: c_w, c_h = imgs[c].get_size() s = (c_w, c_h) c_w /= 2 c_h /= 2 pos = [randint(-c_w, w - c_w), randint(-c_h, h - c_h)] vel = [vx * random0(), vy * random0()] cs.append((pos, vel, s)) ...