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
ecolitan/fatics
venv/lib/python2.7/site-packages/twisted/names/test/test_cache.py
Python
agpl-3.0
4,915
0.001831
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.names.cache}. """ from __future__ import division, absolute_import import time from zope.interface.verify import verifyClass from twisted.trial import unittest from twisted.names import dns, cache from twisted.internet...
self.assertEquals(result[0][0].name.name, b"example.com") return c.lookupAddress(b"example.com").addCallback(cbLookup) def test_cachedResultExpires(self): """ Once the TTL has been exceeded, the result is removed from the cache. """
r = ([dns.RRHeader(b"example.com", dns.A, dns.IN, 60, dns.Record_A("127.0.0.1", 60))], [dns.RRHeader(b"example.com", dns.A, dns.IN, 50, dns.Record_A("127.0.0.1", 50))], [dns.RRHeader(b"example.com", dns.A, dns.IN, 40, ...
ppolewicz/qBittorrent
src/searchengine/nova/engines/torrentz.py
Python
gpl-2.0
5,199
0.003078
#VERSION: 2.14 #AUTHORS: Diego de las Heras (diegodelasheras@gmail.com) # 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 ...
f self.td_counter == 0: if 'name' not in self.current_item: self.current_item['name'] = '' self.current_item['name'] += data elif self.td_counter == 4: if 'size' not in self.current_item: self.current_item['size'] = data...
em['seeds'] = data.strip().replace(',', '') elif self.td_counter == 6: if 'leech' not in self.current_item: self.current_item['leech'] = data.strip().replace(',', '') # display item self.td_counter = None self.current_item[...
ctogle/dilapidator
src/dilap/topology/wiregraph.py
Python
mit
7,123
0.021059
import dilap.core.base as db import dilap.core.plotting as dtl import matplotlib.pyplot as plt import pdb ############################################################################### # wire graph class (purely topological) # # wire graph is a simple data structure # for vertices and edges connecting the...
self.vcnt): v = self.vs[vx] if v is None:continue for ox in self.orings[vx]: r = self.rings[vx][ox] rx,rkws = r if rx in unfn:
#lp = self.loop(vx,ox,'ccw') lp = self.loop(vx,ox,d) lpk = tuple(set(lp)) #if not lpk in loops: if newloopkey(lpk,loops): loops[lpk] = lp unfn.remove(rx) else:co...
hkhamm/proj7-freetimes
busy_times.py
Python
artistic-2.0
6,156
0
import arrow from dateutil import tz import flask import CONFIG START_TIME = CONFIG.START_TIME END_TIME = CONFIG.END_TIME def get_busy_times(events): """ Gets a list of busy times calculated from the list of events. :param events: a list of calendar events. :return: a list of busy times in ascending...
t) day_start = event_start.replace(hour=START_TIME, minute=0) day_end = event_end.replace(hour=END_TIME, minute=0) # all day events that either begin or end in the time interval if ((begin_date <= event_start <= end_date or begin_date <= event_end <= end_date) and ...
event['start']['dateTime'] = begin_date.isoformat() else: event['start']['dateTime'] = day_start.isoformat() if event_end > end_date: event['end']['dateTime'] = end_date.isoformat() else: event['end']['dateTime'] = day_end.rep...
CMPUT-466-551-ML-Project/NILM-Project
nilm/preprocess.py
Python
gpl-2.0
4,748
0.000632
""" A collection of data pre-processing algorithms """ import numpy as np from scipy.optimize import minimize from nilm.evaluation import mean_squared_error def solve_constant_energy(aggregated, device_activations): """ Invert the indicator matrix, solving for the constant energy of each device. We ret...
d the mean squared error. """ def objective(power, total, matrix): """Objective function for the mi
nimization.""" return np.sum((total - np.dot(matrix, power)) ** 2) matrix = np.column_stack(device_activations) p0 = np.zeros(matrix.shape[1]) bounds = [(0, np.inf)] * matrix.shape[1] solution = minimize(objective, p0, args=(aggregated, matrix), method='SLSQP', bounds=...
takeshineshiro/nova
nova/tests/functional/v3/test_keypairs.py
Python
apache-2.0
9,503
0.000105
# Copyright 2012 Nebula, Inc. # Copyright 2013 IBM Corp. # # 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...
not necessarily the key name. return key_name def test_keypairs_import_key_post(self): public_key = fake_crypto.
get_ssh_public_key() self._check_keypairs_import_key_post(public_key) def _check_keypairs_import_key_post(self, public_key, **kwargs): # Get api sample of key pairs post to import user's key. key_name = 'keypair-' + str(uuid.uuid4()) subs = { 'keypair_name': key_name, ...
nirmeshk/oh-mainline
mysite/bugsets/tests.py
Python
agpl-3.0
19,396
0.000155
# -*- coding: utf-8 -*- from __future__ import absolute_import # vim: set ai et ts=4 sw=4: # This file is part of OpenHatch. # Copyright (C) 2014 Elana Hashman # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Fr...
models.BugSet.objects.create(name="best event") url = reverse(mysite.bugsets.views.main_index) response = client.get(url) self.assertEqual(200, response.status_code)
self.assertContains(response, s.get_edit_url()) self.assertNotContains(response, 'if you want to create or edit a bug set.') class BasicBugsetListViewTests(TwillTests): def test_bugset_listview_load(self): s = mysite.bugsets.models.BugSet.objects.create(name="...
4dn-dcic/tibanna
awsf/aws_decode_run_json.py
Python
mit
12,965
0.004165
#!/usr/bin/python import json import sys import re downloadlist_filename = "download_command_list.txt" mountlist_filename = "mount_command_list.txt" input_yml_filename = "inputs.yml" env_filename = "env_command_list.txt" INPUT_DIR = "/data1/input" # data are downloaded to this directory INPUT_MOUNT_DIR_PREFIX = "/dat...
NPUT_DIR + "/%s" data_bucket = v["dir"] profile = v.get("profile", '') profile_flag = "--profile " + profile if profile else '' path1 = v["path"] rename1 = v.get("rename", None) unzip = v.get("unzip", None) i...
th1 if isinstance(path1, list): for path2, rename2 in zip(path1, rename1): if isinstance(path2, list): for path3, rename3 in zip(path2, rename2): if isinstance(path3, list): ...
DemocracyClub/EveryElection
every_election/apps/elections/migrations/0019_auto_20170110_1329.py
Python
bsd-3-clause
468
0
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-01-10 13:29 from __future__ import unicode_literals from django.db import mi
gration
s, models class Migration(migrations.Migration): dependencies = [("elections", "0018_election_group_type")] operations = [ migrations.AlterField( model_name="election", name="group_type", field=models.CharField(blank=True, max_length=100, null=True), ) ...
google/ml-fairness-gym
spaces/multinomial_test.py
Python
apache-2.0
3,523
0.002838
# coding=utf-8 # Copyright 2022 The ML Fairness Gym Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
vector)) def test_contains_incorrect_sum(
self): # check vector with incorrect sum is not contained not_contained_vector = np.asarray([3, 3, 3, 3, 3, 3], dtype=np.uint32) self.assertFalse(self.multinomial_space.contains(not_contained_vector)) def test_contains_incorrect_dtype(self): # check vector with wrong dtype is not contained not_co...
IgorWang/LM4paper
mixlm/visualize.py
Python
gpl-3.0
5,856
0.001195
# -*- coding: utf-8 -*- # Project : LM4paper # Created by igor on 17-3-14 import os import sys import time import json import numpy as np import tensorflow as tf from tensorflow.contrib.tensorboard.plugins import projector from mixlm.lm_train import * from mixlm.clstmdnn import CLSTMDNN from bmlm.common import Check...
feed_dict={self.mo
del.char_x: x}) # print(self.model.char_embedding) return vector[0][0][0] def get_word_embedding(self, word): id = self.word_vocab.get_id(word) x = np.zeros(shape=(4, 20)) x[:, :] = id vector = self.sess.run([self.model.word_embedding.outputs], ...
Nicola17/term2048-AI
tests/test_ui.py
Python
mit
3,717
0.001614
# -*- coding: UTF-8 -*- try: import unittest2 as unittest except ImportError: import unittest import sys import os import helpers from term2048 import ui try: import argparse as _argparse except ImportError: _argparse = None _argv = sys.argv _os_system = os.system class TestUI(unittest.TestCase): ...
None def fake_exit(s): self.exit_status = s raise helpers.FakeExit() self.exit = sys.exit sys.exit = fake_exit sys.argv = _argv self.stdout = sys.stdout self.output = {} sys.stdout = helpers.DevNull(self.output) def tearDown(self): ...
pass else: self.assertFalse(True, "should exit after printing the version") self.assertEqual(self.exit_status, 0) def test_parse_args_no_args(self): sys.argv = ['term2048'] args = ui.parse_cli_args() self.assertEqual(args, { 'version': False, ...
FFMG/myoddweb.piger
monitor/api/python/Python-3.7.2/Lib/test/test_urllib2net.py
Python
gpl-2.0
12,710
0.002754
import unittest from test import support from test.test_urllib2 import sanepathname2url import os import socket import urllib.error import urllib.request import sys support.requires("network") TIMEOUT = 60 # seconds def _retry_thrice(func, exc, *args, **kwargs): for i in range(3): try: ret...
geturl(), "http://www.pythontest.net/elsewhere/#frag") def test_custom_headers(self): url = "http://www.example.com" with support.transient_internet(url)
: opener = urllib.request.build_opener() request = urllib.request.Request(url) self.assertFalse(request.header_items()) opener.open(request) self.assertTrue(request.header_items()) self.assertTrue(request.has_header('User-agent')) reque...
overxfl0w/Inference-Engine
BaseRules.py
Python
gpl-2.0
876
0.045662
#!/usr/bin/env python # -*- coding: utf-8 -*- from BaseReality import BaseReality import re class BaseRules(BaseReality): def _get_rule_precond(self,i): try: return re.match("^(.*)\s?->.*$",self._get_data(i)).groups()[0] except TypeError as te: print "Error con el parametro a la expresion regular de extra...
e_effect(self,i): try: return re.match(".*->\s?(.*)$",self._get_data(i)).groups()[0] except TypeError as te: print "Error con el parametro a la expresion regular de la accion de precondicion de una regla" except: print "Error con la expresion regular" def _extract_set_of_preconditions(self,i): retur...
tconditions(self,i): return self._get_rule_effect(i).split("^")
Mec-iS/semantic-data-chronos
appengine_config.py
Python
apache-2.0
441
0.004535
__author__ = 'lorenzo' # # http://stackoverflow.com/a/29681061/2536357 # from google.appengine.ext import vendor # Add any libraries installed in the "lib" folder. vendor.add('lib') # run from the project root: # pip inst
all -t lib -r requirements.txt # Uncomment if appstat is on #def webapp_add_wsgi_middleware(app): # from go
ogle.appengine.ext.appstats import recording # app = recording.appstats_wsgi_middleware(app) # return app
knuu/nlp100
chap06/56.py
Python
mit
765
0.005229
""" import xml.etree.ElementTree as ET tree = ET.parse('nlp.xml') root = tree.getroot() sentences = [] for sentence in root.iter('sentence'): s = [word.text for word in sentence.iter('word')] if s: sentences.append(s) for mention in root.iter('mention'): mention = {m.tag: m.text for m in mention.findall('*'...
ord.text for token in soup.find_all('to
ken') if token.NER.text == 'PERSON'] print(*persons, sep='\n')
mikel-egana-aranguren/SADI-Galaxy-Docker
galaxy-dist/eggs/mercurial-2.2.3-py2.7-linux-x86_64-ucs4.egg/mercurial/fileset.py
Python
gpl-3.0
13,728
0.004589
# fileset.py - file set queries for mercurial # # Copyright 2010 Matt Mackall <mpm@selenic.com> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. import parser, error, util, merge, re from i18n import _ elements = { "(": (20, (...
symlink. """ # i18n: "symlink" is a keyword getargs(x, 0, 0,
_("symlink takes no arguments")) return [f for f in mctx.existing() if mctx.ctx.flags(f) == 'l'] def resolved(mctx, x): """``resolved()`` File that is marked resolved according to the resolve state. """ # i18n: "resolved" is a keyword getargs(x, 0, 0, _("resolved takes no arguments")) if mc...
barmassimo/MIDI-Notebook
src/midi_notebook/midi_notebook_context.py
Python
gpl-3.0
18,879
0.000742
# MIDI-Notebook - A prototypal MIDI monitor, looper, and recorder written in Python. # Copyright (C) 2014 Massimo Barbieri - http://www.massimobarbieri.it # # 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 F...
ut_port = None self._output_port = None self.midi_out = None self.n_loops = 4 self.loops = [Loop() for n in range(self.n_loops)] self.last_toggle_loop = [0 for n in range(self.n_loops)] self.loop_sync = threading.Condition() self.last_loop_sync = None se...
reads = [None for n in range(self.n_loops)] def clean_all(self): self.last_event = time.time() self.messages_captured = [] for n, l in enumerate(self.loops): self.clean_loop(n) if not self.loop_threads[n] is None: self.loop_threads[n].force_exit() ...
AndrewAnnex/SpiceyPy
src/spiceypy/spiceypy.py
Python
mit
503,480
0.000449
""" The MIT License (MIT) Copyright (c) [2015-2021] [Andrew Annex] 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, modif...
SpiceEKAttDsc, SpiceEKSegSum, ) __author__ = "AndrewAnnex" ################################################################################ OptionalInt = Optional[int] _default_len_out = 256 _SPICE_EK_MAXQSEL = 100 # Twice the 50 in gcc-linux-64 _SPICE_EK_EKRCEX_ROOM_DEFAULT = 100 # Enough? def warn_depr...
None: # pragma: no cover keys = list(kwargs.keys()) values = list(kwargs.values()) if any(values): varnames = ", ".join(keys) warnings.warn( f"Specifying any of: {varnames} will be deprecated as of SpiceyPy 5.0.0", DeprecationWarning, stacklevel=2, ...
google/grr
grr/server/grr_response_server/gui/api_plugins/vfs_test.py
Python
apache-2.0
44,205
0.004594
#!/usr/bin/env python # -*- encoding: utf-8 -*- """This modules contains tests for VFS API handlers.""" import binascii import io import os from unittest import mock import zipfile from absl import app from grr_response_core.lib import factory from grr_response_core.lib import rdfvalue from grr_response_core.lib.rdf...
on.From(1, rdfvalue.DAYS) time_2 = time_1 + rdfvalue.Duration.From(1, rdfvalue.DAYS) # TODO(hanuszczak): This fu
nction not only contains a lot of code duplication # but is also a duplication with `gui_test_lib.CreateFileVersion(s)`. This # should be refactored in the near future. def CreateFileVersions(self, client_id, file_path): """Add a new version for a file.""" path_type, components = rdf_objects.ParseCategori...
raildo/python-keystoneclient
python-keystoneclient-0.4.1.7.gdca1d42/keystoneclient/openstack/common/jsonutils.py
Python
apache-2.0
6,464
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may #...
> # 26164 <type 'list'> # 6491 <type 'float'> # 283 <type 'tuple'> # 19 <type 'long'> if isinstance(value, _simple_types): return value if isinstance(value, datetime.datetime)
: if convert_datetime: return timeutils.strtime(value) else: return value # value of itertools.count doesn't get caught by nasty_type_tests # and results in infinite loop when list(value) is called. if type(value) == itertools.count: return six.text_type(valu...
jkimbo/freight
freight/vcs/base.py
Python
apache-2.0
1,988
0
from __future__ import absolute_import, unicode_literals import os import os.path from freight.constants import PROJECT_ROOT from freight.exceptions import CommandError class UnknownRevision(CommandError): pass class Vcs(object): ssh_connect_path = os.path.join(PROJECT_ROOT, 'bin', 'ssh-connect') def...
default(key, value) env.
setdefault('FREIGHT_SSH_REPO', self.url) kwargs['env'] = env if capture: handler = workspace.capture else: handler = workspace.run rv = handler(command, *args, **kwargs) if isinstance(rv, basestring): return rv.strip() return rv ...
anton44eg/fixturegen
fixturegen/generator.py
Python
mit
2,782
0
from __future__ import absolute_import from functools import partial from pkg_resources import Requirement, resource_filename import re from mako.template import Template from sqlalchemy import MetaData, select, create_engine, text from sqlalchemy.exc import ArgumentError from fixturegen.exc import ( NoSuchTable,...
= '{0}_{1}'.format(table_name, '_' .join((str(row[i]).replace('-', '_') for i in naming_column_ids))) if valid_class_name_re.match(class_name): return class_name raise NonValidRowClassName(class_name) def generate(table, columns...
ne): if not row_naming_columns: try: naming_column_ids = [columns.index('id')] except ValueError: raise WrongNamingColumn() else: try: naming_column_ids = [columns.index(column_name) for column_name in row_naming_column...
peschkaj/adventofcode
python/09.py
Python
mit
1,075
0.003721
import pprint from itertools import permutations places = set() route_table = dict() filename = '09.txt' def add_to_route_table(start, dest, distance): places.add(start) places.add(dest) if not start in route_table: route_table[start] = dict() if not dest in route_table[start]: route_...
ath[1:]): current_length += route_table[source][dest] if not shortest_distan
ce or shortest_distance > current_length: shortest_distance = current_length if not longest_distance or longest_distance < current_length: longest_distance = current_length print shortest_distance, longest_distance
HewlettPackard/python-proliant-sdk
examples/Redfish/ex14_sessions.py
Python
apache-2.0
2,690
0.012639
# Copyright 2016 Hewlett Packard Enterprise Development LP # # 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 requ...
S" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import sys import urlparse from _redfishobject import
RedfishObject from redfish.rest.v1 import ServerDownOrUnreachableError def ex14_sessions(redfishobj, login_account, login_password): sys.stdout.write("\nEXAMPLE 14: Create/Use/Delete a user session\n") new_session = {"UserName": login_account, "Password": login_password} response = redfishobj.redfis...
jasonkuster/incubator-beam
sdks/python/apache_beam/examples/snippets/snippets_test.py
Python
apache-2.0
28,632
0.005204
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
m.FlatMap(filter_using_length, lower_bound=2, upper_bound=pvalue.AsSingleton(
avg_word_len)) # [END model_pardo_side_input] beam.assert_that(small_words, beam.equal_to(['a', 'bb', 'ccc'])) beam.assert_that(larger_than_average, beam.equal_to(['ccc', 'dddd']), label='larger_than_average') beam.assert_that(small_but_nontrivial, beam.equal_to(['bb']), ...
ereOn/loaded
loaded/main.py
Python
lgpl-3.0
1,773
0.000564
""" Scripts. """ import click import logging import platform import six from tornado.ioloop import ( IOLoop, PeriodicCallback, ) from .server import agent_application @click.group() @click.option('-d', '--debug/--no-debug', default=False) @click.pass_context def main_loaded(ctx, debug): """ Loaded ...
stem() == 'Windows': # On Windows, select call can't be interrupted by
SIGINT so we add # a periodic callback that will wake-up the event loop and raise # the KeyboardInterrupt if needed. periodic_callback = PeriodicCallback(lambda: None, 100) periodic_callback.start() try: IOLoop.current().start() except KeyboardInterrupt as ex: cl...
webpadonline/webpadonline.github.io
build.py
Python
bsd-3-clause
7,419
0.011187
#!/usr/bin/python3 import json import os import re import shutil import subprocess import sys import urllib.parse import urllib.request APP_NAME = 'Text' IS_APP = True BASE_DIR = os.path.dirname(sys.argv[0]) SOURCE_DIR = BASE_DIR BUILD_DIR = os.path.join(BASE_DIR, 'build') FILES = [ 'index.html...
_NAME = False COMPILATION_LEVEL = 'SIMPLE_OPTIMIZATIONS' BACKGROUND_COMPILATION_LEVEL = 'ADVANCED_OPTIMIZATIONS' debug_build = False def parse_command_line(): global debug_build for option in sys.argv[1:]: if option == '-d': debug_build = True else: raise Exception('Unknown comma...
ir(path): print('Deleting', path) shutil.rmtree(path, ignore_errors=True) elif os.path.isfile(path): print('Deleting', path) os.remove(path) def copy_files(src, dst, files): for f in files: print('Copying', f) full_path = os.path.join(src, f) target_path = os.path...
mpi4py/mpi4py
demo/mandelbrot/mandelbrot-seq.py
Python
bsd-2-clause
849
0.005889
import numpy as np import time tic = time.time
() x1 = -2.0 x2 = 1.0 y1 = -1.0 y2 = 1.0 w = 150 h = 100 maxit = 127 def mandelbrot(x, y, maxit): c = x + y*1j z = 0 + 0j it = 0 while abs(z) < 2 and it < maxit: z = z**2 + c it += 1 return it dx = (x2 - x1) / w dy = (y2 - y1) / h C = np.empty([h, w], dtype='i') for k in np.ar...
np.arange(w): x = x1 + j * dx C[k, j] = mandelbrot(x, y, maxit) M = C toc = time.time() print('wall clock time: %8.2f seconds' % (toc-tic)) # eye candy (requires matplotlib) if 1: try: from matplotlib import pyplot as plt plt.imshow(M, aspect='equal') try: plt...
prusnak/bitcoin
test/functional/p2p_unrequested_blocks.py
Python
mit
13,045
0.002606
#!/usr/bin/env python3 # Copyright (c) 2015-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test processing of unrequested blocks. Setup: two nodes, node0 + node1, not connected to each other. N...
ll should be processed but # the last (height-too-high) on node (as long as it is not missing any headers) tip = block_h3 all_blocks = [] for i in range(288): next_block = create_block(tip.sha256, create_coinbase(i + 4), tip.nTime+1) next_block.solve() ...
ock(all_blocks[1])) assert_raises_rpc_error(-5, "Block not found", self.nodes[0].getblock, all_blocks[1].hash) assert_raises_rpc_error(-5, "Block not found", self.nodes[0].getblockheader, all_blocks[1].hash) # The block at height 5 should be accepted if we provide the missing header, though ...
plotly/python-api
packages/python/plotly/plotly/validators/layout/scene/zaxis/_color.py
Python
mit
446
0.002242
import _plotly_utils.basevalidators class ColorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__(self, plotly_name="color", parent_name="layout.scene.zaxis", **kwargs):
super(ColorValidator, self).__init__( plotly_name=plotly_name,
parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), role=kwargs.pop("role", "style"), **kwargs )
WikiWatershed/model-my-watershed
deployment/cfn/tile_delivery_network.py
Python
apache-2.0
6,804
0
from troposphere import ( Parameter, Ref, Output, Tags, GetAtt, Join, cloudfront as cf, route53 as r53, s3 ) from cfn.utils.constants import ( AMAZON_S3_HOSTED_ZONE_ID, AMAZON_S3_WEBSITE_DOMAIN, ) from majorkirby import StackNode class TileDeliveryNetwork(StackNode): ...
], DefaultCacheBehavior=cf.DefaultCacheBehavior( ForwardedValues=cf.ForwardedValues(QueryString=True), TargetOriginId='tileOriginId', ViewerProtocolPolicy='allow-all' ), Enabled=True ) ))...
bution, green_tile_distribution def create_s3_resources(self): s3_bucket = self.add_resource(s3.Bucket( 's3TileCacheBucket', BucketName=Join('.', ['tile-cache', Ref(self.public_hosted_zone_name)]), AccessControl=s3.PublicRead, ...
remico/vision_0
goods2excel.py
Python
gpl-3.0
5,421
0.001301
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Parse a goods database table and create an ms excel's workbook from it """ __author__ = 'remico' from xml.etree.ElementTree import ElementTree from abc import ABC, abstractmethod from bs4 import BeautifulSoup, Tag import xlsxwriter import sys, os, glob class IBui...
D1', 'Розничная цена') self.sheet.write_string('E1', 'Размеры') self.sheet.set_column('A:A', 50) self.sheet.set_column('B:B', 80) self.s
heet.set_column('C:C', 20) self.sheet.set_column('D:D', 20) self.sheet.set_column('E:E', 20) self.sheet.set_row(0, 25, header_format) self.sheet.set_default_row(35) def get_result(self): self.book.close() print("'%s' created" % self.filename) return self.boo...
ycl2045/nova-master
nova/tests/virt/libvirt/test_imagebackend.py
Python
apache-2.0
26,862
0.000261
# Copyright 2012 Grid Dynamics # 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...
ase, self).setUp() self.stubs.Set(imagebackend.Raw, 'correct_format', lambda _: None) def
prepare_mocks(self): fn = self.mox.CreateMockAnything() self.mox.StubOutWithMock(imagebackend.utils.synchronized, '__call__') self.mox.StubOutWithMock(imagebackend.libvirt_utils, 'copy_image') self.mox.StubOutWithMock(imagebackend.disk, 'extend') ...
justinasjaronis/hpn
united_geonames/migrations/0015_auto__add_field_geonamesmatchinglogmatchedplaces_remark.py
Python
gpl-3.0
9,334
0.007821
# encoding: 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 'GeoNamesMatchingLogMatchedPlaces.remark' db.add_column('united_geonames_geonamesmatchinglo...
t_name': 'UnitedGeoName'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'main_name': ('django.db.models.fields.CharField', [], {'max_length': '300'})
}, 'united_geonames.unitedgeonamesynonim': { 'Meta': {'object_name': 'UnitedGeoNameSynonim'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']", 'null': 'True'}), 'coordinates': ('django.contrib.gis.db.models.fiel...
diraol/trilhasp
trilhasp/trilhasp/wsgi.py
Python
agpl-3.0
391
0.002558
""" WSGI config for trilhasp project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https:
//docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os os.envir
on.setdefault("DJANGO_SETTINGS_MODULE", "trilhasp.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
mlosch/nnadapter
emu/keras.py
Python
mit
8,953
0.002904
from __future__ import absolute_import import os import numpy as np from emu.nnadapter import NNAdapter from keras.models import model_from_json, model_from_yaml, Model, Sequential from keras import applications from keras import backend from collections import OrderedDict from emu.docutil import doc_inherit imagene...
""" Preprocess a list of imag
es to be used with the neural network. Parameters ---------- listofimages : List of strings or list of ndarrays, shape (Height, Width, Channels) The list may contain image filepaths and image ndarrays. For ndarrays, the shape (Height, Width, Channels) has to conform with...
jobiols/odoo-argentina
l10n_ar_afipws_fe/models/res_currency.py
Python
agpl-3.0
3,043
0
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in module root # directory ############################################################################## from openerp import models, api, _ from openerp.ex...
cy_rate()[1]) @api.multi # def get_pyafipws_currency_rate(self, afip_ws='wsfex', company=False): def get_pyafipws_currency_rate(self, afip_ws='wsfe', company=False): self.ensure_one() # if not company, then we search one that uses argentinian localization if not company: ...
rError(_( 'No company found using argentinian localization')) if not self.afip_code: raise UserError(_('No AFIP code for currency %s') % self.name) ws = company.get_connection(afip_ws).connect() # deberia implementarse igual para wsbfe pero nos da un error ...
shiquanwang/numba
numba/tests/test_mandelbrot.py
Python
bsd-2-clause
1,319
0.002274
""" >>> image = np.zeros((50, 75), dtype=np.uint8) >>> numpy_image = image.copy() >>> image = create_fractal(-2.0, 1.0, -1.0, 1.0, image, 20) >>> numpy_image = create_fractal.py_func(-2.0, 1.0, -1.0, 1.0, numpy_image, 20) >>> assert np.allclose(image, numpy_image) """ from numba import * import numpy as np @autojit(n...
e.shape[1] pixel_size_x = (max_x - min_x) / width pixel_size_y = (max_y - min_y) / height for x in range(width): real = mi
n_x + x * pixel_size_x for y in range(height): imag = min_y + y * pixel_size_y color = mandel(real, imag, iters) image[y, x] = color return image if __name__ == "__main__": import numba numba.testing.testmod()
asadoughi/quark
quark/db/migration/alembic/versions/3b467be51e43_composite_primary_key_port_ip_.py
Python
apache-2.0
3,036
0.001318
"""composite primary key port ip association Revision ID: 3b467be51e43 Revises: 26e984b48a0d Create Date: 2014-10-09 15:42:58.104964 """ # revision identifiers, used by Alembic. revision = '3b467be51e43' down_revision = '26e984b48a0d' import contextlib import itertools from alembic import op import sqlalchemy as s...
ions", "quark_port_ip_address_associations", ['port_id', 'ip
_address_id']) def downgrade(): metadata = sa.MetaData(bind=op.get_bind()) table = sa.Table('quark_port_ip_address_associations', metadata, autoload=True) # NOTE(thomasem): Unfortunately we cannot remove primary keys for columns # that have a ForeignKeyConstraint defined. So, we c...
2nd47/UofT-Projects
CSC369/Virtual Memory/traceprogs/fastslim.py
Python
gpl-2.0
2,771
0.018766
#!/usr/bin/python # This program processes an address trace generated by the Valgrind lackey tool # to create a reduced trace according to the Fastslim-Demand algorithm # described in "
FastSlim: prefetch-safe trace reduction for I/O cache # simulation" by Wei Jin, Xiaobai Sun, and Jeffrey S. Chase in ACM Transactions # on Modeling and Computer Simulation, Vol. 11, No. 2 (April 2001), # pages 125-160. http://doi.acm.org/10.1145/384169.384170 import fileinput import sys import argparse from
operator import attrgetter class TraceItem(object): def __init__(self, reftype, pg, tstamp): self.reftype = reftype self.pg = pg self.tstamp = tstamp self.marked = False def __eq__(self, other): return self.pg == other.pg def __repr__(self): return self.reftype + " " + forma...
addition-it-solutions/project-all
addons/account_analytic_default/__openerp__.py
Python
agpl-3.0
1,764
0.001134
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is fre
e software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is
distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License ...
lukius/ptc
ptc/cblock.py
Python
mit
5,507
0.005266
import threading from buffer import DataBuffer from seqnum import SequenceNumber class PTCControlBlock(object): def __init__(self, send_seq, receive_seq, send_window, receive_window): self.snd_wnd = send_window self.snd_nxt = send_seq.clone() self.snd_una = send_seq.clone() s...
irst_ok = SequenceNumber.a_leq_b_leq_c(self.rcv_nxt, first_byte, self.rcv_nxt+
self.rcv_wnd) last_ok = SequenceNumber.a_leq_b_leq_c(self.rcv_nxt, last_byte, self.rcv_nxt+self.rcv_wnd) return last_byte >= first_byte and (first_ok or last_ok) def should_update_window(self, ack_number): # TODO: add tests for this. ...
plxaye/chromium
src/chrome/test/functional/media_stream_infobar.py
Python
apache-2.0
3,390
0.00295
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import pyauto_functional import pyauto import webrtc_test_base class MediaStreamInfobarTest(webrtc_test_base.WebrtcTestBase): "...
or-1', self._TestGetUserMedia(with_action='cancel')) def testDismissingUserMedia(self): """Dismiss should be treated just like deny, which is described above.""" # Error 1 = Perm
ission denied self.assertEquals('failed-with-error-1', self._TestGetUserMedia(with_action='dismiss')) def testConsecutiveGetUserMediaCalls(self): """Ensures we deal appropriately with several consecutive requests.""" self.assertEquals('failed-with-error-1', sel...
misterwindupbird/IBO
ego/utils/performance.py
Python
mit
2,167
0.00323
#!/usr/bin/env python # encoding: utf-8 # Copyright (C) 2010, 2011 by Eric Brochu # # 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 rig...
0.01, maxiter=10, **kwargs): """ given a GP, find the max and argmax of G_delta, the confidence-bounded prediction of the max of the response surface "
"" assert testfunc.maximize mb = MuBound(GP, delta) _, optx = cdirect(mb.objective, testfunc.bounds, maxiter=maxiter, **kwargs) opt = max(testfunc.f(optx), firstY) return (opt-firstY) / (-testfunc.minimum-firstY)
UnionGospelMission/UGM-Database
Sandbox/SecureDict.py
Python
gpl-3.0
1,147
0.015693
def interactiveConsole(a,b=None): ''' Useful function for debugging Placing interactiveConsole(locals(),globals()) into code will drop into an interactive console when run '''
import code d = {} if b: d.update(b) d.update(a) c=code.InteractiveConsole(locals=d) c.interact() class SecureDict(object): __slots__ = ('__items__',) def __init__(self, *a, **kw): self.__items__ = dict(*a, **kw)
def getItem(self, item, default = None): if default!=None: return self.__items__.get(item,default) try: return self.__items__[item] except KeyError: raise KeyError('Key Error: %s'%item) def setItem(self, item, value): self.__items__[item] = va...
JonathanAlvarado/bioclimatica
nom020/nom/forms.py
Python
mit
1,697
0.041937
#-*- coding: utf-8 -*- from django import forms from django.db.models import Q from nom.models import soluciones, estados, ciudades class data_form(forms.Form): state_choices = [ ('0', 'Escoge un estado'), ] + [(edo.id, edo.estado) for edo in estados.objects.all()] city_choices = [ ('0', 'Escoge una ciudad') ] #tec...
hoiceField( choices = state_choices, label = 'Estado' ) city = forms.ChoiceField( choices = city_choices, label = 'Ciudad' ) #nfloor = forms.ChoiceField( choices = nfloor_choices, label =
'Total de pisos' ) #house_part = forms.ChoiceField( choices = house_part_choices, label = 'Parte de la casa' ) #ubication = forms.ChoiceField( choices = ubication_choices, label = 'Ubicación' ) #material = forms.ChoiceField( choices = material_choices, label = 'Material' ) #area = forms.FloatField(label = "Área", m...
rspavel/spack
var/spack/repos/builtin/packages/libint/package.py
Python
lgpl-2.1
7,364
0.001358
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import os from spack import * TUNE_VARIANTS = ( 'none', 'cp2k-lmax-4', 'cp2k-lmax-5', 'cp2k-lmax-6', ...
licts('tune={0}'.format(tvariant), when='@:2.5.99', msg=('for versions prior to 2.6, tuning for specific' 'codes/configurations is not supported')) def url_for_version(self, version): base_url = "https://github.com/evaleev/libint/archive" if version == Versi...
e_url) elif version < Version('2.1.0'): return "{0}/release-{1}.tar.gz".format(base_url, version.dashed) else: return "{0}/v{1}.tar.gz".format(base_url, version) def autoreconf(self, spec, prefix): libtoolize() aclocal('-I', 'lib/autoconf') autoconf()...
SANDAG/pandana
pandana/testing.py
Python
agpl-3.0
129
0
import os import pytest skipiftravis = pytest.mar
k.skipif( os.environ.get('TRAVIS') == 'true', reason='skip on Travis-CI'
)
aglassman/beer
django_beer/django_beer/tests.py
Python
gpl-2.0
1,261
0.037272
from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import force_authenticate
from rest_framework.test import APITestCase from rest_framework.test import APIRequestFactory from beer_api.models import * class TestGlassTypePost(APITestCase): def test_auth_fail(self): u
rl = '/glass_types/' data = { 'glass_type': 'Mug', 'description': 'A cup with a handle.' } response = self.client.post(url,data,format='json') self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) self.assertEqual(response.data['detail'], 'Authentication credentials were n...
BennerLab/atg
tests/test_alignment_helper.py
Python
gpl-3.0
5,435
0.004416
import pytest import os import sys import shlex from atg.util import align BOWTIE2_LOG = os.path.join(os.path.dirname(__file__), 'data', 'bowtie2_SE.log') KALLISTO_LOG = os.path.join(os.path.dirname(__file__), 'data', 'kallisto_run.json') class TestSTARCommand: def test_star_arg_parsing(self): arguments ...
put == correct_output def test_log_parsing(self):
log_series = align.KallistoAligner.parse_log(KALLISTO_LOG) assert log_series['n_unique'] == 16090035 assert log_series['n_processed'] == 44891704 assert log_series['n_pseudoaligned'] == 36521130
elba7r/frameworking
frappe/installer.py
Python
mit
12,017
0.026213
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt # called from wnf.py # lib/wnf.py --install [rootpassword] [dbname] [source] from __future__ import unicode_literals import os, json, sys, subprocess, shutil import frappe import frappe.database import getpass import ...
"doctype": "Patch Log", "patch": patch }).insert(ignore_permissions=True) frappe.db.commit() def init_singles(): singles = [single['name'] for single in frappe.get_all("DocType", filters={'issingle': True})] for single in singles: if not frappe.db.get_singles_dict(single): doc = frappe.new_doc(single)...
None): site = frappe.local.site make_site_config(db_name, db_password, site_config) sites_path = frappe.local.sites_path frappe.destroy() frappe.init(site, sites_path=sites_path) def make_site_config(db_name=None, db_password=None, site_config=None): frappe.create_folder(os.path.join(frappe.local.site_path)) si...
nlucent/flansible
Flansible/flansible/__init__.py
Python
mit
2,810
0.005338
import platform import os import time import sys import json from threading import Thread from subprocess import Popen, PIPE import subprocess from Queue import Queue, Empty from datetime import datetime from ConfigParser import SafeConfigParser from flask import render_template from flask import Flask, request, rend...
ot") playbook_filter = config.get("Default", "playbook_filter") task_timeout = int(str_task_timeout) api = swagger.docs(Api(app), apiVersion='0.1') celery = Celery(app.name, broker=app.config['broker_url'], backend=app.config['result_backend']) celery.control.time_limit('do_long_running_task', soft=900, hard=900, rep...
nventory): if username == "admin": return True result = False with open("rbac.json") as rbac_file: rbac_data = json.load(rbac_file) user_list = rbac_data['rbac'] for user in user_list: if user['user'] == username: inventory_list = user['inventories'] i...
andreasscalas/dappforum
samples/vote.py
Python
mit
734
0.023161
#!/usr/bin/python3 # Copyright (c) 2015 Davide Gessa # Distr
ibuted under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from libcontractvm import Wallet, WalletExplorer, ConsensusManager from forum import ForumManager import sys import time consMan = ConsensusManager.ConsensusManager () consMan.bootstrap ("h...
he id of the poll: ') choice = input ('Insert the choice for the poll: ') try: print ('Broadcasted:', srMan.vote (pollid, choice)) except: print ('Error.')
cuescience/cuescience-shop
shop/tests/support/model_support.py
Python
mit
1,689
0.007697
from cuescience_shop.models import Client, Address, Order from natspec_utils.decorators import TextSyntax from cart.cart import Cart from django.test.client import Client as TestClient class ClientTestSupport(object): def __init__(self, test_case): self.test_case = test_case self.client = TestClie...
, first_name, last_name, address): client = Client(first_name=first_name, last_name=last_name, shipping_address=address, billing_address=address) client.save() return client @TextSyntax("Create order", types=["Client"], return_type="Order") def create_order(self, client): ca...
Assert client number is #1", types=["str", "Client"]) def assert_client_number(self, client_number, client): self.test_case.assertEqual(client_number, client.client_number) @TextSyntax("Assert order number is #1", types=["str", "Order"]) def assert_order_number(self, order_number, order): ...
tigeral/polygon
python/code_troopers/model/ActionType.py
Python
unlicense
217
0.004608
class ActionType: END_TURN = 0 MOVE = 1 SHOOT = 2 RAISE_STANCE = 3 LOWER_STANCE = 4 THROW_GRENADE = 5 USE
_MEDIKIT = 6 EAT_FIELD_RATION = 7 HEAL
= 8 REQUEST_ENEMY_DISPOSITION = 9
McIntyre-Lab/papers
fear_sem_sd_2015/scripts/ggm_graph_network_neighborhoods.py
Python
lgpl-3.0
7,295
0.006717
#!/usr/bin/env python import os import logging import numpy as np import networkx as nx import matplotlib.pyplot as plt import pickle def setLogger(fname,loglevel): """ Function to handle error logging """ logging.basicConfig(filename=fname, filemode='w', level=loglevel, format='%(asctime)s - %(levelname)s - ...
"" Write output CSV """ prim = '|'.join([str(x) for x in primary]) sec = '|'.join([str(x)
for x in secondary]) pSet = '|'.join([str(x) for x in sexPrim]) sSet = '|'.join([str(x) for x in sexSec]) handle.write("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}\n".format(gene, prim, sec, pSet, sSet, numPrimary, numSecondary, numPrimEnrich, numSecEnrich, numEnrich)) if __name__ == "__main__": lnam...
WZQ1397/automatic-repo
python/modules/ForgeryPyGenerateVirtualData.py
Python
lgpl-3.0
706
0.048159
from forgery_py import * for x in range(20): randPerson=name.first_name(),name.last_name(),personal.gender(),name.location(),address.phone() randCV=lorem_ipsum.title(),lorem_ipsum.sentence() randAddr=address.city(),address.state(),address.country(),address.continent() randEmail=internet.email_address(
) randColor=basic.hex_color() randComment=basic.text(200) randDate=date.date() print("name: {}\n gender: {}\n home: {}\n phone: {}\n email: {}". format(randPerson[:2],randPerson[2],randPerson[3],randPerson[4],randEmail)) print(f" CV: {randCV}") print(f" favourite color: {randColor}") print(f" comm...
))
josircg/raizcidadanista
raizcidadanista/filebrowser/views.py
Python
gpl-3.0
127
0.015748
# As
of version 3.4, all views moved to FileBrowserSite class in filebrowser.sites # This file wil
l be removed with version 3.6
rodrigoasmacedo/PySPED
pysped/cte/__init__.py
Python
lgpl-2.1
3,165
0
# -*- coding: utf-8 -*- # # PySPED - Python libraries to deal with Brazil's SPED Project # # Copyright (C) 2010-2012 # Copyright (C) Aristides Caldeira <aristides.caldeira at tauga.com.br> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Library General Public Lic...
ira <aristides.caldeira arroba tauga.com.br> # # E
ste programa é um software livre: você pode redistribuir e/ou modificar # este programa sob os termos da licença GNU Library General Public License, # publicada pela Free Software Foundation, em sua versão 2.1 ou, de acordo # com sua opção, qualquer versão posterior. # # Este programa é distribuido na esperança de que ...
ambitioninc/django-smart-manager
smart_manager/base.py
Python
mit
1,637
0.004276
from copy import deepcopy from manager_utils import upsert class BaseSmartManager(object): def __init__(self, template): self._template = deepcopy(template) self._built_objs = set() @property def built_objs(self): return self._built_objs def build_obj(self, model_class, is_d...
Builds objects using another builder and a template. Adds the resulting built objects from that builder to the built objects of this builder. """ smart_manager = smart_manager_class(template) built_objs = smart_manager.build() self._built_objs |=
smart_manager.built_objs # make sure build objs is a list or tuple if type(built_objs) not in (list, tuple,): built_objs = [built_objs] return built_objs def build(self): """ All builders must implement the build function, which returns the built object. All bu...
mornelon/QtCreator_compliments
tests/system/suite_APTW/tst_APTW01/test.py
Python
lgpl-2.1
449
0.004454
source("../.
./shared/qtcreator.py") source("../../shared/suites_qtta.py") source("../shared/aptw.py") # test New Qt Gui Application build and run for release and debug option def main(): startApplication("qtcreator" + SettingsPath) checkedTargets = createProject_Qt_GUI
(tempDir(), "SampleApp") # run project for debug and release and verify results runVerify(checkedTargets) #close Qt Creator invokeMenuItem("File", "Exit")
google/intellij-community
python/helpers/pydev/_pydevd_bundle/pydevd_constants.py
Python
apache-2.0
15,389
0.004809
''' This module holds the constants used for specifying the states of the debugger. ''' from __future__ import nested_scopes import platform import sys # Note: the sys import must be here anyways (others depend on it) STATE_RUN = 1 STATE_SUSPEND = 2 PYTHON_SUSPEND = 1 DJANGO_SUSPEND = 2 JINJA2_SUSPEND = 3 JUPYTER_SU...
import platform python_implementation = platform.python_implementation() except: pass else: if python_implementation == 'CPython' and not IS_PYTHON_STACKLESS:
# Only available for CPython! if ( (sys.version_info[0] == 2 and sys.version_info[1] >= 7) or (sys.version_info[0] == 3 and sys.version_info[1] >= 5) or (sys.version_info[0] > 3) ): # Supported in 2.7 or 3.5 onwards (32 or 64) CYTHON_S...
foxscotch/advent-of-code
2020/19/p1.py
Python
mit
2,106
0.00095
# Python 3.8.3 import re class Rule: PATTERN = re.compile(r"(\d+): (\d+|\"[ab]\")( \d+)?(?: \| (\d+)( \d+)?)?") RULES = {} def __init__(self, string): match = self.PATTERN.match(string) self.id = int(match.group(1)) self.RULES[self.id] = self if match.group(2).isnumeric...
= f.read().split("\n\n") yield [Rule(s) for s in rules.splitlines()] yield messages.splitlines() def main(): rules, messages = get_input() pattern = re.compile(Rule.RULES[0].construct_pattern()) total = 0 for message in messages: if pattern.fullmatch(message): tot...
return total if __name__ == "__main__": import time start = time.perf_counter() print(main()) print(time.perf_counter() - start)
dailin/wesnoth
scons/boost.py
Python
gpl-2.0
6,468
0.008349
# vi: syntax=python:et:ts=4 from config_check_utils import find_include from os.path import join, dirname, basename from glob import glob import re def find_boost(env): prefixes = [env["prefix"], "C:\\Boost"] crosscompile = env["host"] include = find_include(prefixes, "boost/config.hpp", default_prefixes=n...
**) { } \n""" test_program += """ int main() { } \n""" if context.TryLink(test_program, ".cpp"): context.Result("yes") return True else: context.Result("no") env.Replace(**backup) return False def CheckBoos
tIostreamsGZip(context): env = context.env backup = env.Clone().Dictionary() context.Message("Checking for gzip support in Boost Iostreams... ") test_program = """ #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filter/gzip.hpp> int main() { ...
jreback/pandas
pandas/tests/arrays/sparse/test_arithmetics.py
Python
bsd-3-clause
20,217
0.000544
import operator import numpy as np import pytest from pandas.compat.numpy import _np_version_under1p20 import pandas as pd import pandas._testing as tm from pandas.core import ops from pandas.core.arrays.sparse import SparseArray, SparseDtype @pytest.fixture(params=["integer", "block"]) def kind(request): """k...
self._check_bool_result(a >
b) self._assert((a > b).to_dense(), a_dense > b_dense) self._check_bool_result(a < b) self._assert((a < b).to_dense(), a_dense < b_dense) # sparse & dense self._check_bool_result(a == b_dense) self._assert((a == b_dense).to_dense(), a_dense == b_...
nedlowe/amaas-core-sdk-python
amaascore/transactions/enums.py
Python
apache-2.0
767
0.006519
from __future__ import absolute_import, division, print_function, unicode_literals CASH_TRANSACTION_TYPES = {'Cashflow', 'Coupon', 'Dividend', 'Payment'} TRANSACTION_TYPES = {'Allocation', 'Block', 'Exercise', 'Expiry',
'Journal', 'Maturity', 'Net', 'Novation', 'Split', 'Trade', 'Transfer'} | CASH_TRANSACTION_TYPES TRANSACTION_INVESTOR_ACTIONS = {'Subscription', 'Rede
mption'} TRANSACTION_LIFECYCLE_ACTIONS = {'Acquire', 'Remove'} TRANSACTION_ACTIONS = {'Buy', 'Sell', 'Short Sell', 'Deliver', 'Receive'} | TRANSACTION_LIFECYCLE_ACTIONS | \ TRANSACTION_INVESTOR_ACTIONS TRANSACTION_CANCEL_STATUSES = {'Cancelled', 'Netted', 'Novated'} TRANSACTION_STATUSES = {'New', ...
lukefi/missamustikka
backend/generateGeotiff.py
Python
mit
2,298
0.012185
# This script generates GeoTiff files based Corine land cover data # Usage: python generateGeotiff.py berryName # berryName is optional. If not provided all output layers are generated. # Licensed under the MIT license from osgeo import gdal, ogr, gdalconst import sys gdal.UseExceptions() gdal.AllRegister() # Paths ...
"][36] = 80 corineToBerryIndex["vadelma"][35] = 60 # Normalize values so that the highest value in output is always 100 normalizationFactor = 100.0 / 80.0 srcDs = gdal.Open(src_filename) corineBand =
srcDs.GetRasterBand(1) xSize = corineBand.XSize ySize = corineBand.YSize print "Input raster size is ", xSize, ySize for berry in berries: driver = srcDs.GetDriver() dstDs = driver.Create(dstPath + "/" + berry + ".tif", xSize, ySize, 1, gdal.GDT_UInt16, options = ['COMPRESS=LZW']) dstDs.SetGeoTransform(srcDs.GetGe...
matejd11/birthdayNotify
birthdayNotify/group.py
Python
mit
1,058
0.009452
import json class Group(object): order = ["name", "facebook", "sms", "mail", "show"] def __init__(self, name, eventsAtr): self.name = name self.eventsAtr = eventsAtr def convert(self): dictionary = {} dictionary["name"] = se...
if dictionary[self.order[atr]] != "": dictionary[self.order[atr]] += ", "+self.eventsAtr[eventAtr].even
t.shortcut else: dictionary[self.order[atr]] = self.eventsAtr[eventAtr].event.shortcut return dictionary def __str__(self): me = self.convert() return str(json.dumps(me, sort_keys = True, indent = 4))
geimer/easybuild-easyblocks
easybuild/easyblocks/g/geant4.py
Python
gpl-2.0
25,334
0.006237
## # Copyright 2009-2013 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en), # the Hercules foundation (htt...
ARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with EasyBuild. If not, see <http://www.gnu.org/licenses/>. ## """ Geant4 support, i...
jn De Weirdt (Ghent University) @author: Dries Verdegem (Ghent University) @author: Kenneth Hoste (Ghent University) @author: Pieter De Baets (Ghent University) @author: Jens Timmerman (Ghent University) """ import os import shutil import re from distutils.version import LooseVersion import easybuild.tools.environmen...
lazlolazlolazlo/onionshare
test/test_onionshare_settings.py
Python
gpl-3.0
5,868
0
""" OnionShare | https://onionshare.org/ Copyright (C) 2017 Micah Lee <micah@micahflee.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any l...
ings() assert (obj.filename == '~/Library/Application Support/OnionShare/onionshare.json') def test_filename_linux( self, custom_version, monkeypatch, os_pa
th_expanduser, platform_linux): obj = settings.Settings() assert obj.filename == '~/.config/onionshare/onionshare.json' def test_filename_windows( self, custom_version, monkeypatch, platform_windows): monkeypatch.setenv('APPDATA', ...
msifuentes/pynet_ansible
test_python/netmiko_wk4_ex7.py
Python
apache-2.0
1,955
0.01023
#!/usr/bin/env python #Import libraries from netmiko import ConnectHandler from getpass import getpass #define variables for the connection to network devices ip_addr = '50.76.53.27' username = 'pyclass' password = getpass() portpy2 = 8022 portsrx = 9822 cisco = 'cisco_ios' juniper = 'juniper' #create a dictionary ...
ing # print pynetrtr1 print pynetrtr2 # print juniper_srx #This uses makes the connection to the network devices defined. #the ** is used to help pass all the dictionary information alone # rtr1 = ConnectHandler(**pynetrtr1) rtr2 = ConnectHandler(**pynetrtr2) # srx = ConnectHandler(**juniper_srx) #this output wi
ll confirm that the connection was made with netmiko and the ssh information used to make the connection # print rtr1 print rtr2 # print srx #this will place rtr2 into config mode and will display the output to confirm we are in that mode. rtr2.config_mode() outp_show = rtr2.find_prompt() print outp_show #then we wi...
xiskoct/Meraki
python-2.7/get-vlans.py
Python
gpl-3.0
3,070
0.011401
#!/usr/bin/env python2.7 # # Aaron Blair # RIoT Solutions # # aaron@aaronpb.me # # get-vlans.py - A simple Python script to get VLANs from Appliance Networks # 15/03/2017 import argparse import csv import pprint import requests import signal import sys import json count = 0 checknet = 0 paramslist = [] vlanoutput = ...
ORG where you would like to get the VLANs for') args = parser.parse_args() #get the organization-name where the networks have to be updated as an argument org=args.ORGName #exit cleanly for SIGINT/Ctrl+C def signal_handler(signal, frame): print("\n***Interrupt!*** ---> Exiting ...") sys.exit(0) signal.signal(...
vReader = csv.reader(csvFile) #loop through the rows in the csvReader object and create a new list (paramslist) of JSON formatted attributes for row in csvReader: NetworkId = str(row[0]) params = NetworkId paramslist.append(params) #get all of the orgs this API key has access to orgsjson = requests.get(or...
benglard/Rhetorical-Analysis
AnaphoraFinder.py
Python
mit
1,934
0.007756
from nltk import word_tokenize class AnaphoraFinder: def __init__(self): self.f = "" self.counter = 0 self.first_word = "" self.b = False #Path is inputted from AIPController #Returns anaphora counter def sendFile(self, path): self.f = open(path) ...
else: try: self.first_word = word_tokenize(line)[0].lower() except: continue self.counter += self.get_all_anaphora(line) except: continue
c = self.counter self.counter = 0 return c #Returns the length of an array which contains all #instances of anaphora def get_all_anaphora(self, line): ana = [] for w in word_tokenize(line)[1:]: try: new_word = self.get_next_word(line, w).low...
mbakthav/artos
PyARTOS/GUI/CameraSampler.py
Python
gpl-3.0
16,231
0.016881
"""Provides the CameraSampleDialog class which creates a window for capturing samples with a camera.""" try: # Python 3 import tkinter as Tkinter from tkinter import N, E, S, W from tkinter import ttk from tkinter import messagebox as tkMessageBox except: # Python 2 import Tkinter...
self.lblInstructions = Tkinter.Message(self, textvariable = self.instructions, justify = 'center') self.lblInstructions.grid(column = 0, row = 0, columnspan = 3, padx = 20) # Label for video stream self.lblVideo = ttk.Label(self, b
ackground = '#000000') self.lblVideo.grid(column = 0, row = 1, columnspan = 3, padx = 20) # Controls at the bottom self.btnCancel = ttk.Button(self, text = 'Cancel', command = self.cancel) self.btnCancel.grid(column = 0, row = 2, sticky = W, padx = 20) self.btnCapt...
halbbob/dff
api/events/__init__.py
Python
gpl-2.0
617
0.003241
# DFF -- An Open Source Digital Forensics Framework # Copyright (C) 2009-2011 ArxSys # This program is free software, distributed under the terms of # the GNU General Public License Version 2. See the LICENSE file # at the top of the source tree. # # See http://www.digital-forensic.org for more information about this...
ng lists # and I
RC channels for your use. # # Author(s): # Frederic Baguelin <fba@digital-forensic.org> __version__ = "${API_EVENT_VERSION}" __all__ = ["libevents"]
thunderhoser/GewitterGefahr
gewittergefahr/gg_utils/conus_boundary_test.py
Python
mit
2,046
0.000489
"""Unit tests for conus_boundary.py.""" import unittest import numpy from gewittergefahr.gg_utils import conus_boundary QUERY_LATITUDES_DEG = numpy.array([ 33.7, 42.6, 39.7, 34.9, 40.2, 33.6, 36.4, 35.1, 30.8, 47.4, 44.2, 45.1, 49.6, 38.9, 35.0, 38.1, 40.7, 47.1, 30.2, 39.2 ])
QUERY_LONGITUDES_DEG = numpy.array([ 276.3, 282.7, 286.6, 287.5, 271.0, 266.4, 258.3, 257.3, 286.8, 235.0, 273.5, 262.5, 277.2, 255.3, 271.8, 254.3, 262.1, 247.8, 262.9, 251.6 ]) IN_CONUS_FLAGS = numpy.array( [1, 1,
0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1], dtype=bool ) class ConusBoundaryTests(unittest.TestCase): """Each method is a unit test for conus_boundary.py.""" def test_find_points_in_conus_no_shortcuts(self): """Ensures correct output from find_points_in_conus. In this case, does n...
hfp/tensorflow-xsmm
tensorflow/contrib/tpu/python/tpu/session_support.py
Python
apache-2.0
15,206
0.005393
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2
.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License....
handling session logging and shutdown notifications.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import threading import time from google.protobuf import text_format from tensorflow.contrib.tpu.python.ops import tpu_ops from tensorflow.core.protobu...
cookinrelaxin/stupendousML
multiple_regression.py
Python
mit
6,194
0.029706
from matplotlib import pyplot as plt import random from math import sqrt, log def read_csv(file_name): with open(file_name, 'r') as f: data = [] attribute_names = {index:name for index,name in enumerate(f.readline().strip().split(','))} while True: line = f.readline() if not line: return data else: ...
test_data], output, simple_weights) plt.scatter([point[variable] for point in train_data], [point['price'] for point in train_data], s=1, alpha=.01) max_x
= max([point[variable] for point in train_data]) max_y = max([point['price'] for point in train_data]) xs = [] ys = [] segment_count = 1000 for i in range(segment_count): x = i*(10.0 / segment_count) xs.append(x) y = dot([x**i for i in range(degree)], simple_weights) #print x,y ys.append(y) # ys.append...
ericflo/awesomestream
awesomestream/repl.py
Python
bsd-3-clause
391
0.007673
import code import sys from awesomestream.jsonrpc import Client def main(): try: host = sys.argv[1] ex
cept IndexError: host = 'http://localhost:9997/' banner = """>>> from awesomestream.jsonrpc import Client >>> c = Client('%s')""" % (host,) c = Client(host) code.interact(banner, local={'Client': Client, 'c': c}) if __
name__ == '__main__': main()
twisted/mantissa
xmantissa/test/historic/test_developerapplication1to2.py
Python
mit
449
0.004454
fr
om axiom.test.historic import stubloader from xmantissa.webadmin import DeveloperApplication from xmantissa.webapp import PrivateApplication class DATestCase(stubloader.StubbedTest): def testUpgrade(self): """ Ensure upgraded fields refer to correct items. """ self.assertEqual(self....
self.store.findUnique(PrivateApplication))
arielj/danceinstitute
models/installment.py
Python
gpl-2.0
8,146
0.021728
#!/usr/local/bin/python # -*- coding: utf-8 -*- import re from datetime import datetime, date from decimal import Decimal from translations import _t, _a from model import Model from lib.query_builder import Query from lib.money import Money import payment import membership import package import settings class Instal...
self._status = 'paid_with_interes
ts' else: self._status = 'paid' self.save() def get_student_id(self): s = self.get_student() return s.id if s else None def get_student(self): return self.membership.student def payments_details(self): return "\n".join(map(lambda p: p.to_s(), self.payments)) def build_payme...
ivanromakh/openprocurement.tender.limited
setup.py
Python
apache-2.0
1,687
0.000593
from setuptools import setup, find_packages import os version = '2.3.14' requires = [ 'setuptools', 'openprocurement.api>=2.3', 'openprocurement.tender.openua', ] test_requires = requires + [ 'webtest', 'python-coveralls', ] docs_requires = requires + [ 'sphinxcontrib-httpdomain', ] entry_p...
services", author='Quintagroup, Ltd.', author_email='inf
o@quintagroup.com', url='https://github.com/openprocurement/openprocurement.tender.limited', license='Apache License 2.0', packages=find_packages(exclude=['ez_setup']), namespace_packages=['openprocurement', 'openprocurement.tender'], include_package_data=True, zip_safe=False, ...
rohitranjan1991/home-assistant
homeassistant/components/broadlink/const.py
Python
mit
728
0
"""Constants.""" from homeassistant.const import Platform DOMAIN = "broadlink" DOMAINS_AND_TYPES = { Platform.REMOTE: {"RM4MINI", "RM4PRO", "RMMINI", "RMMINIB", "RMPRO"}, Platform.SENSOR: {
"A1", "RM4MINI",
"RM4PRO", "RMPRO", "SP2S", "SP3S", "SP4", "SP4B", }, Platform.SWITCH: { "BG1", "MP1", "RM4MINI", "RM4PRO", "RMMINI", "RMMINIB", "RMPRO", "SP1", "SP2", "SP2S", "SP3", "...
brettchien/PyBLEWrapper
pyble/osx/IOBluetooth.py
Python
mit
2,261
0.000885
import objc # Load IOBluetooth objc.loadBundle('IOBluetooth', globals(), bundle_path=objc.pathForFramework("IOBluetooth.framework")) # IOBluetooth CBCentralManager state CONSTS CBCentralManagerStateUnkown = 0 CBCentralManagerStateResetting = 1 CBCentralManagerStateUnsupported = 2 CBCentralManagerState...
ientAuthentication = 0x05 CBATTErrorRequestNotSupported = 0x06 CBATTErrorInvalidOffset = 0x07 CBATTErrorInsufficientAuthorization = 0x08 CBATTErrorPrepareQueueFull = 0x09 CBATTErrorAttributeNotFound = 0x0A CBATTErrorAttributeNotLong = 0x0B CBATTErrorInsufficientEncryptionKeySize = 0x0C CBATTErrorInvalidAttributeValueLe...
CBATTErrorUnlikelyError = 0x0E CBATTErrorInsufficientEncription = 0x0F CBATTErrorUnsupportedGroupType = 0x10 CBATTErrorInsufficientResources = 0x11
Joble/CumulusCI
cumulusci/core/keychain.py
Python
bsd-3-clause
12,877
0.002485
import base64 import json import os import pickle from Crypto import Random from Crypto.Cipher import AES from cumulusci.core.config import BaseConfig from cumulusci.core.config import ConnectedAppOAuthConfig from cumulusci.core.config import OrgConfig from cumulusci.core.config import ScratchOrgConfig from cumulusci...
orgs = {} for org_name in self.list_orgs(): orgs[org_name] = self.get_org(org_name) self.key = key if connected_app: self.set_connected_app(connect
ed_app) if orgs: for org_name, org_config in orgs.items(): self.set_org(org_name, org_config) if services: for service_name, service_config in services.items(): self.set_service(service_name, service_config) def set_connected_app(self, app_c...
sesh/flexx
setup.py
Python
bsd-2-clause
2,298
0.000435
# -*- coding: utf-8 -*- """ Flexx setup script. """ import os from os import path as op try: # use setuptools namespace, allows for "develop" import setuptools # noqa, analysis:ignore except ImportError: pass # it's not essential for installation from distutils.core import setup name = 'flexx' descrip...
e :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS :: MacOS X', 'Operating System ::
Microsoft :: Windows', 'Operating System :: POSIX', 'Programming Language :: Python', #'Programming Language :: Python :: 2.7', # not yet supported 'Programming Language :: Python :: 3.4', ], )
AndKe/MAVProxy
MAVProxy/modules/mavproxy_link.py
Python
gpl-3.0
44,637
0.003562
#!/usr/bin/env python '''enable run-time addition and removal of master link, just like --master on the cnd line''' ''' TO USE: link add 10.11.12.13:14550 link list link remove 3 # to remove 3rd output ''' from pymavlink import mavutil import time, struct, math, sys, fnmatch, traceback, json, os from...
self.cmd_link_list() elif args[0] == "hl": self.cmd_hl(args[1:]) elif args[0] == "dataratelogging": self.cmd_dl(args[1:]) elif args[0] == "add": if len(args) != 2: print("Usage: link add LINK") print('Usage: e.g. link add 127.0....
9876:{"label":"rfd900"}') return self.cmd_link_add(args[1:]) elif args[0] == "attributes": if len(args) != 3: print("Usage: link attributes LINK ATTRIBUTES") print('Usage: e.g. link attributes rfd900 {"label":"bob"}') return...
olivierdalang/stdm
third_party/sqlalchemy/engine/url.py
Python
gpl-2.0
8,113
0.000123
# engine/url.py # Copyright (C) 2005-2014 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """Provides the :class:`~sqlalchemy.engine.url.URL` class which encapsulates i...
he host. :param port: The port number. :param database: The database name. :param query: A dictionary of options to be passed to the dialect and/or the DBAPI upon connect. """ def __init__(se
lf, drivername, username=None, password=None, host=None, port=None, database=None, query=None): self.drivername = drivername self.username = username self.password = password self.host = host if port is not None: self.port = int(port) ...
tekton/django_react
django_react/urls.py
Python
mit
924
0
"""django_react URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Clas...
d an import: from blog import urls as blog_urls 2. Import the include() function: from django.conf.urls import url
, include 3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import url, include from django.contrib import admin import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r"^$", views.index), url(r"^comments", include("comments.urls")) ]
jokeregistry/jokeregistryweb
jokeregistryweb/claims/models.py
Python
gpl-2.0
1,263
0.000792
from django.db i
mport models from jokeregistryweb.jokes.models import Joke class Claim(models.Model): '''A claim of prior art (or infringement)''' FILED = 0 APPROVED = 1 REJECTED = 2 STATUS_CHOICES = ( (FILED, 'Filed'), (APPROVED, 'Approved'), (REJECTED, 'Rejected') ) infringing...
els.ForeignKey( 'jokes.Joke', related_name='infringed_claim', help_text='The original joke') text = models.TextField(help_text='additional detail', null=True, blank=True) status = models.IntegerField(choices=STATUS_CHOICES, default=FILED) created = models.DateTimeField(auto_now_add=...
Comunitea/CMNT_004_15
project-addons/purchase_order_import_ubl/tests/test_ubl_order_import.py
Python
agpl-3.0
1,222
0
# © 2016-2017 Akretion (Alexis de Lattre <alexis.delattre@akretion.com>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo.tests.common import TransactionCase from odoo.tools import file_open i
mport base64 class TestUblOrderImport(TransactionCase): def test_ubl_order_import(self): tests = { 'quote-PO00004.pdf': { 'po_to_update': self.env.ref('purchase.purchase_order_4'), 'incoterm': self.env.ref('stock.incoterm_DDU'), },
} poio = self.env['purchase.order.import'] for filename, res in tests.iteritems(): po = res['po_to_update'] f = file_open( 'purchase_order_import_ubl/tests/files/' + filename, 'rb') quote_file = f.read() wiz = poio.with_context( ...
msreis/SigNetSim
signetsim/tests/test_project.py
Python
agpl-3.0
4,292
0.018406
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2014-2017 Vincent Noel (vincent.noel@butantan.gov.br) # # This file is part of libSigNetSim. # # libSigNetSim 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 Fou...
', 'id': project.id }) self.assertEqual(response_copy_project.status_code, 200) self.assertEqual(len(Project.objects.filter(user=user)), 2) other_project = None for t_project in Project.objects.filter(user=user): if t_project != project: other_project = t_project self.assertEqual(other_project....
nse_delete_project = c.post('/', { 'action': 'delete_folder', 'id': other_project.id }) self.assertEqual(response_delete_project.status_code, 200) self.assertEqual(len(Project.objects.filter(user=user)), 1) self.assertEqual(Project.objects.filter(user=user)[0], project) user_2 = User.objects.filter(us...
funkotron/django-lean
setup.py
Python
bsd-3-clause
2,630
0.001901
# -*- coding: utf-8 -*- """A/B Testing for Django django-lean allows you to perform split-test experiments on your users. In brief, this involves exposing 50% of your users to one implementation and 50% to another, then comparing the performance of these two groups with regards to certain metrics. """ from distutil...
ngo_lean.lean_retention.tests', 'django_lean.lean_segments', 'django_lean.lean_segments.management', 'django_lean.lean_segments.management.commands', ], package_data={ 'django_lean.experiments': ['media/experiments/*.js', 'templates/experiments...
'templates/experiments/include/*.html'], 'django_lean.experiments.tests': ['data/*.json'], }, install_requires=['django >= 1.0'], tests_require=['BeautifulSoup', 'mox'], )
FredrikAppelros/ransac
test.py
Python
mit
1,575
0.006984
#! /usr/bin/env python import numpy as np import gc import matplotlib.pyplot as plt from random import seed, sample, randint from ransac import LineModel, ransac from time import time random_seed = 0 num_iterations = 100 num_samples = 1000 noise_ratio = 0.8 num_noise = int(noise_ratio * num_sampl...
except ValueError: pass end_time = time() mean_time = (end_time - start_time) / num_iterations gc.enable() def summary(): if params: print ' Parameters '.center(40, '=') print params print ' Residual '.center(40, '=') print residual print ' Time '.ce...
X, Y, 'k-') else: print 'RANSAC failed to find a sufficiently good fit for the data.' plt.show() if __name__ == '__main__': setup() run() summary()
pol3waf/svgEd
svged/test/random_draw_test.py
Python
gpl-2.0
213
0.032864
## # This
test shall
simply spawn random shapes and print them to a svg file. ## from svged import shapes def run(): print(shapes.writeHeader()) print(shapes.line(10,10,200,200)) print(shapes.writeEnd())
vorushin/FamilyFeed
settings.py
Python
mit
5,785
0.001556
# Django settings for FamilyFeed project. import os.path PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', '...
A_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') ...
TATIC_URL = '/static/' COFFEESCRIPT_OUTPUT_DIR = 'coffee' # URL prefix for admin static files -- CSS, JavaScript and images. # Make sure to use a trailing slash. # Examples: "http://foo.com/static/admin/", "/static/admin/". ADMIN_MEDIA_PREFIX = '/admin/media/' # Additional locations of static files STATICFILES_DIRS ...
rosskarchner/wendy_lucy
wendy_lucy/storybits/urls.py
Python
gpl-3.0
332
0.003012
from django.conf.urls import url from django.views.generic.base import RedirectView from .views import SceneView, PoiView urlpatterns = [ url(r'^$', RedirectView.as_view(url='/1')), url(r'^(?P<pk>\d+)/$', SceneView.as_view(), name='detail'), url(r'^(?
P<scene_pk>\d+)/(?P<tag>.+)/$', PoiView.as_view(), name
='poi'), ]
Cnlouds/pentest
sshbrute/Util.py
Python
mit
1,119
0.01966
''' Created on Aug 25, 2011 @author: r4stl1n ''' def fileContentsToList(fileName): lineList = [] try: fileParser = open(fileName, 'r') except IOError: print "[!] Could not open file %s " % fileName except: print "[!] Could not access file %s" % fileN...
print "[!] Could not access file %s" % fileName for line in fileParser.
readlines(): newLine = line.replace('\n', '') newTuple = (newLine[:line.find(':')],newLine[line.find(':')+1:]) tupleList.append(newTuple) return tupleList def appendLineToFile(line,filename): fileHandler = open(filename,"a+") fileHandler.write(line + "\n") fileHandler.c...
dya2/python-for-android
python3-alpha/python3-src/Lib/profile.py
Python
apache-2.0
22,537
0.001686
#! /usr/bin/env python3 # # Class for profiling python code. rev 1.0 6/2/94 # # Written by James Roskind # Based on prior profile module by Sjoerd Mullender... # which was hacked somewhat by: Guido van Rossum """Class for profiling Python code.""" # Copyright Disney Enterprises, Inc.
All Rights Reserved. # Licensed to PSF under a Contributor Agreement # # 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 app...
. See the License for the specific language # governing permissions and limitations under the License. import sys import os import time import marshal from optparse import OptionParser __all__ = ["run", "runctx", "Profile"] # Sample timer for use with #i_count = 0 #def integer_timer(): # global i_count # ...